]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - include/clang/AST/Decl.h
Update clang to 84175.
[FreeBSD/FreeBSD.git] / 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
23 namespace clang {
24 class Expr;
25 class FunctionTemplateDecl;
26 class Stmt;
27 class CompoundStmt;
28 class StringLiteral;
29 class TemplateArgumentList;
30 class MemberSpecializationInfo;
31 class FunctionTemplateSpecializationInfo;
32 class TypeLoc;
33
34 /// \brief A container of type source information.
35 ///
36 /// A client can read the relevant info using TypeLoc wrappers, e.g:
37 /// @code
38 /// TypeLoc TL = DeclaratorInfo->getTypeLoc();
39 /// if (PointerLoc *PL = dyn_cast<PointerLoc>(&TL))
40 ///   PL->getStarLoc().print(OS, SrcMgr);
41 /// @endcode
42 ///
43 class DeclaratorInfo {
44   QualType Ty;
45   // Contains a memory block after the class, used for type source information,
46   // allocated by ASTContext.
47   friend class ASTContext;
48   DeclaratorInfo(QualType ty) : Ty(ty) { }
49 public:
50   /// \brief Return the TypeLoc wrapper for the type source info.
51   TypeLoc getTypeLoc() const;
52 };
53
54 /// TranslationUnitDecl - The top declaration context.
55 class TranslationUnitDecl : public Decl, public DeclContext {
56   ASTContext &Ctx;
57
58   explicit TranslationUnitDecl(ASTContext &ctx)
59     : Decl(TranslationUnit, 0, SourceLocation()),
60       DeclContext(TranslationUnit),
61       Ctx(ctx) {}
62 public:
63   ASTContext &getASTContext() const { return Ctx; }
64
65   static TranslationUnitDecl *Create(ASTContext &C);
66   // Implement isa/cast/dyncast/etc.
67   static bool classof(const Decl *D) { return D->getKind() == TranslationUnit; }
68   static bool classof(const TranslationUnitDecl *D) { return true; }
69   static DeclContext *castToDeclContext(const TranslationUnitDecl *D) {
70     return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D));
71   }
72   static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) {
73     return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC));
74   }
75 };
76
77 /// NamedDecl - This represents a decl with a name.  Many decls have names such
78 /// as ObjCMethodDecl, but not @class, etc.
79 class NamedDecl : public Decl {
80   /// Name - The name of this declaration, which is typically a normal
81   /// identifier but may also be a special kind of name (C++
82   /// constructor, Objective-C selector, etc.)
83   DeclarationName Name;
84
85 protected:
86   NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
87     : Decl(DK, DC, L), Name(N) { }
88
89 public:
90   /// getIdentifier - Get the identifier that names this declaration,
91   /// if there is one. This will return NULL if this declaration has
92   /// no name (e.g., for an unnamed class) or if the name is a special
93   /// name (C++ constructor, Objective-C selector, etc.).
94   IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); }
95
96   /// getNameAsCString - Get the name of identifier for this declaration as a
97   /// C string (const char*).  This requires that the declaration have a name
98   /// and that it be a simple identifier.
99   const char *getNameAsCString() const {
100     assert(getIdentifier() && "Name is not a simple identifier");
101     return getIdentifier()->getName();
102   }
103
104   /// getDeclName - Get the actual, stored name of the declaration,
105   /// which may be a special name.
106   DeclarationName getDeclName() const { return Name; }
107
108   /// \brief Set the name of this declaration.
109   void setDeclName(DeclarationName N) { Name = N; }
110
111   /// getNameAsString - Get a human-readable name for the declaration, even if
112   /// it is one of the special kinds of names (C++ constructor, Objective-C
113   /// selector, etc).  Creating this name requires expensive string
114   /// manipulation, so it should be called only when performance doesn't matter.
115   /// For simple declarations, getNameAsCString() should suffice.
116   std::string getNameAsString() const { return Name.getAsString(); }
117
118   /// getQualifiedNameAsString - Returns human-readable qualified name for
119   /// declaration, like A::B::i, for i being member of namespace A::B.
120   /// If declaration is not member of context which can be named (record,
121   /// namespace), it will return same result as getNameAsString().
122   /// Creating this name is expensive, so it should be called only when
123   /// performance doesn't matter.
124   std::string getQualifiedNameAsString() const;
125   std::string getQualifiedNameAsString(const PrintingPolicy &Policy) const;
126
127   /// getNameForDiagnostic - Appends a human-readable name for this
128   /// declaration into the given string.
129   ///
130   /// This is the method invoked by Sema when displaying a NamedDecl
131   /// in a diagnostic.  It does not necessarily produce the same
132   /// result as getNameAsString(); for example, class template
133   /// specializations are printed with their template arguments.
134   ///
135   /// TODO: use an API that doesn't require so many temporary strings
136   virtual void getNameForDiagnostic(std::string &S,
137                                     const PrintingPolicy &Policy,
138                                     bool Qualified) const {
139     if (Qualified)
140       S += getQualifiedNameAsString(Policy);
141     else
142       S += getNameAsString();
143   }
144
145   /// declarationReplaces - Determine whether this declaration, if
146   /// known to be well-formed within its context, will replace the
147   /// declaration OldD if introduced into scope. A declaration will
148   /// replace another declaration if, for example, it is a
149   /// redeclaration of the same variable or function, but not if it is
150   /// a declaration of a different kind (function vs. class) or an
151   /// overloaded function.
152   bool declarationReplaces(NamedDecl *OldD) const;
153
154   /// \brief Determine whether this declaration has linkage.
155   bool hasLinkage() const;
156
157   /// \brief Looks through UsingDecls and ObjCCompatibleAliasDecls for
158   /// the underlying named decl.
159   NamedDecl *getUnderlyingDecl();
160   const NamedDecl *getUnderlyingDecl() const {
161     return const_cast<NamedDecl*>(this)->getUnderlyingDecl();
162   }
163
164   static bool classof(const Decl *D) {
165     return D->getKind() >= NamedFirst && D->getKind() <= NamedLast;
166   }
167   static bool classof(const NamedDecl *D) { return true; }
168 };
169
170 /// NamespaceDecl - Represent a C++ namespace.
171 class NamespaceDecl : public NamedDecl, public DeclContext {
172   SourceLocation LBracLoc, RBracLoc;
173
174   // For extended namespace definitions:
175   //
176   // namespace A { int x; }
177   // namespace A { int y; }
178   //
179   // there will be one NamespaceDecl for each declaration.
180   // NextNamespace points to the next extended declaration.
181   // OrigNamespace points to the original namespace declaration.
182   // OrigNamespace of the first namespace decl points to itself.
183   NamespaceDecl *OrigNamespace, *NextNamespace;
184
185   NamespaceDecl(DeclContext *DC, SourceLocation L, IdentifierInfo *Id)
186     : NamedDecl(Namespace, DC, L, Id), DeclContext(Namespace) {
187     OrigNamespace = this;
188     NextNamespace = 0;
189   }
190 public:
191   static NamespaceDecl *Create(ASTContext &C, DeclContext *DC,
192                                SourceLocation L, IdentifierInfo *Id);
193
194   virtual void Destroy(ASTContext& C);
195
196   // \brief Returns true if this is an anonymous namespace declaration.
197   //
198   // For example:
199   //   namespace {
200   //     ...
201   //   };
202   // q.v. C++ [namespace.unnamed]
203   bool isAnonymousNamespace() const {
204     return !getIdentifier();
205   }
206
207   NamespaceDecl *getNextNamespace() { return NextNamespace; }
208   const NamespaceDecl *getNextNamespace() const { return NextNamespace; }
209   void setNextNamespace(NamespaceDecl *ND) { NextNamespace = ND; }
210
211   NamespaceDecl *getOriginalNamespace() const {
212     return OrigNamespace;
213   }
214   void setOriginalNamespace(NamespaceDecl *ND) { OrigNamespace = ND; }
215
216   virtual NamespaceDecl *getCanonicalDecl() { return OrigNamespace; }
217
218   virtual SourceRange getSourceRange() const {
219     return SourceRange(getLocation(), RBracLoc);
220   }
221
222   SourceLocation getLBracLoc() const { return LBracLoc; }
223   SourceLocation getRBracLoc() const { return RBracLoc; }
224   void setLBracLoc(SourceLocation LBrace) { LBracLoc = LBrace; }
225   void setRBracLoc(SourceLocation RBrace) { RBracLoc = RBrace; }
226
227   // Implement isa/cast/dyncast/etc.
228   static bool classof(const Decl *D) { return D->getKind() == Namespace; }
229   static bool classof(const NamespaceDecl *D) { return true; }
230   static DeclContext *castToDeclContext(const NamespaceDecl *D) {
231     return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D));
232   }
233   static NamespaceDecl *castFromDeclContext(const DeclContext *DC) {
234     return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
235   }
236 };
237
238 /// ValueDecl - Represent the declaration of a variable (in which case it is
239 /// an lvalue) a function (in which case it is a function designator) or
240 /// an enum constant.
241 class ValueDecl : public NamedDecl {
242   QualType DeclType;
243
244 protected:
245   ValueDecl(Kind DK, DeclContext *DC, SourceLocation L,
246             DeclarationName N, QualType T)
247     : NamedDecl(DK, DC, L, N), DeclType(T) {}
248 public:
249   QualType getType() const { return DeclType; }
250   void setType(QualType newType) { DeclType = newType; }
251
252   // Implement isa/cast/dyncast/etc.
253   static bool classof(const Decl *D) {
254     return D->getKind() >= ValueFirst && D->getKind() <= ValueLast;
255   }
256   static bool classof(const ValueDecl *D) { return true; }
257 };
258
259 /// \brief Represents a ValueDecl that came out of a declarator.
260 /// Contains type source information through DeclaratorInfo.
261 class DeclaratorDecl : public ValueDecl {
262   DeclaratorInfo *DeclInfo;
263
264 protected:
265   DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L,
266                  DeclarationName N, QualType T, DeclaratorInfo *DInfo)
267     : ValueDecl(DK, DC, L, N, T), DeclInfo(DInfo) {}
268
269 public:
270   DeclaratorInfo *getDeclaratorInfo() const { return DeclInfo; }
271   void setDeclaratorInfo(DeclaratorInfo *DInfo) { DeclInfo = DInfo; }
272
273   SourceLocation getTypeSpecStartLoc() const;
274
275   // Implement isa/cast/dyncast/etc.
276   static bool classof(const Decl *D) {
277     return D->getKind() >= DeclaratorFirst && D->getKind() <= DeclaratorLast;
278   }
279   static bool classof(const DeclaratorDecl *D) { return true; }
280 };
281
282 /// \brief Structure used to store a statement, the constant value to
283 /// which it was evaluated (if any), and whether or not the statement
284 /// is an integral constant expression (if known).
285 struct EvaluatedStmt {
286   EvaluatedStmt() : WasEvaluated(false), CheckedICE(false), IsICE(false) { }
287
288   /// \brief Whether this statement was already evaluated.
289   bool WasEvaluated : 1;
290
291   /// \brief Whether we already checked whether this statement was an
292   /// integral constant expression.
293   bool CheckedICE : 1;
294
295   /// \brief Whether this statement is an integral constant
296   /// expression. Only valid if CheckedICE is true.
297   bool IsICE : 1;
298
299   Stmt *Value;
300   APValue Evaluated;
301 };
302
303 // \brief Describes the kind of template specialization that a
304 // particular template specialization declaration represents.
305 enum TemplateSpecializationKind {
306   /// This template specialization was formed from a template-id but
307   /// has not yet been declared, defined, or instantiated.
308   TSK_Undeclared = 0,
309   /// This template specialization was implicitly instantiated from a
310   /// template. (C++ [temp.inst]).
311   TSK_ImplicitInstantiation,
312   /// This template specialization was declared or defined by an
313   /// explicit specialization (C++ [temp.expl.spec]) or partial
314   /// specialization (C++ [temp.class.spec]).
315   TSK_ExplicitSpecialization,
316   /// This template specialization was instantiated from a template
317   /// due to an explicit instantiation declaration request
318   /// (C++0x [temp.explicit]).
319   TSK_ExplicitInstantiationDeclaration,
320   /// This template specialization was instantiated from a template
321   /// due to an explicit instantiation definition request
322   /// (C++ [temp.explicit]).
323   TSK_ExplicitInstantiationDefinition
324 };
325   
326 /// VarDecl - An instance of this class is created to represent a variable
327 /// declaration or definition.
328 class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
329 public:
330   enum StorageClass {
331     None, Auto, Register, Extern, Static, PrivateExtern
332   };
333
334   /// getStorageClassSpecifierString - Return the string used to
335   /// specify the storage class \arg SC.
336   ///
337   /// It is illegal to call this function with SC == None.
338   static const char *getStorageClassSpecifierString(StorageClass SC);
339
340 protected:
341   /// \brief Placeholder type used in Init to denote an unparsed C++ default
342   /// argument.
343   struct UnparsedDefaultArgument;
344
345   /// \brief Placeholder type used in Init to denote an uninstantiated C++
346   /// default argument.
347   struct UninstantiatedDefaultArgument;
348
349   typedef llvm::PointerUnion4<Stmt *, EvaluatedStmt *,
350                               UnparsedDefaultArgument *,
351                               UninstantiatedDefaultArgument *> InitType;
352
353   /// \brief The initializer for this variable or, for a ParmVarDecl, the
354   /// C++ default argument.
355   mutable InitType Init;
356
357 private:
358   // FIXME: This can be packed into the bitfields in Decl.
359   unsigned SClass : 3;
360   bool ThreadSpecified : 1;
361   bool HasCXXDirectInit : 1;
362
363   /// DeclaredInCondition - Whether this variable was declared in a
364   /// condition, e.g., if (int x = foo()) { ... }.
365   bool DeclaredInCondition : 1;
366
367   friend class StmtIteratorBase;
368 protected:
369   VarDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
370           QualType T, DeclaratorInfo *DInfo, StorageClass SC)
371     : DeclaratorDecl(DK, DC, L, Id, T, DInfo), Init(),
372       ThreadSpecified(false), HasCXXDirectInit(false),
373       DeclaredInCondition(false) {
374     SClass = SC;
375   }
376
377   typedef Redeclarable<VarDecl> redeclarable_base;
378   virtual VarDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
379
380 public:
381   typedef redeclarable_base::redecl_iterator redecl_iterator;
382   redecl_iterator redecls_begin() const {
383     return redeclarable_base::redecls_begin();
384   }
385   redecl_iterator redecls_end() const {
386     return redeclarable_base::redecls_end();
387   }
388
389   static VarDecl *Create(ASTContext &C, DeclContext *DC,
390                          SourceLocation L, IdentifierInfo *Id,
391                          QualType T, DeclaratorInfo *DInfo, StorageClass S);
392
393   virtual ~VarDecl();
394   virtual void Destroy(ASTContext& C);
395
396   StorageClass getStorageClass() const { return (StorageClass)SClass; }
397   void setStorageClass(StorageClass SC) { SClass = SC; }
398
399   virtual SourceRange getSourceRange() const;
400
401   const Expr *getInit() const {
402     if (Init.isNull())
403       return 0;
404
405     const Stmt *S = Init.dyn_cast<Stmt *>();
406     if (!S) {
407       if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
408         S = ES->Value;
409     }
410     return (const Expr*) S;
411   }
412   Expr *getInit() {
413     if (Init.isNull())
414       return 0;
415
416     Stmt *S = Init.dyn_cast<Stmt *>();
417     if (!S) {
418       if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
419         S = ES->Value;
420     }
421
422     return (Expr*) S;
423   }
424
425   /// \brief Retrieve the address of the initializer expression.
426   Stmt **getInitAddress() {
427     if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
428       return &ES->Value;
429
430     // This union hack tip-toes around strict-aliasing rules.
431     union {
432       InitType *InitPtr;
433       Stmt **StmtPtr;
434     };
435
436     InitPtr = &Init;
437     return StmtPtr;
438   }
439
440   void setInit(ASTContext &C, Expr *I);
441
442   /// \brief Note that constant evaluation has computed the given
443   /// value for this variable's initializer.
444   void setEvaluatedValue(ASTContext &C, const APValue &Value) const {
445     EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
446     if (!Eval) {
447       Stmt *S = Init.get<Stmt *>();
448       Eval = new (C) EvaluatedStmt;
449       Eval->Value = S;
450       Init = Eval;
451     }
452
453     Eval->WasEvaluated = true;
454     Eval->Evaluated = Value;
455   }
456
457   /// \brief Return the already-evaluated value of this variable's
458   /// initializer, or NULL if the value is not yet known.
459   APValue *getEvaluatedValue() const {
460     if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
461       if (Eval->WasEvaluated)
462         return &Eval->Evaluated;
463
464     return 0;
465   }
466
467   /// \brief Determines whether it is already known whether the
468   /// initializer is an integral constant expression or not.
469   bool isInitKnownICE() const {
470     if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
471       return Eval->CheckedICE;
472
473     return false;
474   }
475
476   /// \brief Determines whether the initializer is an integral
477   /// constant expression.
478   ///
479   /// \pre isInitKnownICE()
480   bool isInitICE() const {
481     assert(isInitKnownICE() &&
482            "Check whether we already know that the initializer is an ICE");
483     return Init.get<EvaluatedStmt *>()->IsICE;
484   }
485
486   /// \brief Note that we now know whether the initializer is an
487   /// integral constant expression.
488   void setInitKnownICE(ASTContext &C, bool IsICE) const {
489     EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
490     if (!Eval) {
491       Stmt *S = Init.get<Stmt *>();
492       Eval = new (C) EvaluatedStmt;
493       Eval->Value = S;
494       Init = Eval;
495     }
496
497     Eval->CheckedICE = true;
498     Eval->IsICE = IsICE;
499   }
500
501   /// \brief Retrieve the definition of this variable, which may come
502   /// from a previous declaration. Def will be set to the VarDecl that
503   /// contains the initializer, and the result will be that
504   /// initializer.
505   const Expr *getDefinition(const VarDecl *&Def) const;
506
507   void setThreadSpecified(bool T) { ThreadSpecified = T; }
508   bool isThreadSpecified() const {
509     return ThreadSpecified;
510   }
511
512   void setCXXDirectInitializer(bool T) { HasCXXDirectInit = T; }
513
514   /// hasCXXDirectInitializer - If true, the initializer was a direct
515   /// initializer, e.g: "int x(1);". The Init expression will be the expression
516   /// inside the parens or a "ClassType(a,b,c)" class constructor expression for
517   /// class types. Clients can distinguish between "int x(1);" and "int x=1;"
518   /// by checking hasCXXDirectInitializer.
519   ///
520   bool hasCXXDirectInitializer() const {
521     return HasCXXDirectInit;
522   }
523
524   /// isDeclaredInCondition - Whether this variable was declared as
525   /// part of a condition in an if/switch/while statement, e.g.,
526   /// @code
527   /// if (int x = foo()) { ... }
528   /// @endcode
529   bool isDeclaredInCondition() const {
530     return DeclaredInCondition;
531   }
532   void setDeclaredInCondition(bool InCondition) {
533     DeclaredInCondition = InCondition;
534   }
535
536   virtual VarDecl *getCanonicalDecl();
537
538   /// hasLocalStorage - Returns true if a variable with function scope
539   ///  is a non-static local variable.
540   bool hasLocalStorage() const {
541     if (getStorageClass() == None)
542       return !isFileVarDecl();
543
544     // Return true for:  Auto, Register.
545     // Return false for: Extern, Static, PrivateExtern.
546
547     return getStorageClass() <= Register;
548   }
549
550   /// hasExternStorage - Returns true if a variable has extern or
551   /// __private_extern__ storage.
552   bool hasExternalStorage() const {
553     return getStorageClass() == Extern || getStorageClass() == PrivateExtern;
554   }
555
556   /// hasGlobalStorage - Returns true for all variables that do not
557   ///  have local storage.  This includs all global variables as well
558   ///  as static variables declared within a function.
559   bool hasGlobalStorage() const { return !hasLocalStorage(); }
560
561   /// isBlockVarDecl - Returns true for local variable declarations.  Note that
562   /// this includes static variables inside of functions.
563   ///
564   ///   void foo() { int x; static int y; extern int z; }
565   ///
566   bool isBlockVarDecl() const {
567     if (getKind() != Decl::Var)
568       return false;
569     if (const DeclContext *DC = getDeclContext())
570       return DC->getLookupContext()->isFunctionOrMethod();
571     return false;
572   }
573
574   /// \brief Determines whether this is a static data member.
575   ///
576   /// This will only be true in C++, and applies to, e.g., the
577   /// variable 'x' in:
578   /// \code
579   /// struct S {
580   ///   static int x;
581   /// };
582   /// \endcode
583   bool isStaticDataMember() const {
584     return getDeclContext()->isRecord();
585   }
586
587   /// \brief Determine whether this is or was instantiated from an out-of-line 
588   /// definition of a static data member.
589   bool isOutOfLine() const;
590   
591   /// \brief If this variable is an instantiated static data member of a
592   /// class template specialization, returns the templated static data member
593   /// from which it was instantiated.
594   VarDecl *getInstantiatedFromStaticDataMember() const;
595
596   /// \brief If this variable is a static data member, determine what kind of 
597   /// template specialization or instantiation this is.
598   TemplateSpecializationKind getTemplateSpecializationKind() const;
599   
600   /// \brief If this variable is an instantiation of a static data member of a
601   /// class template specialization, retrieves the member specialization
602   /// information.
603   MemberSpecializationInfo *getMemberSpecializationInfo() const;
604   
605   /// \brief For a static data member that was instantiated from a static
606   /// data member of a class template, set the template specialiation kind.
607   void setTemplateSpecializationKind(TemplateSpecializationKind TSK);
608   
609   /// isFileVarDecl - Returns true for file scoped variable declaration.
610   bool isFileVarDecl() const {
611     if (getKind() != Decl::Var)
612       return false;
613     if (const DeclContext *Ctx = getDeclContext()) {
614       Ctx = Ctx->getLookupContext();
615       if (isa<TranslationUnitDecl>(Ctx) || isa<NamespaceDecl>(Ctx) )
616         return true;
617     }
618     if (isStaticDataMember())
619       return true;
620
621     return false;
622   }
623
624   /// \brief Determine whether this is a tentative definition of a
625   /// variable in C.
626   bool isTentativeDefinition(ASTContext &Context) const;
627
628   /// \brief Determines whether this variable is a variable with
629   /// external, C linkage.
630   bool isExternC() const;
631
632   // Implement isa/cast/dyncast/etc.
633   static bool classof(const Decl *D) {
634     return D->getKind() >= VarFirst && D->getKind() <= VarLast;
635   }
636   static bool classof(const VarDecl *D) { return true; }
637 };
638
639 class ImplicitParamDecl : public VarDecl {
640 protected:
641   ImplicitParamDecl(Kind DK, DeclContext *DC, SourceLocation L,
642                     IdentifierInfo *Id, QualType Tw)
643     : VarDecl(DK, DC, L, Id, Tw, /*DInfo=*/0, VarDecl::None) {}
644 public:
645   static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC,
646                                    SourceLocation L, IdentifierInfo *Id,
647                                    QualType T);
648   // Implement isa/cast/dyncast/etc.
649   static bool classof(const ImplicitParamDecl *D) { return true; }
650   static bool classof(const Decl *D) { return D->getKind() == ImplicitParam; }
651 };
652
653 /// ParmVarDecl - Represent a parameter to a function.
654 class ParmVarDecl : public VarDecl {
655   // NOTE: VC++ treats enums as signed, avoid using the ObjCDeclQualifier enum
656   /// FIXME: Also can be paced into the bitfields in Decl.
657   /// in, inout, etc.
658   unsigned objcDeclQualifier : 6;
659
660   /// \brief Retrieves the fake "value" of an unparsed
661   static Expr *getUnparsedDefaultArgValue() {
662     uintptr_t Value = (uintptr_t)-1;
663     // Mask off the low bits
664     Value &= ~(uintptr_t)0x07;
665     return reinterpret_cast<Expr*> (Value);
666   }
667
668 protected:
669   ParmVarDecl(Kind DK, DeclContext *DC, SourceLocation L,
670               IdentifierInfo *Id, QualType T, DeclaratorInfo *DInfo,
671               StorageClass S, Expr *DefArg)
672   : VarDecl(DK, DC, L, Id, T, DInfo, S), objcDeclQualifier(OBJC_TQ_None) {
673     setDefaultArg(DefArg);
674   }
675
676 public:
677   static ParmVarDecl *Create(ASTContext &C, DeclContext *DC,
678                              SourceLocation L,IdentifierInfo *Id,
679                              QualType T, DeclaratorInfo *DInfo,
680                              StorageClass S, Expr *DefArg);
681
682   ObjCDeclQualifier getObjCDeclQualifier() const {
683     return ObjCDeclQualifier(objcDeclQualifier);
684   }
685   void setObjCDeclQualifier(ObjCDeclQualifier QTVal) {
686     objcDeclQualifier = QTVal;
687   }
688
689   const Expr *getDefaultArg() const {
690     assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
691     assert(!hasUninstantiatedDefaultArg() &&
692            "Default argument is not yet instantiated!");
693     return getInit();
694   }
695   Expr *getDefaultArg() {
696     assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
697     assert(!hasUninstantiatedDefaultArg() &&
698            "Default argument is not yet instantiated!");
699     return getInit();
700   }
701   void setDefaultArg(Expr *defarg) {
702     Init = reinterpret_cast<Stmt *>(defarg);
703   }
704
705   /// \brief Retrieve the source range that covers the entire default
706   /// argument.
707   SourceRange getDefaultArgRange() const;  
708   void setUninstantiatedDefaultArg(Expr *arg) {
709     Init = reinterpret_cast<UninstantiatedDefaultArgument *>(arg);
710   }
711   Expr *getUninstantiatedDefaultArg() {
712     return (Expr *)Init.get<UninstantiatedDefaultArgument *>();
713   }
714   const Expr *getUninstantiatedDefaultArg() const {
715     return (const Expr *)Init.get<UninstantiatedDefaultArgument *>();
716   }
717
718   /// hasDefaultArg - Determines whether this parameter has a default argument,
719   /// either parsed or not.
720   bool hasDefaultArg() const {
721     return getInit() || hasUnparsedDefaultArg() ||
722       hasUninstantiatedDefaultArg();
723   }
724
725   /// hasUnparsedDefaultArg - Determines whether this parameter has a
726   /// default argument that has not yet been parsed. This will occur
727   /// during the processing of a C++ class whose member functions have
728   /// default arguments, e.g.,
729   /// @code
730   ///   class X {
731   ///   public:
732   ///     void f(int x = 17); // x has an unparsed default argument now
733   ///   }; // x has a regular default argument now
734   /// @endcode
735   bool hasUnparsedDefaultArg() const {
736     return Init.is<UnparsedDefaultArgument*>();
737   }
738
739   bool hasUninstantiatedDefaultArg() const {
740     return Init.is<UninstantiatedDefaultArgument*>();
741   }
742
743   /// setUnparsedDefaultArg - Specify that this parameter has an
744   /// unparsed default argument. The argument will be replaced with a
745   /// real default argument via setDefaultArg when the class
746   /// definition enclosing the function declaration that owns this
747   /// default argument is completed.
748   void setUnparsedDefaultArg() {
749     Init = (UnparsedDefaultArgument *)0;
750   }
751
752   QualType getOriginalType() const;
753
754   /// setOwningFunction - Sets the function declaration that owns this
755   /// ParmVarDecl. Since ParmVarDecls are often created before the
756   /// FunctionDecls that own them, this routine is required to update
757   /// the DeclContext appropriately.
758   void setOwningFunction(DeclContext *FD) { setDeclContext(FD); }
759
760   // Implement isa/cast/dyncast/etc.
761   static bool classof(const Decl *D) {
762     return (D->getKind() == ParmVar ||
763             D->getKind() == OriginalParmVar);
764   }
765   static bool classof(const ParmVarDecl *D) { return true; }
766 };
767
768 /// OriginalParmVarDecl - Represent a parameter to a function, when
769 /// the type of the parameter has been promoted. This node represents the
770 /// parameter to the function with its original type.
771 ///
772 class OriginalParmVarDecl : public ParmVarDecl {
773   friend class ParmVarDecl;
774 protected:
775   QualType OriginalType;
776 private:
777   OriginalParmVarDecl(DeclContext *DC, SourceLocation L,
778                               IdentifierInfo *Id, QualType T,
779                               DeclaratorInfo *DInfo,
780                               QualType OT, StorageClass S,
781                               Expr *DefArg)
782   : ParmVarDecl(OriginalParmVar, DC, L, Id, T, DInfo, S, DefArg),
783     OriginalType(OT) {}
784 public:
785   static OriginalParmVarDecl *Create(ASTContext &C, DeclContext *DC,
786                                      SourceLocation L,IdentifierInfo *Id,
787                                      QualType T, DeclaratorInfo *DInfo,
788                                      QualType OT, StorageClass S, Expr *DefArg);
789
790   void setOriginalType(QualType T) { OriginalType = T; }
791
792   // Implement isa/cast/dyncast/etc.
793   static bool classof(const Decl *D) { return D->getKind() == OriginalParmVar; }
794   static bool classof(const OriginalParmVarDecl *D) { return true; }
795 };
796
797 /// FunctionDecl - An instance of this class is created to represent a
798 /// function declaration or definition.
799 ///
800 /// Since a given function can be declared several times in a program,
801 /// there may be several FunctionDecls that correspond to that
802 /// function. Only one of those FunctionDecls will be found when
803 /// traversing the list of declarations in the context of the
804 /// FunctionDecl (e.g., the translation unit); this FunctionDecl
805 /// contains all of the information known about the function. Other,
806 /// previous declarations of the function are available via the
807 /// getPreviousDeclaration() chain.
808 class FunctionDecl : public DeclaratorDecl, public DeclContext,
809                      public Redeclarable<FunctionDecl> {
810 public:
811   enum StorageClass {
812     None, Extern, Static, PrivateExtern
813   };
814
815 private:
816   /// ParamInfo - new[]'d array of pointers to VarDecls for the formal
817   /// parameters of this function.  This is null if a prototype or if there are
818   /// no formals.
819   ParmVarDecl **ParamInfo;
820
821   LazyDeclStmtPtr Body;
822
823   // FIXME: This can be packed into the bitfields in Decl.
824   // NOTE: VC++ treats enums as signed, avoid using the StorageClass enum
825   unsigned SClass : 2;
826   bool IsInline : 1;
827   bool IsVirtualAsWritten : 1;
828   bool IsPure : 1;
829   bool HasInheritedPrototype : 1;
830   bool HasWrittenPrototype : 1;
831   bool IsDeleted : 1;
832   bool IsTrivial : 1; // sunk from CXXMethodDecl
833   bool IsCopyAssignment : 1;  // sunk from CXXMethodDecl
834   bool HasImplicitReturnZero : 1;
835
836   /// \brief End part of this FunctionDecl's source range.
837   ///
838   /// We could compute the full range in getSourceRange(). However, when we're
839   /// dealing with a function definition deserialized from a PCH/AST file,
840   /// we can only compute the full range once the function body has been
841   /// de-serialized, so it's far better to have the (sometimes-redundant)
842   /// EndRangeLoc.
843   SourceLocation EndRangeLoc;
844
845   /// \brief The template or declaration that this declaration
846   /// describes or was instantiated from, respectively.
847   ///
848   /// For non-templates, this value will be NULL. For function
849   /// declarations that describe a function template, this will be a
850   /// pointer to a FunctionTemplateDecl. For member functions
851   /// of class template specializations, this will be a MemberSpecializationInfo
852   /// pointer containing information about the specialization.
853   /// For function template specializations, this will be a
854   /// FunctionTemplateSpecializationInfo, which contains information about
855   /// the template being specialized and the template arguments involved in
856   /// that specialization.
857   llvm::PointerUnion3<FunctionTemplateDecl *, 
858                       MemberSpecializationInfo *,
859                       FunctionTemplateSpecializationInfo *>
860     TemplateOrSpecialization;
861
862 protected:
863   FunctionDecl(Kind DK, DeclContext *DC, SourceLocation L,
864                DeclarationName N, QualType T, DeclaratorInfo *DInfo,
865                StorageClass S, bool isInline)
866     : DeclaratorDecl(DK, DC, L, N, T, DInfo),
867       DeclContext(DK),
868       ParamInfo(0), Body(),
869       SClass(S), IsInline(isInline), 
870       IsVirtualAsWritten(false), IsPure(false), HasInheritedPrototype(false),
871       HasWrittenPrototype(true), IsDeleted(false), IsTrivial(false),
872       IsCopyAssignment(false),
873       HasImplicitReturnZero(false),
874       EndRangeLoc(L), TemplateOrSpecialization() {}
875
876   virtual ~FunctionDecl() {}
877   virtual void Destroy(ASTContext& C);
878
879   typedef Redeclarable<FunctionDecl> redeclarable_base;
880   virtual FunctionDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
881
882 public:
883   typedef redeclarable_base::redecl_iterator redecl_iterator;
884   redecl_iterator redecls_begin() const {
885     return redeclarable_base::redecls_begin();
886   }
887   redecl_iterator redecls_end() const {
888     return redeclarable_base::redecls_end();
889   }
890
891   static FunctionDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L,
892                               DeclarationName N, QualType T,
893                               DeclaratorInfo *DInfo,
894                               StorageClass S = None, bool isInline = false,
895                               bool hasWrittenPrototype = true);
896
897   virtual void getNameForDiagnostic(std::string &S,
898                                     const PrintingPolicy &Policy,
899                                     bool Qualified) const;
900
901   virtual SourceRange getSourceRange() const {
902     return SourceRange(getLocation(), EndRangeLoc);
903   }
904   void setLocEnd(SourceLocation E) {
905     EndRangeLoc = E;
906   }
907
908   /// getBody - Retrieve the body (definition) of the function. The
909   /// function body might be in any of the (re-)declarations of this
910   /// function. The variant that accepts a FunctionDecl pointer will
911   /// set that function declaration to the actual declaration
912   /// containing the body (if there is one).
913   Stmt *getBody(const FunctionDecl *&Definition) const;
914
915   virtual Stmt *getBody() const {
916     const FunctionDecl* Definition;
917     return getBody(Definition);
918   }
919
920   /// isThisDeclarationADefinition - Returns whether this specific
921   /// declaration of the function is also a definition. This does not
922   /// determine whether the function has been defined (e.g., in a
923   /// previous definition); for that information, use getBody.
924   /// FIXME: Should return true if function is deleted or defaulted. However,
925   /// CodeGenModule.cpp uses it, and I don't know if this would break it.
926   bool isThisDeclarationADefinition() const { return Body; }
927
928   void setBody(Stmt *B);
929   void setLazyBody(uint64_t Offset) { Body = Offset; }
930
931   /// Whether this function is marked as virtual explicitly.
932   bool isVirtualAsWritten() const { return IsVirtualAsWritten; }
933   void setVirtualAsWritten(bool V) { IsVirtualAsWritten = V; }
934
935   /// Whether this virtual function is pure, i.e. makes the containing class
936   /// abstract.
937   bool isPure() const { return IsPure; }
938   void setPure(bool P = true) { IsPure = P; }
939
940   /// Whether this function is "trivial" in some specialized C++ senses.
941   /// Can only be true for default constructors, copy constructors,
942   /// copy assignment operators, and destructors.  Not meaningful until
943   /// the class has been fully built by Sema.
944   bool isTrivial() const { return IsTrivial; }
945   void setTrivial(bool IT) { IsTrivial = IT; }
946
947   bool isCopyAssignment() const { return IsCopyAssignment; }
948   void setCopyAssignment(bool CA) { IsCopyAssignment = CA; }
949
950   /// Whether falling off this function implicitly returns null/zero.
951   /// If a more specific implicit return value is required, front-ends
952   /// should synthesize the appropriate return statements.
953   bool hasImplicitReturnZero() const { return HasImplicitReturnZero; }
954   void setHasImplicitReturnZero(bool IRZ) { HasImplicitReturnZero = IRZ; }
955
956   /// \brief Whether this function has a prototype, either because one
957   /// was explicitly written or because it was "inherited" by merging
958   /// a declaration without a prototype with a declaration that has a
959   /// prototype.
960   bool hasPrototype() const {
961     return HasWrittenPrototype || HasInheritedPrototype;
962   }
963
964   bool hasWrittenPrototype() const { return HasWrittenPrototype; }
965   void setHasWrittenPrototype(bool P) { HasWrittenPrototype = P; }
966
967   /// \brief Whether this function inherited its prototype from a
968   /// previous declaration.
969   bool hasInheritedPrototype() const { return HasInheritedPrototype; }
970   void setHasInheritedPrototype(bool P = true) { HasInheritedPrototype = P; }
971
972   /// \brief Whether this function has been deleted.
973   ///
974   /// A function that is "deleted" (via the C++0x "= delete" syntax)
975   /// acts like a normal function, except that it cannot actually be
976   /// called or have its address taken. Deleted functions are
977   /// typically used in C++ overload resolution to attract arguments
978   /// whose type or lvalue/rvalue-ness would permit the use of a
979   /// different overload that would behave incorrectly. For example,
980   /// one might use deleted functions to ban implicit conversion from
981   /// a floating-point number to an Integer type:
982   ///
983   /// @code
984   /// struct Integer {
985   ///   Integer(long); // construct from a long
986   ///   Integer(double) = delete; // no construction from float or double
987   ///   Integer(long double) = delete; // no construction from long double
988   /// };
989   /// @endcode
990   bool isDeleted() const { return IsDeleted; }
991   void setDeleted(bool D = true) { IsDeleted = D; }
992
993   /// \brief Determines whether this is a function "main", which is
994   /// the entry point into an executable program.
995   bool isMain() const;
996
997   /// \brief Determines whether this function is a function with
998   /// external, C linkage.
999   bool isExternC() const;
1000
1001   /// \brief Determines whether this is a global function.
1002   bool isGlobal() const;
1003
1004   void setPreviousDeclaration(FunctionDecl * PrevDecl);
1005
1006   virtual const FunctionDecl *getCanonicalDecl() const;
1007   virtual FunctionDecl *getCanonicalDecl();
1008
1009   unsigned getBuiltinID() const;
1010
1011   unsigned getNumParmVarDeclsFromType() const;
1012
1013   // Iterator access to formal parameters.
1014   unsigned param_size() const { return getNumParams(); }
1015   typedef ParmVarDecl **param_iterator;
1016   typedef ParmVarDecl * const *param_const_iterator;
1017
1018   param_iterator param_begin() { return ParamInfo; }
1019   param_iterator param_end()   { return ParamInfo+param_size(); }
1020
1021   param_const_iterator param_begin() const { return ParamInfo; }
1022   param_const_iterator param_end() const   { return ParamInfo+param_size(); }
1023
1024   /// getNumParams - Return the number of parameters this function must have
1025   /// based on its functiontype.  This is the length of the PararmInfo array
1026   /// after it has been created.
1027   unsigned getNumParams() const;
1028
1029   const ParmVarDecl *getParamDecl(unsigned i) const {
1030     assert(i < getNumParams() && "Illegal param #");
1031     return ParamInfo[i];
1032   }
1033   ParmVarDecl *getParamDecl(unsigned i) {
1034     assert(i < getNumParams() && "Illegal param #");
1035     return ParamInfo[i];
1036   }
1037   void setParams(ASTContext& C, ParmVarDecl **NewParamInfo, unsigned NumParams);
1038
1039   /// getMinRequiredArguments - Returns the minimum number of arguments
1040   /// needed to call this function. This may be fewer than the number of
1041   /// function parameters, if some of the parameters have default
1042   /// arguments (in C++).
1043   unsigned getMinRequiredArguments() const;
1044
1045   QualType getResultType() const {
1046     return getType()->getAs<FunctionType>()->getResultType();
1047   }
1048   StorageClass getStorageClass() const { return StorageClass(SClass); }
1049   void setStorageClass(StorageClass SC) { SClass = SC; }
1050
1051   bool isInline() const { return IsInline; }
1052   void setInline(bool I) { IsInline = I; }
1053
1054   bool isInlineDefinitionExternallyVisible() const;
1055                        
1056   /// isOverloadedOperator - Whether this function declaration
1057   /// represents an C++ overloaded operator, e.g., "operator+".
1058   bool isOverloadedOperator() const {
1059     return getOverloadedOperator() != OO_None;
1060   };
1061
1062   OverloadedOperatorKind getOverloadedOperator() const;
1063
1064   /// \brief If this function is an instantiation of a member function
1065   /// of a class template specialization, retrieves the function from
1066   /// which it was instantiated.
1067   ///
1068   /// This routine will return non-NULL for (non-templated) member
1069   /// functions of class templates and for instantiations of function
1070   /// templates. For example, given:
1071   ///
1072   /// \code
1073   /// template<typename T>
1074   /// struct X {
1075   ///   void f(T);
1076   /// };
1077   /// \endcode
1078   ///
1079   /// The declaration for X<int>::f is a (non-templated) FunctionDecl
1080   /// whose parent is the class template specialization X<int>. For
1081   /// this declaration, getInstantiatedFromFunction() will return
1082   /// the FunctionDecl X<T>::A. When a complete definition of
1083   /// X<int>::A is required, it will be instantiated from the
1084   /// declaration returned by getInstantiatedFromMemberFunction().
1085   FunctionDecl *getInstantiatedFromMemberFunction() const;
1086
1087   /// \brief If this function is an instantiation of a member function of a
1088   /// class template specialization, retrieves the member specialization
1089   /// information.
1090   MemberSpecializationInfo *getMemberSpecializationInfo() const;
1091                        
1092   /// \brief Specify that this record is an instantiation of the
1093   /// member function FD.
1094   void setInstantiationOfMemberFunction(FunctionDecl *FD,
1095                                         TemplateSpecializationKind TSK);
1096
1097   /// \brief Retrieves the function template that is described by this
1098   /// function declaration.
1099   ///
1100   /// Every function template is represented as a FunctionTemplateDecl
1101   /// and a FunctionDecl (or something derived from FunctionDecl). The
1102   /// former contains template properties (such as the template
1103   /// parameter lists) while the latter contains the actual
1104   /// description of the template's
1105   /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
1106   /// FunctionDecl that describes the function template,
1107   /// getDescribedFunctionTemplate() retrieves the
1108   /// FunctionTemplateDecl from a FunctionDecl.
1109   FunctionTemplateDecl *getDescribedFunctionTemplate() const {
1110     return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl*>();
1111   }
1112
1113   void setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
1114     TemplateOrSpecialization = Template;
1115   }
1116
1117   /// \brief Determine whether this function is a function template 
1118   /// specialization.
1119   bool isFunctionTemplateSpecialization() const {
1120     return getPrimaryTemplate() != 0;
1121   }
1122        
1123   /// \brief If this function is actually a function template specialization,
1124   /// retrieve information about this function template specialization. 
1125   /// Otherwise, returns NULL.
1126   FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const {
1127     return TemplateOrSpecialization.
1128              dyn_cast<FunctionTemplateSpecializationInfo*>();
1129   }
1130                        
1131   /// \brief Retrieve the primary template that this function template
1132   /// specialization either specializes or was instantiated from.
1133   ///
1134   /// If this function declaration is not a function template specialization,
1135   /// returns NULL.
1136   FunctionTemplateDecl *getPrimaryTemplate() const;
1137
1138   /// \brief Retrieve the template arguments used to produce this function
1139   /// template specialization from the primary template.
1140   ///
1141   /// If this function declaration is not a function template specialization,
1142   /// returns NULL.
1143   const TemplateArgumentList *getTemplateSpecializationArgs() const;
1144
1145   /// \brief Specify that this function declaration is actually a function
1146   /// template specialization.
1147   ///
1148   /// \param Context the AST context in which this function resides.
1149   ///
1150   /// \param Template the function template that this function template
1151   /// specialization specializes.
1152   ///
1153   /// \param TemplateArgs the template arguments that produced this
1154   /// function template specialization from the template.
1155   ///
1156   /// \param InsertPos If non-NULL, the position in the function template
1157   /// specialization set where the function template specialization data will
1158   /// be inserted.
1159   ///
1160   /// \param TSK the kind of template specialization this is.
1161   void setFunctionTemplateSpecialization(ASTContext &Context,
1162                                          FunctionTemplateDecl *Template,
1163                                       const TemplateArgumentList *TemplateArgs,
1164                                          void *InsertPos,
1165                     TemplateSpecializationKind TSK = TSK_ImplicitInstantiation);
1166
1167   /// \brief Determine what kind of template instantiation this function
1168   /// represents.
1169   TemplateSpecializationKind getTemplateSpecializationKind() const;
1170
1171   /// \brief Determine what kind of template instantiation this function
1172   /// represents.
1173   void setTemplateSpecializationKind(TemplateSpecializationKind TSK);
1174
1175   /// \brief Determine whether this is or was instantiated from an out-of-line 
1176   /// definition of a member function.
1177   bool isOutOfLine() const;
1178                        
1179   // Implement isa/cast/dyncast/etc.
1180   static bool classof(const Decl *D) {
1181     return D->getKind() >= FunctionFirst && D->getKind() <= FunctionLast;
1182   }
1183   static bool classof(const FunctionDecl *D) { return true; }
1184   static DeclContext *castToDeclContext(const FunctionDecl *D) {
1185     return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
1186   }
1187   static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
1188     return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
1189   }
1190 };
1191
1192
1193 /// FieldDecl - An instance of this class is created by Sema::ActOnField to
1194 /// represent a member of a struct/union/class.
1195 class FieldDecl : public DeclaratorDecl {
1196   // FIXME: This can be packed into the bitfields in Decl.
1197   bool Mutable : 1;
1198   Expr *BitWidth;
1199 protected:
1200   FieldDecl(Kind DK, DeclContext *DC, SourceLocation L,
1201             IdentifierInfo *Id, QualType T, DeclaratorInfo *DInfo,
1202             Expr *BW, bool Mutable)
1203     : DeclaratorDecl(DK, DC, L, Id, T, DInfo), Mutable(Mutable), BitWidth(BW) {
1204   }
1205
1206 public:
1207   static FieldDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L,
1208                            IdentifierInfo *Id, QualType T,
1209                            DeclaratorInfo *DInfo, Expr *BW, bool Mutable);
1210
1211   /// isMutable - Determines whether this field is mutable (C++ only).
1212   bool isMutable() const { return Mutable; }
1213
1214   /// \brief Set whether this field is mutable (C++ only).
1215   void setMutable(bool M) { Mutable = M; }
1216
1217   /// isBitfield - Determines whether this field is a bitfield.
1218   bool isBitField() const { return BitWidth != NULL; }
1219
1220   /// @brief Determines whether this is an unnamed bitfield.
1221   bool isUnnamedBitfield() const { return BitWidth != NULL && !getDeclName(); }
1222
1223   /// isAnonymousStructOrUnion - Determines whether this field is a
1224   /// representative for an anonymous struct or union. Such fields are
1225   /// unnamed and are implicitly generated by the implementation to
1226   /// store the data for the anonymous union or struct.
1227   bool isAnonymousStructOrUnion() const;
1228
1229   Expr *getBitWidth() const { return BitWidth; }
1230   void setBitWidth(Expr *BW) { BitWidth = BW; }
1231
1232   // Implement isa/cast/dyncast/etc.
1233   static bool classof(const Decl *D) {
1234     return D->getKind() >= FieldFirst && D->getKind() <= FieldLast;
1235   }
1236   static bool classof(const FieldDecl *D) { return true; }
1237 };
1238
1239 /// EnumConstantDecl - An instance of this object exists for each enum constant
1240 /// that is defined.  For example, in "enum X {a,b}", each of a/b are
1241 /// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
1242 /// TagType for the X EnumDecl.
1243 class EnumConstantDecl : public ValueDecl {
1244   Stmt *Init; // an integer constant expression
1245   llvm::APSInt Val; // The value.
1246 protected:
1247   EnumConstantDecl(DeclContext *DC, SourceLocation L,
1248                    IdentifierInfo *Id, QualType T, Expr *E,
1249                    const llvm::APSInt &V)
1250     : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {}
1251
1252   virtual ~EnumConstantDecl() {}
1253 public:
1254
1255   static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC,
1256                                   SourceLocation L, IdentifierInfo *Id,
1257                                   QualType T, Expr *E,
1258                                   const llvm::APSInt &V);
1259
1260   virtual void Destroy(ASTContext& C);
1261
1262   const Expr *getInitExpr() const { return (const Expr*) Init; }
1263   Expr *getInitExpr() { return (Expr*) Init; }
1264   const llvm::APSInt &getInitVal() const { return Val; }
1265
1266   void setInitExpr(Expr *E) { Init = (Stmt*) E; }
1267   void setInitVal(const llvm::APSInt &V) { Val = V; }
1268
1269   // Implement isa/cast/dyncast/etc.
1270   static bool classof(const Decl *D) { return D->getKind() == EnumConstant; }
1271   static bool classof(const EnumConstantDecl *D) { return true; }
1272
1273   friend class StmtIteratorBase;
1274 };
1275
1276
1277 /// TypeDecl - Represents a declaration of a type.
1278 ///
1279 class TypeDecl : public NamedDecl {
1280   /// TypeForDecl - This indicates the Type object that represents
1281   /// this TypeDecl.  It is a cache maintained by
1282   /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and
1283   /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl.
1284   mutable Type *TypeForDecl;
1285   friend class ASTContext;
1286   friend class DeclContext;
1287   friend class TagDecl;
1288   friend class TemplateTypeParmDecl;
1289   friend class ClassTemplateSpecializationDecl;
1290   friend class TagType;
1291
1292 protected:
1293   TypeDecl(Kind DK, DeclContext *DC, SourceLocation L,
1294            IdentifierInfo *Id)
1295     : NamedDecl(DK, DC, L, Id), TypeForDecl(0) {}
1296
1297 public:
1298   // Low-level accessor
1299   Type *getTypeForDecl() const { return TypeForDecl; }
1300   void setTypeForDecl(Type *TD) { TypeForDecl = TD; }
1301
1302   // Implement isa/cast/dyncast/etc.
1303   static bool classof(const Decl *D) {
1304     return D->getKind() >= TypeFirst && D->getKind() <= TypeLast;
1305   }
1306   static bool classof(const TypeDecl *D) { return true; }
1307 };
1308
1309
1310 class TypedefDecl : public TypeDecl {
1311   /// UnderlyingType - This is the type the typedef is set to.
1312   QualType UnderlyingType;
1313   TypedefDecl(DeclContext *DC, SourceLocation L,
1314               IdentifierInfo *Id, QualType T)
1315     : TypeDecl(Typedef, DC, L, Id), UnderlyingType(T) {}
1316
1317   virtual ~TypedefDecl() {}
1318 public:
1319
1320   static TypedefDecl *Create(ASTContext &C, DeclContext *DC,
1321                              SourceLocation L,IdentifierInfo *Id,
1322                              QualType T);
1323
1324   QualType getUnderlyingType() const { return UnderlyingType; }
1325   void setUnderlyingType(QualType newType) { UnderlyingType = newType; }
1326
1327   // Implement isa/cast/dyncast/etc.
1328   static bool classof(const Decl *D) { return D->getKind() == Typedef; }
1329   static bool classof(const TypedefDecl *D) { return true; }
1330 };
1331
1332 class TypedefDecl;
1333
1334 /// TagDecl - Represents the declaration of a struct/union/class/enum.
1335 class TagDecl
1336   : public TypeDecl, public DeclContext, public Redeclarable<TagDecl> {
1337 public:
1338   // This is really ugly.
1339   typedef ElaboratedType::TagKind TagKind;
1340   static const TagKind TK_struct = ElaboratedType::TK_struct;
1341   static const TagKind TK_union = ElaboratedType::TK_union;
1342   static const TagKind TK_class = ElaboratedType::TK_class;
1343   static const TagKind TK_enum = ElaboratedType::TK_enum;
1344
1345 private:
1346   // FIXME: This can be packed into the bitfields in Decl.
1347   /// TagDeclKind - The TagKind enum.
1348   unsigned TagDeclKind : 2;
1349
1350   /// IsDefinition - True if this is a definition ("struct foo {};"), false if
1351   /// it is a declaration ("struct foo;").
1352   bool IsDefinition : 1;
1353
1354   /// TypedefForAnonDecl - If a TagDecl is anonymous and part of a typedef,
1355   /// this points to the TypedefDecl. Used for mangling.
1356   TypedefDecl *TypedefForAnonDecl;
1357
1358   SourceLocation TagKeywordLoc;
1359   SourceLocation RBraceLoc;
1360
1361 protected:
1362   TagDecl(Kind DK, TagKind TK, DeclContext *DC, SourceLocation L,
1363           IdentifierInfo *Id, TagDecl *PrevDecl,
1364           SourceLocation TKL = SourceLocation())
1365     : TypeDecl(DK, DC, L, Id), DeclContext(DK), TypedefForAnonDecl(0),
1366       TagKeywordLoc(TKL) {
1367     assert((DK != Enum || TK == TK_enum) &&"EnumDecl not matched with TK_enum");
1368     TagDeclKind = TK;
1369     IsDefinition = false;
1370     setPreviousDeclaration(PrevDecl);
1371   }
1372
1373   typedef Redeclarable<TagDecl> redeclarable_base;
1374   virtual TagDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
1375
1376 public:
1377   typedef redeclarable_base::redecl_iterator redecl_iterator;
1378   redecl_iterator redecls_begin() const {
1379     return redeclarable_base::redecls_begin();
1380   }
1381   redecl_iterator redecls_end() const {
1382     return redeclarable_base::redecls_end();
1383   }
1384
1385   SourceLocation getRBraceLoc() const { return RBraceLoc; }
1386   void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
1387
1388   SourceLocation getTagKeywordLoc() const { return TagKeywordLoc; }
1389   void setTagKeywordLoc(SourceLocation TKL) { TagKeywordLoc = TKL; }
1390
1391   virtual SourceRange getSourceRange() const;
1392
1393   virtual TagDecl* getCanonicalDecl();
1394
1395   /// isDefinition - Return true if this decl has its body specified.
1396   bool isDefinition() const {
1397     return IsDefinition;
1398   }
1399
1400   /// \brief Whether this declaration declares a type that is
1401   /// dependent, i.e., a type that somehow depends on template
1402   /// parameters.
1403   bool isDependentType() const { return isDependentContext(); }
1404
1405   /// @brief Starts the definition of this tag declaration.
1406   ///
1407   /// This method should be invoked at the beginning of the definition
1408   /// of this tag declaration. It will set the tag type into a state
1409   /// where it is in the process of being defined.
1410   void startDefinition();
1411
1412   /// @brief Completes the definition of this tag declaration.
1413   void completeDefinition();
1414
1415   /// getDefinition - Returns the TagDecl that actually defines this
1416   ///  struct/union/class/enum.  When determining whether or not a
1417   ///  struct/union/class/enum is completely defined, one should use this method
1418   ///  as opposed to 'isDefinition'.  'isDefinition' indicates whether or not a
1419   ///  specific TagDecl is defining declaration, not whether or not the
1420   ///  struct/union/class/enum type is defined.  This method returns NULL if
1421   ///  there is no TagDecl that defines the struct/union/class/enum.
1422   TagDecl* getDefinition(ASTContext& C) const;
1423
1424   const char *getKindName() const {
1425     return ElaboratedType::getNameForTagKind(getTagKind());
1426   }
1427
1428   /// getTagKindForTypeSpec - Converts a type specifier (DeclSpec::TST)
1429   /// into a tag kind.  It is an error to provide a type specifier
1430   /// which *isn't* a tag kind here.
1431   static TagKind getTagKindForTypeSpec(unsigned TypeSpec);
1432
1433   TagKind getTagKind() const {
1434     return TagKind(TagDeclKind);
1435   }
1436
1437   void setTagKind(TagKind TK) { TagDeclKind = TK; }
1438
1439   bool isStruct() const { return getTagKind() == TK_struct; }
1440   bool isClass()  const { return getTagKind() == TK_class; }
1441   bool isUnion()  const { return getTagKind() == TK_union; }
1442   bool isEnum()   const { return getTagKind() == TK_enum; }
1443
1444   TypedefDecl *getTypedefForAnonDecl() const { return TypedefForAnonDecl; }
1445   void setTypedefForAnonDecl(TypedefDecl *TDD) { TypedefForAnonDecl = TDD; }
1446
1447   // Implement isa/cast/dyncast/etc.
1448   static bool classof(const Decl *D) {
1449     return D->getKind() >= TagFirst && D->getKind() <= TagLast;
1450   }
1451   static bool classof(const TagDecl *D) { return true; }
1452
1453   static DeclContext *castToDeclContext(const TagDecl *D) {
1454     return static_cast<DeclContext *>(const_cast<TagDecl*>(D));
1455   }
1456   static TagDecl *castFromDeclContext(const DeclContext *DC) {
1457     return static_cast<TagDecl *>(const_cast<DeclContext*>(DC));
1458   }
1459
1460   void setDefinition(bool V) { IsDefinition = V; }
1461 };
1462
1463 /// EnumDecl - Represents an enum.  As an extension, we allow forward-declared
1464 /// enums.
1465 class EnumDecl : public TagDecl {
1466   /// IntegerType - This represent the integer type that the enum corresponds
1467   /// to for code generation purposes.  Note that the enumerator constants may
1468   /// have a different type than this does.
1469   QualType IntegerType;
1470
1471   /// \brief If the enumeration was instantiated from an enumeration
1472   /// within a class or function template, this pointer refers to the
1473   /// enumeration declared within the template.
1474   EnumDecl *InstantiatedFrom;
1475
1476   EnumDecl(DeclContext *DC, SourceLocation L,
1477            IdentifierInfo *Id, EnumDecl *PrevDecl, SourceLocation TKL)
1478     : TagDecl(Enum, TK_enum, DC, L, Id, PrevDecl, TKL), InstantiatedFrom(0) {
1479       IntegerType = QualType();
1480     }
1481 public:
1482   EnumDecl *getCanonicalDecl() {
1483     return cast<EnumDecl>(TagDecl::getCanonicalDecl());
1484   }
1485
1486   static EnumDecl *Create(ASTContext &C, DeclContext *DC,
1487                           SourceLocation L, IdentifierInfo *Id,
1488                           SourceLocation TKL, EnumDecl *PrevDecl);
1489
1490   virtual void Destroy(ASTContext& C);
1491
1492   /// completeDefinition - When created, the EnumDecl corresponds to a
1493   /// forward-declared enum. This method is used to mark the
1494   /// declaration as being defined; it's enumerators have already been
1495   /// added (via DeclContext::addDecl). NewType is the new underlying
1496   /// type of the enumeration type.
1497   void completeDefinition(ASTContext &C, QualType NewType);
1498
1499   // enumerator_iterator - Iterates through the enumerators of this
1500   // enumeration.
1501   typedef specific_decl_iterator<EnumConstantDecl> enumerator_iterator;
1502
1503   enumerator_iterator enumerator_begin() const {
1504     return enumerator_iterator(this->decls_begin());
1505   }
1506
1507   enumerator_iterator enumerator_end() const {
1508     return enumerator_iterator(this->decls_end());
1509   }
1510
1511   /// getIntegerType - Return the integer type this enum decl corresponds to.
1512   /// This returns a null qualtype for an enum forward definition.
1513   QualType getIntegerType() const { return IntegerType; }
1514
1515   /// \brief Set the underlying integer type.
1516   void setIntegerType(QualType T) { IntegerType = T; }
1517
1518   /// \brief Returns the enumeration (declared within the template)
1519   /// from which this enumeration type was instantiated, or NULL if
1520   /// this enumeration was not instantiated from any template.
1521   EnumDecl *getInstantiatedFromMemberEnum() const {
1522     return InstantiatedFrom;
1523   }
1524
1525   void setInstantiationOfMemberEnum(EnumDecl *IF) { InstantiatedFrom = IF; }
1526
1527   static bool classof(const Decl *D) { return D->getKind() == Enum; }
1528   static bool classof(const EnumDecl *D) { return true; }
1529 };
1530
1531
1532 /// RecordDecl - Represents a struct/union/class.  For example:
1533 ///   struct X;                  // Forward declaration, no "body".
1534 ///   union Y { int A, B; };     // Has body with members A and B (FieldDecls).
1535 /// This decl will be marked invalid if *any* members are invalid.
1536 ///
1537 class RecordDecl : public TagDecl {
1538   // FIXME: This can be packed into the bitfields in Decl.
1539   /// HasFlexibleArrayMember - This is true if this struct ends with a flexible
1540   /// array member (e.g. int X[]) or if this union contains a struct that does.
1541   /// If so, this cannot be contained in arrays or other structs as a member.
1542   bool HasFlexibleArrayMember : 1;
1543
1544   /// AnonymousStructOrUnion - Whether this is the type of an
1545   /// anonymous struct or union.
1546   bool AnonymousStructOrUnion : 1;
1547
1548   /// HasObjectMember - This is true if this struct has at least one
1549   /// member containing an object
1550   bool HasObjectMember : 1;
1551
1552 protected:
1553   RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
1554              SourceLocation L, IdentifierInfo *Id,
1555              RecordDecl *PrevDecl, SourceLocation TKL);
1556   virtual ~RecordDecl();
1557
1558 public:
1559   static RecordDecl *Create(ASTContext &C, TagKind TK, DeclContext *DC,
1560                             SourceLocation L, IdentifierInfo *Id,
1561                             SourceLocation TKL = SourceLocation(),
1562                             RecordDecl* PrevDecl = 0);
1563
1564   virtual void Destroy(ASTContext& C);
1565
1566   bool hasFlexibleArrayMember() const { return HasFlexibleArrayMember; }
1567   void setHasFlexibleArrayMember(bool V) { HasFlexibleArrayMember = V; }
1568
1569   /// isAnonymousStructOrUnion - Whether this is an anonymous struct
1570   /// or union. To be an anonymous struct or union, it must have been
1571   /// declared without a name and there must be no objects of this
1572   /// type declared, e.g.,
1573   /// @code
1574   ///   union { int i; float f; };
1575   /// @endcode
1576   /// is an anonymous union but neither of the following are:
1577   /// @code
1578   ///  union X { int i; float f; };
1579   ///  union { int i; float f; } obj;
1580   /// @endcode
1581   bool isAnonymousStructOrUnion() const { return AnonymousStructOrUnion; }
1582   void setAnonymousStructOrUnion(bool Anon) {
1583     AnonymousStructOrUnion = Anon;
1584   }
1585
1586   bool hasObjectMember() const { return HasObjectMember; }
1587   void setHasObjectMember (bool val) { HasObjectMember = val; }
1588
1589   /// \brief Determines whether this declaration represents the
1590   /// injected class name.
1591   ///
1592   /// The injected class name in C++ is the name of the class that
1593   /// appears inside the class itself. For example:
1594   ///
1595   /// \code
1596   /// struct C {
1597   ///   // C is implicitly declared here as a synonym for the class name.
1598   /// };
1599   ///
1600   /// C::C c; // same as "C c;"
1601   /// \endcode
1602   bool isInjectedClassName() const;
1603
1604   /// getDefinition - Returns the RecordDecl that actually defines this
1605   ///  struct/union/class.  When determining whether or not a struct/union/class
1606   ///  is completely defined, one should use this method as opposed to
1607   ///  'isDefinition'.  'isDefinition' indicates whether or not a specific
1608   ///  RecordDecl is defining declaration, not whether or not the record
1609   ///  type is defined.  This method returns NULL if there is no RecordDecl
1610   ///  that defines the struct/union/tag.
1611   RecordDecl* getDefinition(ASTContext& C) const {
1612     return cast_or_null<RecordDecl>(TagDecl::getDefinition(C));
1613   }
1614
1615   // Iterator access to field members. The field iterator only visits
1616   // the non-static data members of this class, ignoring any static
1617   // data members, functions, constructors, destructors, etc.
1618   typedef specific_decl_iterator<FieldDecl> field_iterator;
1619
1620   field_iterator field_begin() const {
1621     return field_iterator(decls_begin());
1622   }
1623   field_iterator field_end() const {
1624     return field_iterator(decls_end());
1625   }
1626
1627   // field_empty - Whether there are any fields (non-static data
1628   // members) in this record.
1629   bool field_empty() const {
1630     return field_begin() == field_end();
1631   }
1632
1633   /// completeDefinition - Notes that the definition of this type is
1634   /// now complete.
1635   void completeDefinition(ASTContext& C);
1636
1637   static bool classof(const Decl *D) {
1638     return D->getKind() >= RecordFirst && D->getKind() <= RecordLast;
1639   }
1640   static bool classof(const RecordDecl *D) { return true; }
1641 };
1642
1643 class FileScopeAsmDecl : public Decl {
1644   StringLiteral *AsmString;
1645   FileScopeAsmDecl(DeclContext *DC, SourceLocation L, StringLiteral *asmstring)
1646     : Decl(FileScopeAsm, DC, L), AsmString(asmstring) {}
1647 public:
1648   static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC,
1649                                   SourceLocation L, StringLiteral *Str);
1650
1651   const StringLiteral *getAsmString() const { return AsmString; }
1652   StringLiteral *getAsmString() { return AsmString; }
1653   void setAsmString(StringLiteral *Asm) { AsmString = Asm; }
1654
1655   static bool classof(const Decl *D) {
1656     return D->getKind() == FileScopeAsm;
1657   }
1658   static bool classof(const FileScopeAsmDecl *D) { return true; }
1659 };
1660
1661 /// BlockDecl - This represents a block literal declaration, which is like an
1662 /// unnamed FunctionDecl.  For example:
1663 /// ^{ statement-body }   or   ^(int arg1, float arg2){ statement-body }
1664 ///
1665 class BlockDecl : public Decl, public DeclContext {
1666   // FIXME: This can be packed into the bitfields in Decl.
1667   bool isVariadic : 1;
1668   /// ParamInfo - new[]'d array of pointers to ParmVarDecls for the formal
1669   /// parameters of this function.  This is null if a prototype or if there are
1670   /// no formals.
1671   ParmVarDecl **ParamInfo;
1672   unsigned NumParams;
1673
1674   Stmt *Body;
1675
1676 protected:
1677   BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
1678     : Decl(Block, DC, CaretLoc), DeclContext(Block),
1679       isVariadic(false), ParamInfo(0), NumParams(0), Body(0) {}
1680
1681   virtual ~BlockDecl();
1682   virtual void Destroy(ASTContext& C);
1683
1684 public:
1685   static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L);
1686
1687   SourceLocation getCaretLocation() const { return getLocation(); }
1688
1689   bool IsVariadic() const { return isVariadic; }
1690   void setIsVariadic(bool value) { isVariadic = value; }
1691
1692   CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; }
1693   Stmt *getBody() const { return (Stmt*) Body; }
1694   void setBody(CompoundStmt *B) { Body = (Stmt*) B; }
1695
1696   // Iterator access to formal parameters.
1697   unsigned param_size() const { return getNumParams(); }
1698   typedef ParmVarDecl **param_iterator;
1699   typedef ParmVarDecl * const *param_const_iterator;
1700
1701   bool param_empty() const { return NumParams == 0; }
1702   param_iterator param_begin()  { return ParamInfo; }
1703   param_iterator param_end()   { return ParamInfo+param_size(); }
1704
1705   param_const_iterator param_begin() const { return ParamInfo; }
1706   param_const_iterator param_end() const   { return ParamInfo+param_size(); }
1707
1708   unsigned getNumParams() const;
1709   const ParmVarDecl *getParamDecl(unsigned i) const {
1710     assert(i < getNumParams() && "Illegal param #");
1711     return ParamInfo[i];
1712   }
1713   ParmVarDecl *getParamDecl(unsigned i) {
1714     assert(i < getNumParams() && "Illegal param #");
1715     return ParamInfo[i];
1716   }
1717   void setParams(ASTContext& C, ParmVarDecl **NewParamInfo, unsigned NumParams);
1718
1719   // Implement isa/cast/dyncast/etc.
1720   static bool classof(const Decl *D) { return D->getKind() == Block; }
1721   static bool classof(const BlockDecl *D) { return true; }
1722   static DeclContext *castToDeclContext(const BlockDecl *D) {
1723     return static_cast<DeclContext *>(const_cast<BlockDecl*>(D));
1724   }
1725   static BlockDecl *castFromDeclContext(const DeclContext *DC) {
1726     return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC));
1727   }
1728 };
1729
1730 /// Insertion operator for diagnostics.  This allows sending NamedDecl's
1731 /// into a diagnostic with <<.
1732 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1733                                            NamedDecl* ND) {
1734   DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND), Diagnostic::ak_nameddecl);
1735   return DB;
1736 }
1737
1738 }  // end namespace clang
1739
1740 #endif