]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - contrib/llvm/tools/clang/include/clang/AST/ASTContext.h
MFC r244628:
[FreeBSD/stable/9.git] / contrib / llvm / tools / clang / include / clang / AST / ASTContext.h
1 //===--- ASTContext.h - Context to hold long-lived AST nodes ----*- 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 /// \file
11 /// \brief Defines the clang::ASTContext interface.
12 ///
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_CLANG_AST_ASTCONTEXT_H
16 #define LLVM_CLANG_AST_ASTCONTEXT_H
17
18 #include "clang/Basic/AddressSpaces.h"
19 #include "clang/Basic/IdentifierTable.h"
20 #include "clang/Basic/LangOptions.h"
21 #include "clang/Basic/OperatorKinds.h"
22 #include "clang/Basic/PartialDiagnostic.h"
23 #include "clang/Basic/VersionTuple.h"
24 #include "clang/AST/Decl.h"
25 #include "clang/AST/LambdaMangleContext.h"
26 #include "clang/AST/NestedNameSpecifier.h"
27 #include "clang/AST/PrettyPrinter.h"
28 #include "clang/AST/TemplateName.h"
29 #include "clang/AST/Type.h"
30 #include "clang/AST/CanonicalType.h"
31 #include "clang/AST/RawCommentList.h"
32 #include "clang/AST/CommentCommandTraits.h"
33 #include "llvm/ADT/DenseMap.h"
34 #include "llvm/ADT/FoldingSet.h"
35 #include "llvm/ADT/IntrusiveRefCntPtr.h"
36 #include "llvm/ADT/OwningPtr.h"
37 #include "llvm/ADT/SmallPtrSet.h"
38 #include "llvm/ADT/TinyPtrVector.h"
39 #include "llvm/Support/Allocator.h"
40 #include <vector>
41
42 namespace llvm {
43   struct fltSemantics;
44 }
45
46 namespace clang {
47   class FileManager;
48   class ASTRecordLayout;
49   class BlockExpr;
50   class CharUnits;
51   class DiagnosticsEngine;
52   class Expr;
53   class ExternalASTSource;
54   class ASTMutationListener;
55   class IdentifierTable;
56   class SelectorTable;
57   class TargetInfo;
58   class CXXABI;
59   // Decls
60   class DeclContext;
61   class CXXConversionDecl;
62   class CXXMethodDecl;
63   class CXXRecordDecl;
64   class Decl;
65   class FieldDecl;
66   class MangleContext;
67   class ObjCIvarDecl;
68   class ObjCIvarRefExpr;
69   class ObjCPropertyDecl;
70   class ParmVarDecl;
71   class RecordDecl;
72   class StoredDeclsMap;
73   class TagDecl;
74   class TemplateTemplateParmDecl;
75   class TemplateTypeParmDecl;
76   class TranslationUnitDecl;
77   class TypeDecl;
78   class TypedefNameDecl;
79   class UsingDecl;
80   class UsingShadowDecl;
81   class UnresolvedSetIterator;
82
83   namespace Builtin { class Context; }
84
85   namespace comments {
86     class FullComment;
87   }
88
89 /// \brief Holds long-lived AST nodes (such as types and decls) that can be
90 /// referred to throughout the semantic analysis of a file.
91 class ASTContext : public RefCountedBase<ASTContext> {
92   ASTContext &this_() { return *this; }
93
94   mutable std::vector<Type*> Types;
95   mutable llvm::FoldingSet<ExtQuals> ExtQualNodes;
96   mutable llvm::FoldingSet<ComplexType> ComplexTypes;
97   mutable llvm::FoldingSet<PointerType> PointerTypes;
98   mutable llvm::FoldingSet<BlockPointerType> BlockPointerTypes;
99   mutable llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes;
100   mutable llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes;
101   mutable llvm::FoldingSet<MemberPointerType> MemberPointerTypes;
102   mutable llvm::FoldingSet<ConstantArrayType> ConstantArrayTypes;
103   mutable llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
104   mutable std::vector<VariableArrayType*> VariableArrayTypes;
105   mutable llvm::FoldingSet<DependentSizedArrayType> DependentSizedArrayTypes;
106   mutable llvm::FoldingSet<DependentSizedExtVectorType>
107     DependentSizedExtVectorTypes;
108   mutable llvm::FoldingSet<VectorType> VectorTypes;
109   mutable llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes;
110   mutable llvm::ContextualFoldingSet<FunctionProtoType, ASTContext&>
111     FunctionProtoTypes;
112   mutable llvm::FoldingSet<DependentTypeOfExprType> DependentTypeOfExprTypes;
113   mutable llvm::FoldingSet<DependentDecltypeType> DependentDecltypeTypes;
114   mutable llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes;
115   mutable llvm::FoldingSet<SubstTemplateTypeParmType>
116     SubstTemplateTypeParmTypes;
117   mutable llvm::FoldingSet<SubstTemplateTypeParmPackType>
118     SubstTemplateTypeParmPackTypes;
119   mutable llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&>
120     TemplateSpecializationTypes;
121   mutable llvm::FoldingSet<ParenType> ParenTypes;
122   mutable llvm::FoldingSet<ElaboratedType> ElaboratedTypes;
123   mutable llvm::FoldingSet<DependentNameType> DependentNameTypes;
124   mutable llvm::ContextualFoldingSet<DependentTemplateSpecializationType,
125                                      ASTContext&>
126     DependentTemplateSpecializationTypes;
127   llvm::FoldingSet<PackExpansionType> PackExpansionTypes;
128   mutable llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes;
129   mutable llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes;
130   mutable llvm::FoldingSet<AutoType> AutoTypes;
131   mutable llvm::FoldingSet<AtomicType> AtomicTypes;
132   llvm::FoldingSet<AttributedType> AttributedTypes;
133
134   mutable llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames;
135   mutable llvm::FoldingSet<DependentTemplateName> DependentTemplateNames;
136   mutable llvm::FoldingSet<SubstTemplateTemplateParmStorage> 
137     SubstTemplateTemplateParms;
138   mutable llvm::ContextualFoldingSet<SubstTemplateTemplateParmPackStorage,
139                                      ASTContext&> 
140     SubstTemplateTemplateParmPacks;
141   
142   /// \brief The set of nested name specifiers.
143   ///
144   /// This set is managed by the NestedNameSpecifier class.
145   mutable llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers;
146   mutable NestedNameSpecifier *GlobalNestedNameSpecifier;
147   friend class NestedNameSpecifier;
148
149   /// \brief A cache mapping from RecordDecls to ASTRecordLayouts.
150   ///
151   /// This is lazily created.  This is intentionally not serialized.
152   mutable llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>
153     ASTRecordLayouts;
154   mutable llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>
155     ObjCLayouts;
156
157   /// \brief A cache from types to size and alignment information.
158   typedef llvm::DenseMap<const Type*,
159                          std::pair<uint64_t, unsigned> > TypeInfoMap;
160   mutable TypeInfoMap MemoizedTypeInfo;
161
162   /// \brief A cache mapping from CXXRecordDecls to key functions.
163   llvm::DenseMap<const CXXRecordDecl*, const CXXMethodDecl*> KeyFunctions;
164   
165   /// \brief Mapping from ObjCContainers to their ObjCImplementations.
166   llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls;
167   
168   /// \brief Mapping from ObjCMethod to its duplicate declaration in the same
169   /// interface.
170   llvm::DenseMap<const ObjCMethodDecl*,const ObjCMethodDecl*> ObjCMethodRedecls;
171
172   /// \brief Mapping from __block VarDecls to their copy initialization expr.
173   llvm::DenseMap<const VarDecl*, Expr*> BlockVarCopyInits;
174     
175   /// \brief Mapping from class scope functions specialization to their
176   /// template patterns.
177   llvm::DenseMap<const FunctionDecl*, FunctionDecl*>
178     ClassScopeSpecializationPattern;
179
180   /// \brief Representation of a "canonical" template template parameter that
181   /// is used in canonical template names.
182   class CanonicalTemplateTemplateParm : public llvm::FoldingSetNode {
183     TemplateTemplateParmDecl *Parm;
184     
185   public:
186     CanonicalTemplateTemplateParm(TemplateTemplateParmDecl *Parm) 
187       : Parm(Parm) { }
188     
189     TemplateTemplateParmDecl *getParam() const { return Parm; }
190     
191     void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, Parm); }
192     
193     static void Profile(llvm::FoldingSetNodeID &ID, 
194                         TemplateTemplateParmDecl *Parm);
195   };
196   mutable llvm::FoldingSet<CanonicalTemplateTemplateParm>
197     CanonTemplateTemplateParms;
198   
199   TemplateTemplateParmDecl *
200     getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const;
201
202   /// \brief The typedef for the __int128_t type.
203   mutable TypedefDecl *Int128Decl;
204
205   /// \brief The typedef for the __uint128_t type.
206   mutable TypedefDecl *UInt128Decl;
207   
208   /// \brief The typedef for the target specific predefined
209   /// __builtin_va_list type.
210   mutable TypedefDecl *BuiltinVaListDecl;
211
212   /// \brief The typedef for the predefined \c id type.
213   mutable TypedefDecl *ObjCIdDecl;
214   
215   /// \brief The typedef for the predefined \c SEL type.
216   mutable TypedefDecl *ObjCSelDecl;
217
218   /// \brief The typedef for the predefined \c Class type.
219   mutable TypedefDecl *ObjCClassDecl;
220
221   /// \brief The typedef for the predefined \c Protocol class in Objective-C.
222   mutable ObjCInterfaceDecl *ObjCProtocolClassDecl;
223   
224   /// \brief The typedef for the predefined 'BOOL' type.
225   mutable TypedefDecl *BOOLDecl;
226
227   // Typedefs which may be provided defining the structure of Objective-C
228   // pseudo-builtins
229   QualType ObjCIdRedefinitionType;
230   QualType ObjCClassRedefinitionType;
231   QualType ObjCSelRedefinitionType;
232
233   QualType ObjCConstantStringType;
234   mutable RecordDecl *CFConstantStringTypeDecl;
235   
236   QualType ObjCNSStringType;
237
238   /// \brief The typedef declaration for the Objective-C "instancetype" type.
239   TypedefDecl *ObjCInstanceTypeDecl;
240   
241   /// \brief The type for the C FILE type.
242   TypeDecl *FILEDecl;
243
244   /// \brief The type for the C jmp_buf type.
245   TypeDecl *jmp_bufDecl;
246
247   /// \brief The type for the C sigjmp_buf type.
248   TypeDecl *sigjmp_bufDecl;
249
250   /// \brief The type for the C ucontext_t type.
251   TypeDecl *ucontext_tDecl;
252
253   /// \brief Type for the Block descriptor for Blocks CodeGen.
254   ///
255   /// Since this is only used for generation of debug info, it is not
256   /// serialized.
257   mutable RecordDecl *BlockDescriptorType;
258
259   /// \brief Type for the Block descriptor for Blocks CodeGen.
260   ///
261   /// Since this is only used for generation of debug info, it is not
262   /// serialized.
263   mutable RecordDecl *BlockDescriptorExtendedType;
264
265   /// \brief Declaration for the CUDA cudaConfigureCall function.
266   FunctionDecl *cudaConfigureCallDecl;
267
268   TypeSourceInfo NullTypeSourceInfo;
269
270   /// \brief Keeps track of all declaration attributes.
271   ///
272   /// Since so few decls have attrs, we keep them in a hash map instead of
273   /// wasting space in the Decl class.
274   llvm::DenseMap<const Decl*, AttrVec*> DeclAttrs;
275
276   /// \brief Keeps track of the static data member templates from which
277   /// static data members of class template specializations were instantiated.
278   ///
279   /// This data structure stores the mapping from instantiations of static
280   /// data members to the static data member representations within the
281   /// class template from which they were instantiated along with the kind
282   /// of instantiation or specialization (a TemplateSpecializationKind - 1).
283   ///
284   /// Given the following example:
285   ///
286   /// \code
287   /// template<typename T>
288   /// struct X {
289   ///   static T value;
290   /// };
291   ///
292   /// template<typename T>
293   ///   T X<T>::value = T(17);
294   ///
295   /// int *x = &X<int>::value;
296   /// \endcode
297   ///
298   /// This mapping will contain an entry that maps from the VarDecl for
299   /// X<int>::value to the corresponding VarDecl for X<T>::value (within the
300   /// class template X) and will be marked TSK_ImplicitInstantiation.
301   llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *> 
302     InstantiatedFromStaticDataMember;
303
304   /// \brief Keeps track of the declaration from which a UsingDecl was
305   /// created during instantiation.
306   ///
307   /// The source declaration is always a UsingDecl, an UnresolvedUsingValueDecl,
308   /// or an UnresolvedUsingTypenameDecl.
309   ///
310   /// For example:
311   /// \code
312   /// template<typename T>
313   /// struct A {
314   ///   void f();
315   /// };
316   ///
317   /// template<typename T>
318   /// struct B : A<T> {
319   ///   using A<T>::f;
320   /// };
321   ///
322   /// template struct B<int>;
323   /// \endcode
324   ///
325   /// This mapping will contain an entry that maps from the UsingDecl in
326   /// B<int> to the UnresolvedUsingDecl in B<T>.
327   llvm::DenseMap<UsingDecl *, NamedDecl *> InstantiatedFromUsingDecl;
328
329   llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>
330     InstantiatedFromUsingShadowDecl;
331
332   llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl;
333
334   /// \brief Mapping that stores the methods overridden by a given C++
335   /// member function.
336   ///
337   /// Since most C++ member functions aren't virtual and therefore
338   /// don't override anything, we store the overridden functions in
339   /// this map on the side rather than within the CXXMethodDecl structure.
340   typedef llvm::TinyPtrVector<const CXXMethodDecl*> CXXMethodVector;
341   llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector> OverriddenMethods;
342
343   /// \brief Mapping from each declaration context to its corresponding lambda 
344   /// mangling context.
345   llvm::DenseMap<const DeclContext *, LambdaMangleContext> LambdaMangleContexts;
346   
347   /// \brief Mapping that stores parameterIndex values for ParmVarDecls when
348   /// that value exceeds the bitfield size of ParmVarDeclBits.ParameterIndex.
349   typedef llvm::DenseMap<const VarDecl *, unsigned> ParameterIndexTable;
350   ParameterIndexTable ParamIndices;  
351   
352   ImportDecl *FirstLocalImport;
353   ImportDecl *LastLocalImport;
354   
355   TranslationUnitDecl *TUDecl;
356
357   /// \brief The associated SourceManager object.a
358   SourceManager &SourceMgr;
359
360   /// \brief The language options used to create the AST associated with
361   ///  this ASTContext object.
362   LangOptions &LangOpts;
363
364   /// \brief The allocator used to create AST objects.
365   ///
366   /// AST objects are never destructed; rather, all memory associated with the
367   /// AST objects will be released when the ASTContext itself is destroyed.
368   mutable llvm::BumpPtrAllocator BumpAlloc;
369
370   /// \brief Allocator for partial diagnostics.
371   PartialDiagnostic::StorageAllocator DiagAllocator;
372
373   /// \brief The current C++ ABI.
374   OwningPtr<CXXABI> ABI;
375   CXXABI *createCXXABI(const TargetInfo &T);
376
377   /// \brief The logical -> physical address space map.
378   const LangAS::Map *AddrSpaceMap;
379
380   friend class ASTDeclReader;
381   friend class ASTReader;
382   friend class ASTWriter;
383   friend class CXXRecordDecl;
384
385   const TargetInfo *Target;
386   clang::PrintingPolicy PrintingPolicy;
387   
388 public:
389   IdentifierTable &Idents;
390   SelectorTable &Selectors;
391   Builtin::Context &BuiltinInfo;
392   mutable DeclarationNameTable DeclarationNames;
393   OwningPtr<ExternalASTSource> ExternalSource;
394   ASTMutationListener *Listener;
395
396   const clang::PrintingPolicy &getPrintingPolicy() const {
397     return PrintingPolicy;
398   }
399
400   void setPrintingPolicy(const clang::PrintingPolicy &Policy) {
401     PrintingPolicy = Policy;
402   }
403   
404   SourceManager& getSourceManager() { return SourceMgr; }
405   const SourceManager& getSourceManager() const { return SourceMgr; }
406
407   llvm::BumpPtrAllocator &getAllocator() const {
408     return BumpAlloc;
409   }
410
411   void *Allocate(unsigned Size, unsigned Align = 8) const {
412     return BumpAlloc.Allocate(Size, Align);
413   }
414   void Deallocate(void *Ptr) const { }
415   
416   /// Return the total amount of physical memory allocated for representing
417   /// AST nodes and type information.
418   size_t getASTAllocatedMemory() const {
419     return BumpAlloc.getTotalMemory();
420   }
421   /// Return the total memory used for various side tables.
422   size_t getSideTableAllocatedMemory() const;
423   
424   PartialDiagnostic::StorageAllocator &getDiagAllocator() {
425     return DiagAllocator;
426   }
427
428   const TargetInfo &getTargetInfo() const { return *Target; }
429   
430   const LangOptions& getLangOpts() const { return LangOpts; }
431
432   DiagnosticsEngine &getDiagnostics() const;
433
434   FullSourceLoc getFullLoc(SourceLocation Loc) const {
435     return FullSourceLoc(Loc,SourceMgr);
436   }
437
438   /// \brief All comments in this translation unit.
439   RawCommentList Comments;
440
441   /// \brief True if comments are already loaded from ExternalASTSource.
442   mutable bool CommentsLoaded;
443
444   class RawCommentAndCacheFlags {
445   public:
446     enum Kind {
447       /// We searched for a comment attached to the particular declaration, but
448       /// didn't find any.
449       ///
450       /// getRaw() == 0.
451       NoCommentInDecl = 0,
452
453       /// We have found a comment attached to this particular declaration.
454       ///
455       /// getRaw() != 0.
456       FromDecl,
457
458       /// This declaration does not have an attached comment, and we have
459       /// searched the redeclaration chain.
460       ///
461       /// If getRaw() == 0, the whole redeclaration chain does not have any
462       /// comments.
463       ///
464       /// If getRaw() != 0, it is a comment propagated from other
465       /// redeclaration.
466       FromRedecl
467     };
468
469     Kind getKind() const LLVM_READONLY {
470       return Data.getInt();
471     }
472
473     void setKind(Kind K) {
474       Data.setInt(K);
475     }
476
477     const RawComment *getRaw() const LLVM_READONLY {
478       return Data.getPointer();
479     }
480
481     void setRaw(const RawComment *RC) {
482       Data.setPointer(RC);
483     }
484
485     const Decl *getOriginalDecl() const LLVM_READONLY {
486       return OriginalDecl;
487     }
488
489     void setOriginalDecl(const Decl *Orig) {
490       OriginalDecl = Orig;
491     }
492
493   private:
494     llvm::PointerIntPair<const RawComment *, 2, Kind> Data;
495     const Decl *OriginalDecl;
496   };
497
498   /// \brief Mapping from declarations to comments attached to any
499   /// redeclaration.
500   ///
501   /// Raw comments are owned by Comments list.  This mapping is populated
502   /// lazily.
503   mutable llvm::DenseMap<const Decl *, RawCommentAndCacheFlags> RedeclComments;
504
505   /// \brief Mapping from declarations to parsed comments attached to any
506   /// redeclaration.
507   mutable llvm::DenseMap<const Decl *, comments::FullComment *> ParsedComments;
508
509   /// \brief Return the documentation comment attached to a given declaration,
510   /// without looking into cache.
511   RawComment *getRawCommentForDeclNoCache(const Decl *D) const;
512
513 public:
514   RawCommentList &getRawCommentList() {
515     return Comments;
516   }
517
518   void addComment(const RawComment &RC) {
519     assert(LangOpts.RetainCommentsFromSystemHeaders ||
520            !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
521     Comments.addComment(RC, BumpAlloc);
522   }
523
524   /// \brief Return the documentation comment attached to a given declaration.
525   /// Returns NULL if no comment is attached.
526   ///
527   /// \param OriginalDecl if not NULL, is set to declaration AST node that had
528   /// the comment, if the comment we found comes from a redeclaration.
529   const RawComment *getRawCommentForAnyRedecl(
530                                       const Decl *D,
531                                       const Decl **OriginalDecl = NULL) const;
532
533   /// Return parsed documentation comment attached to a given declaration.
534   /// Returns NULL if no comment is attached.
535   ///
536   /// \param PP the Preprocessor used with this TU.  Could be NULL if
537   /// preprocessor is not available.
538   comments::FullComment *getCommentForDecl(const Decl *D,
539                                            const Preprocessor *PP) const;
540   
541   comments::FullComment *cloneFullComment(comments::FullComment *FC,
542                                          const Decl *D) const;
543
544 private:
545   mutable comments::CommandTraits CommentCommandTraits;
546
547 public:
548   comments::CommandTraits &getCommentCommandTraits() const {
549     return CommentCommandTraits;
550   }
551
552   /// \brief Retrieve the attributes for the given declaration.
553   AttrVec& getDeclAttrs(const Decl *D);
554
555   /// \brief Erase the attributes corresponding to the given declaration.
556   void eraseDeclAttrs(const Decl *D);
557
558   /// \brief If this variable is an instantiated static data member of a
559   /// class template specialization, returns the templated static data member
560   /// from which it was instantiated.
561   MemberSpecializationInfo *getInstantiatedFromStaticDataMember(
562                                                            const VarDecl *Var);
563
564   FunctionDecl *getClassScopeSpecializationPattern(const FunctionDecl *FD);
565
566   void setClassScopeSpecializationPattern(FunctionDecl *FD,
567                                           FunctionDecl *Pattern);
568
569   /// \brief Note that the static data member \p Inst is an instantiation of
570   /// the static data member template \p Tmpl of a class template.
571   void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
572                                            TemplateSpecializationKind TSK,
573                         SourceLocation PointOfInstantiation = SourceLocation());
574
575   /// \brief If the given using decl \p Inst is an instantiation of a
576   /// (possibly unresolved) using decl from a template instantiation,
577   /// return it.
578   NamedDecl *getInstantiatedFromUsingDecl(UsingDecl *Inst);
579
580   /// \brief Remember that the using decl \p Inst is an instantiation
581   /// of the using decl \p Pattern of a class template.
582   void setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern);
583
584   void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
585                                           UsingShadowDecl *Pattern);
586   UsingShadowDecl *getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst);
587
588   FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field);
589
590   void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl);
591   
592   /// \brief Return \c true if \p FD is a zero-length bitfield which follows
593   /// the non-bitfield \p LastFD.
594   bool ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD, 
595                                       const FieldDecl *LastFD) const;
596
597   /// \brief Return \c true if \p FD is a zero-length bitfield which follows
598   /// the bitfield \p LastFD.
599   bool ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
600                                    const FieldDecl *LastFD) const;
601   
602   /// \brief Return \c true if \p FD is a bitfield which follows the bitfield
603   /// \p LastFD.
604   bool BitfieldFollowsBitfield(const FieldDecl *FD,
605                                const FieldDecl *LastFD) const;
606   
607   /// \brief Return \c true if \p FD is not a bitfield which follows the
608   /// bitfield \p LastFD.
609   bool NonBitfieldFollowsBitfield(const FieldDecl *FD,
610                                   const FieldDecl *LastFD) const;
611   
612   /// \brief Return \c true if \p FD is a bitfield which follows the
613   /// non-bitfield \p LastFD.
614   bool BitfieldFollowsNonBitfield(const FieldDecl *FD,
615                                   const FieldDecl *LastFD) const;
616
617   // Access to the set of methods overridden by the given C++ method.
618   typedef CXXMethodVector::const_iterator overridden_cxx_method_iterator;
619   overridden_cxx_method_iterator
620   overridden_methods_begin(const CXXMethodDecl *Method) const;
621
622   overridden_cxx_method_iterator
623   overridden_methods_end(const CXXMethodDecl *Method) const;
624
625   unsigned overridden_methods_size(const CXXMethodDecl *Method) const;
626
627   /// \brief Note that the given C++ \p Method overrides the given \p
628   /// Overridden method.
629   void addOverriddenMethod(const CXXMethodDecl *Method, 
630                            const CXXMethodDecl *Overridden);
631
632   /// \brief Return C++ or ObjC overridden methods for the given \p Method.
633   ///
634   /// An ObjC method is considered to override any method in the class's
635   /// base classes, its protocols, or its categories' protocols, that has
636   /// the same selector and is of the same kind (class or instance).
637   /// A method in an implementation is not considered as overriding the same
638   /// method in the interface or its categories.
639   void getOverriddenMethods(
640                         const NamedDecl *Method,
641                         SmallVectorImpl<const NamedDecl *> &Overridden) const;
642   
643   /// \brief Notify the AST context that a new import declaration has been
644   /// parsed or implicitly created within this translation unit.
645   void addedLocalImportDecl(ImportDecl *Import);
646
647   static ImportDecl *getNextLocalImport(ImportDecl *Import) {
648     return Import->NextLocalImport;
649   }
650   
651   /// \brief Iterator that visits import declarations.
652   class import_iterator {
653     ImportDecl *Import;
654     
655   public:
656     typedef ImportDecl               *value_type;
657     typedef ImportDecl               *reference;
658     typedef ImportDecl               *pointer;
659     typedef int                       difference_type;
660     typedef std::forward_iterator_tag iterator_category;
661     
662     import_iterator() : Import() { }
663     explicit import_iterator(ImportDecl *Import) : Import(Import) { }
664     
665     reference operator*() const { return Import; }
666     pointer operator->() const { return Import; }
667     
668     import_iterator &operator++() {
669       Import = ASTContext::getNextLocalImport(Import);
670       return *this;
671     }
672
673     import_iterator operator++(int) {
674       import_iterator Other(*this);
675       ++(*this);
676       return Other;
677     }
678     
679     friend bool operator==(import_iterator X, import_iterator Y) {
680       return X.Import == Y.Import;
681     }
682
683     friend bool operator!=(import_iterator X, import_iterator Y) {
684       return X.Import != Y.Import;
685     }
686   };
687   
688   import_iterator local_import_begin() const { 
689     return import_iterator(FirstLocalImport); 
690   }
691   import_iterator local_import_end() const { return import_iterator(); }
692   
693   TranslationUnitDecl *getTranslationUnitDecl() const { return TUDecl; }
694
695
696   // Builtin Types.
697   CanQualType VoidTy;
698   CanQualType BoolTy;
699   CanQualType CharTy;
700   CanQualType WCharTy;  // [C++ 3.9.1p5], integer type in C99.
701   CanQualType WIntTy;   // [C99 7.24.1], integer type unchanged by default promotions.
702   CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99.
703   CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99.
704   CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty;
705   CanQualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy;
706   CanQualType UnsignedLongLongTy, UnsignedInt128Ty;
707   CanQualType FloatTy, DoubleTy, LongDoubleTy;
708   CanQualType HalfTy; // [OpenCL 6.1.1.1], ARM NEON
709   CanQualType FloatComplexTy, DoubleComplexTy, LongDoubleComplexTy;
710   CanQualType VoidPtrTy, NullPtrTy;
711   CanQualType DependentTy, OverloadTy, BoundMemberTy, UnknownAnyTy;
712   CanQualType BuiltinFnTy;
713   CanQualType PseudoObjectTy, ARCUnbridgedCastTy;
714   CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy;
715   CanQualType ObjCBuiltinBoolTy;
716
717   // Types for deductions in C++0x [stmt.ranged]'s desugaring. Built on demand.
718   mutable QualType AutoDeductTy;     // Deduction against 'auto'.
719   mutable QualType AutoRRefDeductTy; // Deduction against 'auto &&'.
720
721   // Type used to help define __builtin_va_list for some targets.
722   // The type is built when constructing 'BuiltinVaListDecl'.
723   mutable QualType VaListTagTy;
724
725   ASTContext(LangOptions& LOpts, SourceManager &SM, const TargetInfo *t,
726              IdentifierTable &idents, SelectorTable &sels,
727              Builtin::Context &builtins,
728              unsigned size_reserve,
729              bool DelayInitialization = false);
730
731   ~ASTContext();
732
733   /// \brief Attach an external AST source to the AST context.
734   ///
735   /// The external AST source provides the ability to load parts of
736   /// the abstract syntax tree as needed from some external storage,
737   /// e.g., a precompiled header.
738   void setExternalSource(OwningPtr<ExternalASTSource> &Source);
739
740   /// \brief Retrieve a pointer to the external AST source associated
741   /// with this AST context, if any.
742   ExternalASTSource *getExternalSource() const { return ExternalSource.get(); }
743
744   /// \brief Attach an AST mutation listener to the AST context.
745   ///
746   /// The AST mutation listener provides the ability to track modifications to
747   /// the abstract syntax tree entities committed after they were initially
748   /// created.
749   void setASTMutationListener(ASTMutationListener *Listener) {
750     this->Listener = Listener;
751   }
752
753   /// \brief Retrieve a pointer to the AST mutation listener associated
754   /// with this AST context, if any.
755   ASTMutationListener *getASTMutationListener() const { return Listener; }
756
757   void PrintStats() const;
758   const std::vector<Type*>& getTypes() const { return Types; }
759
760   /// \brief Retrieve the declaration for the 128-bit signed integer type.
761   TypedefDecl *getInt128Decl() const;
762
763   /// \brief Retrieve the declaration for the 128-bit unsigned integer type.
764   TypedefDecl *getUInt128Decl() const;
765   
766   //===--------------------------------------------------------------------===//
767   //                           Type Constructors
768   //===--------------------------------------------------------------------===//
769
770 private:
771   /// \brief Return a type with extended qualifiers.
772   QualType getExtQualType(const Type *Base, Qualifiers Quals) const;
773
774   QualType getTypeDeclTypeSlow(const TypeDecl *Decl) const;
775
776 public:
777   /// \brief Return the uniqued reference to the type for an address space
778   /// qualified type with the specified type and address space.
779   ///
780   /// The resulting type has a union of the qualifiers from T and the address
781   /// space. If T already has an address space specifier, it is silently
782   /// replaced.
783   QualType getAddrSpaceQualType(QualType T, unsigned AddressSpace) const;
784
785   /// \brief Return the uniqued reference to the type for an Objective-C
786   /// gc-qualified type.
787   ///
788   /// The retulting type has a union of the qualifiers from T and the gc
789   /// attribute.
790   QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const;
791
792   /// \brief Return the uniqued reference to the type for a \c restrict
793   /// qualified type.
794   ///
795   /// The resulting type has a union of the qualifiers from \p T and
796   /// \c restrict.
797   QualType getRestrictType(QualType T) const {
798     return T.withFastQualifiers(Qualifiers::Restrict);
799   }
800
801   /// \brief Return the uniqued reference to the type for a \c volatile
802   /// qualified type.
803   ///
804   /// The resulting type has a union of the qualifiers from \p T and
805   /// \c volatile.
806   QualType getVolatileType(QualType T) const {
807     return T.withFastQualifiers(Qualifiers::Volatile);
808   }
809
810   /// \brief Return the uniqued reference to the type for a \c const
811   /// qualified type.
812   ///
813   /// The resulting type has a union of the qualifiers from \p T and \c const.
814   ///
815   /// It can be reasonably expected that this will always be equivalent to
816   /// calling T.withConst().
817   QualType getConstType(QualType T) const { return T.withConst(); }
818
819   /// \brief Change the ExtInfo on a function type.
820   const FunctionType *adjustFunctionType(const FunctionType *Fn,
821                                          FunctionType::ExtInfo EInfo);
822
823   /// \brief Return the uniqued reference to the type for a complex
824   /// number with the specified element type.
825   QualType getComplexType(QualType T) const;
826   CanQualType getComplexType(CanQualType T) const {
827     return CanQualType::CreateUnsafe(getComplexType((QualType) T));
828   }
829
830   /// \brief Return the uniqued reference to the type for a pointer to
831   /// the specified type.
832   QualType getPointerType(QualType T) const;
833   CanQualType getPointerType(CanQualType T) const {
834     return CanQualType::CreateUnsafe(getPointerType((QualType) T));
835   }
836
837   /// \brief Return the uniqued reference to the atomic type for the specified
838   /// type.
839   QualType getAtomicType(QualType T) const;
840
841   /// \brief Return the uniqued reference to the type for a block of the
842   /// specified type.
843   QualType getBlockPointerType(QualType T) const;
844
845   /// Gets the struct used to keep track of the descriptor for pointer to
846   /// blocks.
847   QualType getBlockDescriptorType() const;
848
849   /// Gets the struct used to keep track of the extended descriptor for
850   /// pointer to blocks.
851   QualType getBlockDescriptorExtendedType() const;
852
853   void setcudaConfigureCallDecl(FunctionDecl *FD) {
854     cudaConfigureCallDecl = FD;
855   }
856   FunctionDecl *getcudaConfigureCallDecl() {
857     return cudaConfigureCallDecl;
858   }
859
860   /// Builds the struct used for __block variables.
861   QualType BuildByRefType(StringRef DeclName, QualType Ty) const;
862
863   /// Returns true iff we need copy/dispose helpers for the given type.
864   bool BlockRequiresCopying(QualType Ty) const;
865
866   /// \brief Return the uniqued reference to the type for an lvalue reference
867   /// to the specified type.
868   QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true)
869     const;
870
871   /// \brief Return the uniqued reference to the type for an rvalue reference
872   /// to the specified type.
873   QualType getRValueReferenceType(QualType T) const;
874
875   /// \brief Return the uniqued reference to the type for a member pointer to
876   /// the specified type in the specified class.
877   ///
878   /// The class \p Cls is a \c Type because it could be a dependent name.
879   QualType getMemberPointerType(QualType T, const Type *Cls) const;
880
881   /// \brief Return a non-unique reference to the type for a variable array of
882   /// the specified element type.
883   QualType getVariableArrayType(QualType EltTy, Expr *NumElts,
884                                 ArrayType::ArraySizeModifier ASM,
885                                 unsigned IndexTypeQuals,
886                                 SourceRange Brackets) const;
887
888   /// \brief Return a non-unique reference to the type for a dependently-sized
889   /// array of the specified element type.
890   ///
891   /// FIXME: We will need these to be uniqued, or at least comparable, at some
892   /// point.
893   QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
894                                       ArrayType::ArraySizeModifier ASM,
895                                       unsigned IndexTypeQuals,
896                                       SourceRange Brackets) const;
897
898   /// \brief Return a unique reference to the type for an incomplete array of
899   /// the specified element type.
900   QualType getIncompleteArrayType(QualType EltTy,
901                                   ArrayType::ArraySizeModifier ASM,
902                                   unsigned IndexTypeQuals) const;
903
904   /// \brief Return the unique reference to the type for a constant array of
905   /// the specified element type.
906   QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize,
907                                 ArrayType::ArraySizeModifier ASM,
908                                 unsigned IndexTypeQuals) const;
909   
910   /// \brief Returns a vla type where known sizes are replaced with [*].
911   QualType getVariableArrayDecayedType(QualType Ty) const;
912
913   /// \brief Return the unique reference to a vector type of the specified
914   /// element type and size.
915   ///
916   /// \pre \p VectorType must be a built-in type.
917   QualType getVectorType(QualType VectorType, unsigned NumElts,
918                          VectorType::VectorKind VecKind) const;
919
920   /// \brief Return the unique reference to an extended vector type
921   /// of the specified element type and size.
922   ///
923   /// \pre \p VectorType must be a built-in type.
924   QualType getExtVectorType(QualType VectorType, unsigned NumElts) const;
925
926   /// \pre Return a non-unique reference to the type for a dependently-sized
927   /// vector of the specified element type.
928   ///
929   /// FIXME: We will need these to be uniqued, or at least comparable, at some
930   /// point.
931   QualType getDependentSizedExtVectorType(QualType VectorType,
932                                           Expr *SizeExpr,
933                                           SourceLocation AttrLoc) const;
934
935   /// \brief Return a K&R style C function type like 'int()'.
936   QualType getFunctionNoProtoType(QualType ResultTy,
937                                   const FunctionType::ExtInfo &Info) const;
938
939   QualType getFunctionNoProtoType(QualType ResultTy) const {
940     return getFunctionNoProtoType(ResultTy, FunctionType::ExtInfo());
941   }
942
943   /// \brief Return a normal function type with a typed argument list.
944   QualType getFunctionType(QualType ResultTy,
945                            const QualType *Args, unsigned NumArgs,
946                            const FunctionProtoType::ExtProtoInfo &EPI) const;
947
948   /// \brief Return the unique reference to the type for the specified type
949   /// declaration.
950   QualType getTypeDeclType(const TypeDecl *Decl,
951                            const TypeDecl *PrevDecl = 0) const {
952     assert(Decl && "Passed null for Decl param");
953     if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
954
955     if (PrevDecl) {
956       assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
957       Decl->TypeForDecl = PrevDecl->TypeForDecl;
958       return QualType(PrevDecl->TypeForDecl, 0);
959     }
960
961     return getTypeDeclTypeSlow(Decl);
962   }
963
964   /// \brief Return the unique reference to the type for the specified
965   /// typedef-name decl.
966   QualType getTypedefType(const TypedefNameDecl *Decl,
967                           QualType Canon = QualType()) const;
968
969   QualType getRecordType(const RecordDecl *Decl) const;
970
971   QualType getEnumType(const EnumDecl *Decl) const;
972
973   QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const;
974
975   QualType getAttributedType(AttributedType::Kind attrKind,
976                              QualType modifiedType,
977                              QualType equivalentType);
978
979   QualType getSubstTemplateTypeParmType(const TemplateTypeParmType *Replaced,
980                                         QualType Replacement) const;
981   QualType getSubstTemplateTypeParmPackType(
982                                           const TemplateTypeParmType *Replaced,
983                                             const TemplateArgument &ArgPack);
984
985   QualType getTemplateTypeParmType(unsigned Depth, unsigned Index,
986                                    bool ParameterPack,
987                                    TemplateTypeParmDecl *ParmDecl = 0) const;
988
989   QualType getTemplateSpecializationType(TemplateName T,
990                                          const TemplateArgument *Args,
991                                          unsigned NumArgs,
992                                          QualType Canon = QualType()) const;
993
994   QualType getCanonicalTemplateSpecializationType(TemplateName T,
995                                                   const TemplateArgument *Args,
996                                                   unsigned NumArgs) const;
997
998   QualType getTemplateSpecializationType(TemplateName T,
999                                          const TemplateArgumentListInfo &Args,
1000                                          QualType Canon = QualType()) const;
1001
1002   TypeSourceInfo *
1003   getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc,
1004                                     const TemplateArgumentListInfo &Args,
1005                                     QualType Canon = QualType()) const;
1006
1007   QualType getParenType(QualType NamedType) const;
1008
1009   QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1010                              NestedNameSpecifier *NNS,
1011                              QualType NamedType) const;
1012   QualType getDependentNameType(ElaboratedTypeKeyword Keyword,
1013                                 NestedNameSpecifier *NNS,
1014                                 const IdentifierInfo *Name,
1015                                 QualType Canon = QualType()) const;
1016
1017   QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
1018                                                   NestedNameSpecifier *NNS,
1019                                                   const IdentifierInfo *Name,
1020                                     const TemplateArgumentListInfo &Args) const;
1021   QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
1022                                                   NestedNameSpecifier *NNS,
1023                                                   const IdentifierInfo *Name,
1024                                                   unsigned NumArgs,
1025                                             const TemplateArgument *Args) const;
1026
1027   QualType getPackExpansionType(QualType Pattern,
1028                                 llvm::Optional<unsigned> NumExpansions);
1029
1030   QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
1031                                 ObjCInterfaceDecl *PrevDecl = 0) const;
1032
1033   QualType getObjCObjectType(QualType Base,
1034                              ObjCProtocolDecl * const *Protocols,
1035                              unsigned NumProtocols) const;
1036
1037   /// \brief Return a ObjCObjectPointerType type for the given ObjCObjectType.
1038   QualType getObjCObjectPointerType(QualType OIT) const;
1039
1040   /// \brief GCC extension.
1041   QualType getTypeOfExprType(Expr *e) const;
1042   QualType getTypeOfType(QualType t) const;
1043
1044   /// \brief C++11 decltype.
1045   QualType getDecltypeType(Expr *e, QualType UnderlyingType) const;
1046
1047   /// \brief Unary type transforms
1048   QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
1049                                  UnaryTransformType::UTTKind UKind) const;
1050
1051   /// \brief C++11 deduced auto type.
1052   QualType getAutoType(QualType DeducedType) const;
1053
1054   /// \brief C++11 deduction pattern for 'auto' type.
1055   QualType getAutoDeductType() const;
1056
1057   /// \brief C++11 deduction pattern for 'auto &&' type.
1058   QualType getAutoRRefDeductType() const;
1059
1060   /// \brief Return the unique reference to the type for the specified TagDecl
1061   /// (struct/union/class/enum) decl.
1062   QualType getTagDeclType(const TagDecl *Decl) const;
1063
1064   /// \brief Return the unique type for "size_t" (C99 7.17), defined in
1065   /// <stddef.h>.
1066   ///
1067   /// The sizeof operator requires this (C99 6.5.3.4p4).
1068   CanQualType getSizeType() const;
1069
1070   /// \brief Return the unique type for "intmax_t" (C99 7.18.1.5), defined in
1071   /// <stdint.h>.
1072   CanQualType getIntMaxType() const;
1073
1074   /// \brief Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in
1075   /// <stdint.h>.
1076   CanQualType getUIntMaxType() const;
1077
1078   /// \brief In C++, this returns the unique wchar_t type.  In C99, this
1079   /// returns a type compatible with the type defined in <stddef.h> as defined
1080   /// by the target.
1081   QualType getWCharType() const { return WCharTy; }
1082
1083   /// \brief Return the type of "signed wchar_t".
1084   ///
1085   /// Used when in C++, as a GCC extension.
1086   QualType getSignedWCharType() const;
1087
1088   /// \brief Return the type of "unsigned wchar_t".
1089   ///
1090   /// Used when in C++, as a GCC extension.
1091   QualType getUnsignedWCharType() const;
1092
1093   /// \brief In C99, this returns a type compatible with the type
1094   /// defined in <stddef.h> as defined by the target.
1095   QualType getWIntType() const { return WIntTy; }
1096
1097   /// \brief Return the unique type for "ptrdiff_t" (C99 7.17) defined in
1098   /// <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1099   QualType getPointerDiffType() const;
1100
1101   /// \brief Return the unique type for "pid_t" defined in
1102   /// <sys/types.h>. We need this to compute the correct type for vfork().
1103   QualType getProcessIDType() const;
1104
1105   /// \brief Return the C structure type used to represent constant CFStrings.
1106   QualType getCFConstantStringType() const;
1107
1108   /// Get the structure type used to representation CFStrings, or NULL
1109   /// if it hasn't yet been built.
1110   QualType getRawCFConstantStringType() const {
1111     if (CFConstantStringTypeDecl)
1112       return getTagDeclType(CFConstantStringTypeDecl);
1113     return QualType();
1114   }
1115   void setCFConstantStringType(QualType T);
1116
1117   // This setter/getter represents the ObjC type for an NSConstantString.
1118   void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl);
1119   QualType getObjCConstantStringInterface() const {
1120     return ObjCConstantStringType;
1121   }
1122
1123   QualType getObjCNSStringType() const {
1124     return ObjCNSStringType;
1125   }
1126   
1127   void setObjCNSStringType(QualType T) {
1128     ObjCNSStringType = T;
1129   }
1130   
1131   /// \brief Retrieve the type that \c id has been defined to, which may be
1132   /// different from the built-in \c id if \c id has been typedef'd.
1133   QualType getObjCIdRedefinitionType() const {
1134     if (ObjCIdRedefinitionType.isNull())
1135       return getObjCIdType();
1136     return ObjCIdRedefinitionType;
1137   }
1138   
1139   /// \brief Set the user-written type that redefines \c id.
1140   void setObjCIdRedefinitionType(QualType RedefType) {
1141     ObjCIdRedefinitionType = RedefType;
1142   }
1143
1144   /// \brief Retrieve the type that \c Class has been defined to, which may be
1145   /// different from the built-in \c Class if \c Class has been typedef'd.
1146   QualType getObjCClassRedefinitionType() const {
1147     if (ObjCClassRedefinitionType.isNull())
1148       return getObjCClassType();
1149     return ObjCClassRedefinitionType;
1150   }
1151   
1152   /// \brief Set the user-written type that redefines 'SEL'.
1153   void setObjCClassRedefinitionType(QualType RedefType) {
1154     ObjCClassRedefinitionType = RedefType;
1155   }
1156
1157   /// \brief Retrieve the type that 'SEL' has been defined to, which may be
1158   /// different from the built-in 'SEL' if 'SEL' has been typedef'd.
1159   QualType getObjCSelRedefinitionType() const {
1160     if (ObjCSelRedefinitionType.isNull())
1161       return getObjCSelType();
1162     return ObjCSelRedefinitionType;
1163   }
1164
1165   
1166   /// \brief Set the user-written type that redefines 'SEL'.
1167   void setObjCSelRedefinitionType(QualType RedefType) {
1168     ObjCSelRedefinitionType = RedefType;
1169   }
1170
1171   /// \brief Retrieve the Objective-C "instancetype" type, if already known;
1172   /// otherwise, returns a NULL type;
1173   QualType getObjCInstanceType() {
1174     return getTypeDeclType(getObjCInstanceTypeDecl());
1175   }
1176
1177   /// \brief Retrieve the typedef declaration corresponding to the Objective-C
1178   /// "instancetype" type.
1179   TypedefDecl *getObjCInstanceTypeDecl();
1180   
1181   /// \brief Set the type for the C FILE type.
1182   void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; }
1183
1184   /// \brief Retrieve the C FILE type.
1185   QualType getFILEType() const {
1186     if (FILEDecl)
1187       return getTypeDeclType(FILEDecl);
1188     return QualType();
1189   }
1190
1191   /// \brief Set the type for the C jmp_buf type.
1192   void setjmp_bufDecl(TypeDecl *jmp_bufDecl) {
1193     this->jmp_bufDecl = jmp_bufDecl;
1194   }
1195
1196   /// \brief Retrieve the C jmp_buf type.
1197   QualType getjmp_bufType() const {
1198     if (jmp_bufDecl)
1199       return getTypeDeclType(jmp_bufDecl);
1200     return QualType();
1201   }
1202
1203   /// \brief Set the type for the C sigjmp_buf type.
1204   void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) {
1205     this->sigjmp_bufDecl = sigjmp_bufDecl;
1206   }
1207
1208   /// \brief Retrieve the C sigjmp_buf type.
1209   QualType getsigjmp_bufType() const {
1210     if (sigjmp_bufDecl)
1211       return getTypeDeclType(sigjmp_bufDecl);
1212     return QualType();
1213   }
1214
1215   /// \brief Set the type for the C ucontext_t type.
1216   void setucontext_tDecl(TypeDecl *ucontext_tDecl) {
1217     this->ucontext_tDecl = ucontext_tDecl;
1218   }
1219
1220   /// \brief Retrieve the C ucontext_t type.
1221   QualType getucontext_tType() const {
1222     if (ucontext_tDecl)
1223       return getTypeDeclType(ucontext_tDecl);
1224     return QualType();
1225   }
1226
1227   /// \brief The result type of logical operations, '<', '>', '!=', etc.
1228   QualType getLogicalOperationType() const {
1229     return getLangOpts().CPlusPlus ? BoolTy : IntTy;
1230   }
1231
1232   /// \brief Emit the Objective-CC type encoding for the given type \p T into
1233   /// \p S.
1234   ///
1235   /// If \p Field is specified then record field names are also encoded.
1236   void getObjCEncodingForType(QualType T, std::string &S,
1237                               const FieldDecl *Field=0) const;
1238
1239   void getLegacyIntegralTypeEncoding(QualType &t) const;
1240
1241   /// \brief Put the string version of the type qualifiers \p QT into \p S.
1242   void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
1243                                        std::string &S) const;
1244
1245   /// \brief Emit the encoded type for the function \p Decl into \p S.
1246   ///
1247   /// This is in the same format as Objective-C method encodings.
1248   ///
1249   /// \returns true if an error occurred (e.g., because one of the parameter
1250   /// types is incomplete), false otherwise.
1251   bool getObjCEncodingForFunctionDecl(const FunctionDecl *Decl, std::string& S);
1252
1253   /// \brief Emit the encoded type for the method declaration \p Decl into
1254   /// \p S.
1255   ///
1256   /// \returns true if an error occurred (e.g., because one of the parameter
1257   /// types is incomplete), false otherwise.
1258   bool getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, std::string &S,
1259                                     bool Extended = false)
1260     const;
1261
1262   /// \brief Return the encoded type for this block declaration.
1263   std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const;
1264   
1265   /// getObjCEncodingForPropertyDecl - Return the encoded type for
1266   /// this method declaration. If non-NULL, Container must be either
1267   /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
1268   /// only be NULL when getting encodings for protocol properties.
1269   void getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
1270                                       const Decl *Container,
1271                                       std::string &S) const;
1272
1273   bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
1274                                       ObjCProtocolDecl *rProto) const;
1275
1276   /// \brief Return the size of type \p T for Objective-C encoding purpose,
1277   /// in characters.
1278   CharUnits getObjCEncodingTypeSize(QualType T) const;
1279
1280   /// \brief Retrieve the typedef corresponding to the predefined \c id type
1281   /// in Objective-C.
1282   TypedefDecl *getObjCIdDecl() const;
1283   
1284   /// \brief Represents the Objective-CC \c id type.
1285   ///
1286   /// This is set up lazily, by Sema.  \c id is always a (typedef for a)
1287   /// pointer type, a pointer to a struct.
1288   QualType getObjCIdType() const {
1289     return getTypeDeclType(getObjCIdDecl());
1290   }
1291
1292   /// \brief Retrieve the typedef corresponding to the predefined 'SEL' type
1293   /// in Objective-C.
1294   TypedefDecl *getObjCSelDecl() const;
1295   
1296   /// \brief Retrieve the type that corresponds to the predefined Objective-C
1297   /// 'SEL' type.
1298   QualType getObjCSelType() const { 
1299     return getTypeDeclType(getObjCSelDecl());
1300   }
1301
1302   /// \brief Retrieve the typedef declaration corresponding to the predefined
1303   /// Objective-C 'Class' type.
1304   TypedefDecl *getObjCClassDecl() const;
1305   
1306   /// \brief Represents the Objective-C \c Class type.
1307   ///
1308   /// This is set up lazily, by Sema.  \c Class is always a (typedef for a)
1309   /// pointer type, a pointer to a struct.
1310   QualType getObjCClassType() const { 
1311     return getTypeDeclType(getObjCClassDecl());
1312   }
1313
1314   /// \brief Retrieve the Objective-C class declaration corresponding to 
1315   /// the predefined \c Protocol class.
1316   ObjCInterfaceDecl *getObjCProtocolDecl() const;
1317
1318   /// \brief Retrieve declaration of 'BOOL' typedef
1319   TypedefDecl *getBOOLDecl() const {
1320     return BOOLDecl;
1321   }
1322
1323   /// \brief Save declaration of 'BOOL' typedef
1324   void setBOOLDecl(TypedefDecl *TD) {
1325     BOOLDecl = TD;
1326   }
1327
1328   /// \brief type of 'BOOL' type.
1329   QualType getBOOLType() const {
1330     return getTypeDeclType(getBOOLDecl());
1331   }
1332   
1333   /// \brief Retrieve the type of the Objective-C \c Protocol class.
1334   QualType getObjCProtoType() const {
1335     return getObjCInterfaceType(getObjCProtocolDecl());
1336   }
1337   
1338   /// \brief Retrieve the C type declaration corresponding to the predefined
1339   /// \c __builtin_va_list type.
1340   TypedefDecl *getBuiltinVaListDecl() const;
1341
1342   /// \brief Retrieve the type of the \c __builtin_va_list type.
1343   QualType getBuiltinVaListType() const {
1344     return getTypeDeclType(getBuiltinVaListDecl());
1345   }
1346
1347   /// \brief Retrieve the C type declaration corresponding to the predefined
1348   /// \c __va_list_tag type used to help define the \c __builtin_va_list type
1349   /// for some targets.
1350   QualType getVaListTagType() const;
1351
1352   /// \brief Return a type with additional \c const, \c volatile, or
1353   /// \c restrict qualifiers.
1354   QualType getCVRQualifiedType(QualType T, unsigned CVR) const {
1355     return getQualifiedType(T, Qualifiers::fromCVRMask(CVR));
1356   }
1357
1358   /// \brief Un-split a SplitQualType.
1359   QualType getQualifiedType(SplitQualType split) const {
1360     return getQualifiedType(split.Ty, split.Quals);
1361   }
1362
1363   /// \brief Return a type with additional qualifiers.
1364   QualType getQualifiedType(QualType T, Qualifiers Qs) const {
1365     if (!Qs.hasNonFastQualifiers())
1366       return T.withFastQualifiers(Qs.getFastQualifiers());
1367     QualifierCollector Qc(Qs);
1368     const Type *Ptr = Qc.strip(T);
1369     return getExtQualType(Ptr, Qc);
1370   }
1371
1372   /// \brief Return a type with additional qualifiers.
1373   QualType getQualifiedType(const Type *T, Qualifiers Qs) const {
1374     if (!Qs.hasNonFastQualifiers())
1375       return QualType(T, Qs.getFastQualifiers());
1376     return getExtQualType(T, Qs);
1377   }
1378
1379   /// \brief Return a type with the given lifetime qualifier.
1380   ///
1381   /// \pre Neither type.ObjCLifetime() nor \p lifetime may be \c OCL_None.
1382   QualType getLifetimeQualifiedType(QualType type,
1383                                     Qualifiers::ObjCLifetime lifetime) {
1384     assert(type.getObjCLifetime() == Qualifiers::OCL_None);
1385     assert(lifetime != Qualifiers::OCL_None);
1386
1387     Qualifiers qs;
1388     qs.addObjCLifetime(lifetime);
1389     return getQualifiedType(type, qs);
1390   }
1391
1392   DeclarationNameInfo getNameForTemplate(TemplateName Name,
1393                                          SourceLocation NameLoc) const;
1394
1395   TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin,
1396                                          UnresolvedSetIterator End) const;
1397
1398   TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
1399                                         bool TemplateKeyword,
1400                                         TemplateDecl *Template) const;
1401
1402   TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1403                                         const IdentifierInfo *Name) const;
1404   TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1405                                         OverloadedOperatorKind Operator) const;
1406   TemplateName getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
1407                                             TemplateName replacement) const;
1408   TemplateName getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
1409                                         const TemplateArgument &ArgPack) const;
1410   
1411   enum GetBuiltinTypeError {
1412     GE_None,              ///< No error
1413     GE_Missing_stdio,     ///< Missing a type from <stdio.h>
1414     GE_Missing_setjmp,    ///< Missing a type from <setjmp.h>
1415     GE_Missing_ucontext   ///< Missing a type from <ucontext.h>
1416   };
1417
1418   /// \brief Return the type for the specified builtin.
1419   ///
1420   /// If \p IntegerConstantArgs is non-null, it is filled in with a bitmask of
1421   /// arguments to the builtin that are required to be integer constant
1422   /// expressions.
1423   QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error,
1424                           unsigned *IntegerConstantArgs = 0) const;
1425
1426 private:
1427   CanQualType getFromTargetType(unsigned Type) const;
1428   std::pair<uint64_t, unsigned> getTypeInfoImpl(const Type *T) const;
1429
1430   //===--------------------------------------------------------------------===//
1431   //                         Type Predicates.
1432   //===--------------------------------------------------------------------===//
1433
1434 public:
1435   /// \brief Return one of the GCNone, Weak or Strong Objective-C garbage
1436   /// collection attributes.
1437   Qualifiers::GC getObjCGCAttrKind(QualType Ty) const;
1438
1439   /// \brief Return true if the given vector types are of the same unqualified
1440   /// type or if they are equivalent to the same GCC vector type.
1441   ///
1442   /// \note This ignores whether they are target-specific (AltiVec or Neon)
1443   /// types.
1444   bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec);
1445
1446   /// \brief Return true if this is an \c NSObject object with its \c NSObject
1447   /// attribute set.
1448   static bool isObjCNSObjectType(QualType Ty) {
1449     return Ty->isObjCNSObjectType();
1450   }
1451
1452   //===--------------------------------------------------------------------===//
1453   //                         Type Sizing and Analysis
1454   //===--------------------------------------------------------------------===//
1455
1456   /// \brief Return the APFloat 'semantics' for the specified scalar floating
1457   /// point type.
1458   const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
1459
1460   /// \brief Get the size and alignment of the specified complete type in bits.
1461   std::pair<uint64_t, unsigned> getTypeInfo(const Type *T) const;
1462   std::pair<uint64_t, unsigned> getTypeInfo(QualType T) const {
1463     return getTypeInfo(T.getTypePtr());
1464   }
1465
1466   /// \brief Return the size of the specified (complete) type \p T, in bits.
1467   uint64_t getTypeSize(QualType T) const {
1468     return getTypeInfo(T).first;
1469   }
1470   uint64_t getTypeSize(const Type *T) const {
1471     return getTypeInfo(T).first;
1472   }
1473
1474   /// \brief Return the size of the character type, in bits.
1475   uint64_t getCharWidth() const {
1476     return getTypeSize(CharTy);
1477   }
1478   
1479   /// \brief Convert a size in bits to a size in characters.
1480   CharUnits toCharUnitsFromBits(int64_t BitSize) const;
1481
1482   /// \brief Convert a size in characters to a size in bits.
1483   int64_t toBits(CharUnits CharSize) const;
1484
1485   /// \brief Return the size of the specified (complete) type \p T, in
1486   /// characters.
1487   CharUnits getTypeSizeInChars(QualType T) const;
1488   CharUnits getTypeSizeInChars(const Type *T) const;
1489
1490   /// \brief Return the ABI-specified alignment of a (complete) type \p T, in
1491   /// bits.
1492   unsigned getTypeAlign(QualType T) const {
1493     return getTypeInfo(T).second;
1494   }
1495   unsigned getTypeAlign(const Type *T) const {
1496     return getTypeInfo(T).second;
1497   }
1498
1499   /// \brief Return the ABI-specified alignment of a (complete) type \p T, in 
1500   /// characters.
1501   CharUnits getTypeAlignInChars(QualType T) const;
1502   CharUnits getTypeAlignInChars(const Type *T) const;
1503   
1504   // getTypeInfoDataSizeInChars - Return the size of a type, in chars. If the
1505   // type is a record, its data size is returned.
1506   std::pair<CharUnits, CharUnits> getTypeInfoDataSizeInChars(QualType T) const;
1507
1508   std::pair<CharUnits, CharUnits> getTypeInfoInChars(const Type *T) const;
1509   std::pair<CharUnits, CharUnits> getTypeInfoInChars(QualType T) const;
1510
1511   /// \brief Return the "preferred" alignment of the specified type \p T for
1512   /// the current target, in bits.
1513   ///
1514   /// This can be different than the ABI alignment in cases where it is
1515   /// beneficial for performance to overalign a data type.
1516   unsigned getPreferredTypeAlign(const Type *T) const;
1517
1518   /// \brief Return a conservative estimate of the alignment of the specified
1519   /// decl \p D.
1520   ///
1521   /// \pre \p D must not be a bitfield type, as bitfields do not have a valid
1522   /// alignment.
1523   ///
1524   /// If \p RefAsPointee, references are treated like their underlying type
1525   /// (for alignof), else they're treated like pointers (for CodeGen).
1526   CharUnits getDeclAlign(const Decl *D, bool RefAsPointee = false) const;
1527
1528   /// \brief Get or compute information about the layout of the specified
1529   /// record (struct/union/class) \p D, which indicates its size and field
1530   /// position information.
1531   const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D) const;
1532
1533   /// \brief Get or compute information about the layout of the specified
1534   /// Objective-C interface.
1535   const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D)
1536     const;
1537
1538   void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS,
1539                         bool Simple = false) const;
1540
1541   /// \brief Get or compute information about the layout of the specified
1542   /// Objective-C implementation.
1543   ///
1544   /// This may differ from the interface if synthesized ivars are present.
1545   const ASTRecordLayout &
1546   getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const;
1547
1548   /// \brief Get the key function for the given record decl, or NULL if there
1549   /// isn't one.
1550   ///
1551   /// The key function is, according to the Itanium C++ ABI section 5.2.3:
1552   ///
1553   /// ...the first non-pure virtual function that is not inline at the point
1554   /// of class definition.
1555   const CXXMethodDecl *getKeyFunction(const CXXRecordDecl *RD);
1556
1557   /// Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
1558   uint64_t getFieldOffset(const ValueDecl *FD) const;
1559
1560   bool isNearlyEmpty(const CXXRecordDecl *RD) const;
1561
1562   MangleContext *createMangleContext();
1563   
1564   void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass,
1565                             SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const;
1566   
1567   unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const;
1568   void CollectInheritedProtocols(const Decl *CDecl,
1569                           llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols);
1570
1571   //===--------------------------------------------------------------------===//
1572   //                            Type Operators
1573   //===--------------------------------------------------------------------===//
1574
1575   /// \brief Return the canonical (structural) type corresponding to the
1576   /// specified potentially non-canonical type \p T.
1577   ///
1578   /// The non-canonical version of a type may have many "decorated" versions of
1579   /// types.  Decorators can include typedefs, 'typeof' operators, etc. The
1580   /// returned type is guaranteed to be free of any of these, allowing two
1581   /// canonical types to be compared for exact equality with a simple pointer
1582   /// comparison.
1583   CanQualType getCanonicalType(QualType T) const {
1584     return CanQualType::CreateUnsafe(T.getCanonicalType());
1585   }
1586
1587   const Type *getCanonicalType(const Type *T) const {
1588     return T->getCanonicalTypeInternal().getTypePtr();
1589   }
1590
1591   /// \brief Return the canonical parameter type corresponding to the specific
1592   /// potentially non-canonical one.
1593   ///
1594   /// Qualifiers are stripped off, functions are turned into function
1595   /// pointers, and arrays decay one level into pointers.
1596   CanQualType getCanonicalParamType(QualType T) const;
1597
1598   /// \brief Determine whether the given types \p T1 and \p T2 are equivalent.
1599   bool hasSameType(QualType T1, QualType T2) const {
1600     return getCanonicalType(T1) == getCanonicalType(T2);
1601   }
1602
1603   /// \brief Return this type as a completely-unqualified array type,
1604   /// capturing the qualifiers in \p Quals.
1605   ///
1606   /// This will remove the minimal amount of sugaring from the types, similar
1607   /// to the behavior of QualType::getUnqualifiedType().
1608   ///
1609   /// \param T is the qualified type, which may be an ArrayType
1610   ///
1611   /// \param Quals will receive the full set of qualifiers that were
1612   /// applied to the array.
1613   ///
1614   /// \returns if this is an array type, the completely unqualified array type
1615   /// that corresponds to it. Otherwise, returns T.getUnqualifiedType().
1616   QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals);
1617
1618   /// \brief Determine whether the given types are equivalent after
1619   /// cvr-qualifiers have been removed.
1620   bool hasSameUnqualifiedType(QualType T1, QualType T2) const {
1621     return getCanonicalType(T1).getTypePtr() ==
1622            getCanonicalType(T2).getTypePtr();
1623   }
1624
1625   bool UnwrapSimilarPointerTypes(QualType &T1, QualType &T2);
1626   
1627   /// \brief Retrieves the "canonical" nested name specifier for a
1628   /// given nested name specifier.
1629   ///
1630   /// The canonical nested name specifier is a nested name specifier
1631   /// that uniquely identifies a type or namespace within the type
1632   /// system. For example, given:
1633   ///
1634   /// \code
1635   /// namespace N {
1636   ///   struct S {
1637   ///     template<typename T> struct X { typename T* type; };
1638   ///   };
1639   /// }
1640   ///
1641   /// template<typename T> struct Y {
1642   ///   typename N::S::X<T>::type member;
1643   /// };
1644   /// \endcode
1645   ///
1646   /// Here, the nested-name-specifier for N::S::X<T>:: will be
1647   /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined
1648   /// by declarations in the type system and the canonical type for
1649   /// the template type parameter 'T' is template-param-0-0.
1650   NestedNameSpecifier *
1651   getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const;
1652
1653   /// \brief Retrieves the default calling convention to use for
1654   /// C++ instance methods.
1655   CallingConv getDefaultCXXMethodCallConv(bool isVariadic);
1656
1657   /// \brief Retrieves the canonical representation of the given
1658   /// calling convention.
1659   CallingConv getCanonicalCallConv(CallingConv CC) const;
1660
1661   /// \brief Determines whether two calling conventions name the same
1662   /// calling convention.
1663   bool isSameCallConv(CallingConv lcc, CallingConv rcc) {
1664     return (getCanonicalCallConv(lcc) == getCanonicalCallConv(rcc));
1665   }
1666
1667   /// \brief Retrieves the "canonical" template name that refers to a
1668   /// given template.
1669   ///
1670   /// The canonical template name is the simplest expression that can
1671   /// be used to refer to a given template. For most templates, this
1672   /// expression is just the template declaration itself. For example,
1673   /// the template std::vector can be referred to via a variety of
1674   /// names---std::vector, \::std::vector, vector (if vector is in
1675   /// scope), etc.---but all of these names map down to the same
1676   /// TemplateDecl, which is used to form the canonical template name.
1677   ///
1678   /// Dependent template names are more interesting. Here, the
1679   /// template name could be something like T::template apply or
1680   /// std::allocator<T>::template rebind, where the nested name
1681   /// specifier itself is dependent. In this case, the canonical
1682   /// template name uses the shortest form of the dependent
1683   /// nested-name-specifier, which itself contains all canonical
1684   /// types, values, and templates.
1685   TemplateName getCanonicalTemplateName(TemplateName Name) const;
1686
1687   /// \brief Determine whether the given template names refer to the same
1688   /// template.
1689   bool hasSameTemplateName(TemplateName X, TemplateName Y);
1690   
1691   /// \brief Retrieve the "canonical" template argument.
1692   ///
1693   /// The canonical template argument is the simplest template argument
1694   /// (which may be a type, value, expression, or declaration) that
1695   /// expresses the value of the argument.
1696   TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg)
1697     const;
1698
1699   /// Type Query functions.  If the type is an instance of the specified class,
1700   /// return the Type pointer for the underlying maximally pretty type.  This
1701   /// is a member of ASTContext because this may need to do some amount of
1702   /// canonicalization, e.g. to move type qualifiers into the element type.
1703   const ArrayType *getAsArrayType(QualType T) const;
1704   const ConstantArrayType *getAsConstantArrayType(QualType T) const {
1705     return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T));
1706   }
1707   const VariableArrayType *getAsVariableArrayType(QualType T) const {
1708     return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T));
1709   }
1710   const IncompleteArrayType *getAsIncompleteArrayType(QualType T) const {
1711     return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
1712   }
1713   const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T)
1714     const {
1715     return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T));
1716   }
1717   
1718   /// \brief Return the innermost element type of an array type.
1719   ///
1720   /// For example, will return "int" for int[m][n]
1721   QualType getBaseElementType(const ArrayType *VAT) const;
1722
1723   /// \brief Return the innermost element type of a type (which needn't
1724   /// actually be an array type).
1725   QualType getBaseElementType(QualType QT) const;
1726
1727   /// \brief Return number of constant array elements.
1728   uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const;
1729
1730   /// \brief Perform adjustment on the parameter type of a function.
1731   ///
1732   /// This routine adjusts the given parameter type @p T to the actual
1733   /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
1734   /// C++ [dcl.fct]p3). The adjusted parameter type is returned.
1735   QualType getAdjustedParameterType(QualType T) const;
1736   
1737   /// \brief Retrieve the parameter type as adjusted for use in the signature
1738   /// of a function, decaying array and function types and removing top-level
1739   /// cv-qualifiers.
1740   QualType getSignatureParameterType(QualType T) const;
1741   
1742   /// \brief Return the properly qualified result of decaying the specified
1743   /// array type to a pointer.
1744   ///
1745   /// This operation is non-trivial when handling typedefs etc.  The canonical
1746   /// type of \p T must be an array type, this returns a pointer to a properly
1747   /// qualified element of the array.
1748   ///
1749   /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
1750   QualType getArrayDecayedType(QualType T) const;
1751
1752   /// \brief Return the type that \p PromotableType will promote to: C99
1753   /// 6.3.1.1p2, assuming that \p PromotableType is a promotable integer type.
1754   QualType getPromotedIntegerType(QualType PromotableType) const;
1755
1756   /// \brief Recurses in pointer/array types until it finds an Objective-C
1757   /// retainable type and returns its ownership.
1758   Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const;
1759
1760   /// \brief Whether this is a promotable bitfield reference according
1761   /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
1762   ///
1763   /// \returns the type this bit-field will promote to, or NULL if no
1764   /// promotion occurs.
1765   QualType isPromotableBitField(Expr *E) const;
1766
1767   /// \brief Return the highest ranked integer type, see C99 6.3.1.8p1. 
1768   ///
1769   /// If \p LHS > \p RHS, returns 1.  If \p LHS == \p RHS, returns 0.  If
1770   /// \p LHS < \p RHS, return -1.
1771   int getIntegerTypeOrder(QualType LHS, QualType RHS) const;
1772
1773   /// \brief Compare the rank of the two specified floating point types,
1774   /// ignoring the domain of the type (i.e. 'double' == '_Complex double').
1775   ///
1776   /// If \p LHS > \p RHS, returns 1.  If \p LHS == \p RHS, returns 0.  If
1777   /// \p LHS < \p RHS, return -1.
1778   int getFloatingTypeOrder(QualType LHS, QualType RHS) const;
1779
1780   /// \brief Return a real floating point or a complex type (based on
1781   /// \p typeDomain/\p typeSize).
1782   ///
1783   /// \param typeDomain a real floating point or complex type.
1784   /// \param typeSize a real floating point or complex type.
1785   QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
1786                                              QualType typeDomain) const;
1787
1788   unsigned getTargetAddressSpace(QualType T) const {
1789     return getTargetAddressSpace(T.getQualifiers());
1790   }
1791
1792   unsigned getTargetAddressSpace(Qualifiers Q) const {
1793     return getTargetAddressSpace(Q.getAddressSpace());
1794   }
1795
1796   unsigned getTargetAddressSpace(unsigned AS) const {
1797     if (AS < LangAS::Offset || AS >= LangAS::Offset + LangAS::Count)
1798       return AS;
1799     else
1800       return (*AddrSpaceMap)[AS - LangAS::Offset];
1801   }
1802
1803 private:
1804   // Helper for integer ordering
1805   unsigned getIntegerRank(const Type *T) const;
1806
1807 public:
1808
1809   //===--------------------------------------------------------------------===//
1810   //                    Type Compatibility Predicates
1811   //===--------------------------------------------------------------------===//
1812
1813   /// Compatibility predicates used to check assignment expressions.
1814   bool typesAreCompatible(QualType T1, QualType T2, 
1815                           bool CompareUnqualified = false); // C99 6.2.7p1
1816
1817   bool propertyTypesAreCompatible(QualType, QualType); 
1818   bool typesAreBlockPointerCompatible(QualType, QualType); 
1819
1820   bool isObjCIdType(QualType T) const {
1821     return T == getObjCIdType();
1822   }
1823   bool isObjCClassType(QualType T) const {
1824     return T == getObjCClassType();
1825   }
1826   bool isObjCSelType(QualType T) const {
1827     return T == getObjCSelType();
1828   }
1829   bool QualifiedIdConformsQualifiedId(QualType LHS, QualType RHS);
1830   bool ObjCQualifiedIdTypesAreCompatible(QualType LHS, QualType RHS,
1831                                          bool ForCompare);
1832
1833   bool ObjCQualifiedClassTypesAreCompatible(QualType LHS, QualType RHS);
1834   
1835   // Check the safety of assignment from LHS to RHS
1836   bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
1837                                const ObjCObjectPointerType *RHSOPT);
1838   bool canAssignObjCInterfaces(const ObjCObjectType *LHS,
1839                                const ObjCObjectType *RHS);
1840   bool canAssignObjCInterfacesInBlockPointer(
1841                                           const ObjCObjectPointerType *LHSOPT,
1842                                           const ObjCObjectPointerType *RHSOPT,
1843                                           bool BlockReturnType);
1844   bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
1845   QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT,
1846                                    const ObjCObjectPointerType *RHSOPT);
1847   bool canBindObjCObjectType(QualType To, QualType From);
1848
1849   // Functions for calculating composite types
1850   QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false,
1851                       bool Unqualified = false, bool BlockReturnType = false);
1852   QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false,
1853                               bool Unqualified = false);
1854   QualType mergeFunctionArgumentTypes(QualType, QualType,
1855                                       bool OfBlockPointer=false,
1856                                       bool Unqualified = false);
1857   QualType mergeTransparentUnionType(QualType, QualType,
1858                                      bool OfBlockPointer=false,
1859                                      bool Unqualified = false);
1860   
1861   QualType mergeObjCGCQualifiers(QualType, QualType);
1862     
1863   bool FunctionTypesMatchOnNSConsumedAttrs(
1864          const FunctionProtoType *FromFunctionType,
1865          const FunctionProtoType *ToFunctionType);
1866
1867   void ResetObjCLayout(const ObjCContainerDecl *CD) {
1868     ObjCLayouts[CD] = 0;
1869   }
1870
1871   //===--------------------------------------------------------------------===//
1872   //                    Integer Predicates
1873   //===--------------------------------------------------------------------===//
1874
1875   // The width of an integer, as defined in C99 6.2.6.2. This is the number
1876   // of bits in an integer type excluding any padding bits.
1877   unsigned getIntWidth(QualType T) const;
1878
1879   // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
1880   // unsigned integer type.  This method takes a signed type, and returns the
1881   // corresponding unsigned integer type.
1882   QualType getCorrespondingUnsignedType(QualType T) const;
1883
1884   //===--------------------------------------------------------------------===//
1885   //                    Type Iterators.
1886   //===--------------------------------------------------------------------===//
1887
1888   typedef std::vector<Type*>::iterator       type_iterator;
1889   typedef std::vector<Type*>::const_iterator const_type_iterator;
1890
1891   type_iterator types_begin() { return Types.begin(); }
1892   type_iterator types_end() { return Types.end(); }
1893   const_type_iterator types_begin() const { return Types.begin(); }
1894   const_type_iterator types_end() const { return Types.end(); }
1895
1896   //===--------------------------------------------------------------------===//
1897   //                    Integer Values
1898   //===--------------------------------------------------------------------===//
1899
1900   /// \brief Make an APSInt of the appropriate width and signedness for the
1901   /// given \p Value and integer \p Type.
1902   llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const {
1903     llvm::APSInt Res(getIntWidth(Type), 
1904                      !Type->isSignedIntegerOrEnumerationType());
1905     Res = Value;
1906     return Res;
1907   }
1908
1909   bool isSentinelNullExpr(const Expr *E);
1910
1911   /// \brief Get the implementation of the ObjCInterfaceDecl \p D, or NULL if
1912   /// none exists.
1913   ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D);
1914   /// \brief Get the implementation of the ObjCCategoryDecl \p D, or NULL if
1915   /// none exists.
1916   ObjCCategoryImplDecl   *getObjCImplementation(ObjCCategoryDecl *D);
1917
1918   /// \brief Return true if there is at least one \@implementation in the TU.
1919   bool AnyObjCImplementation() {
1920     return !ObjCImpls.empty();
1921   }
1922
1923   /// \brief Set the implementation of ObjCInterfaceDecl.
1924   void setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1925                              ObjCImplementationDecl *ImplD);
1926   /// \brief Set the implementation of ObjCCategoryDecl.
1927   void setObjCImplementation(ObjCCategoryDecl *CatD,
1928                              ObjCCategoryImplDecl *ImplD);
1929
1930   /// \brief Get the duplicate declaration of a ObjCMethod in the same
1931   /// interface, or null if none exists.
1932   const ObjCMethodDecl *getObjCMethodRedeclaration(
1933                                                const ObjCMethodDecl *MD) const {
1934     return ObjCMethodRedecls.lookup(MD);
1935   }
1936
1937   void setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
1938                                   const ObjCMethodDecl *Redecl) {
1939     assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
1940     ObjCMethodRedecls[MD] = Redecl;
1941   }
1942
1943   /// \brief Returns the Objective-C interface that \p ND belongs to if it is
1944   /// an Objective-C method/property/ivar etc. that is part of an interface,
1945   /// otherwise returns null.
1946   ObjCInterfaceDecl *getObjContainingInterface(NamedDecl *ND) const;
1947   
1948   /// \brief Set the copy inialization expression of a block var decl.
1949   void setBlockVarCopyInits(VarDecl*VD, Expr* Init);
1950   /// \brief Get the copy initialization expression of the VarDecl \p VD, or
1951   /// NULL if none exists.
1952   Expr *getBlockVarCopyInits(const VarDecl* VD);
1953
1954   /// \brief Allocate an uninitialized TypeSourceInfo.
1955   ///
1956   /// The caller should initialize the memory held by TypeSourceInfo using
1957   /// the TypeLoc wrappers.
1958   ///
1959   /// \param T the type that will be the basis for type source info. This type
1960   /// should refer to how the declarator was written in source code, not to
1961   /// what type semantic analysis resolved the declarator to.
1962   ///
1963   /// \param Size the size of the type info to create, or 0 if the size
1964   /// should be calculated based on the type.
1965   TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0) const;
1966
1967   /// \brief Allocate a TypeSourceInfo where all locations have been
1968   /// initialized to a given location, which defaults to the empty
1969   /// location.
1970   TypeSourceInfo *
1971   getTrivialTypeSourceInfo(QualType T, 
1972                            SourceLocation Loc = SourceLocation()) const;
1973
1974   TypeSourceInfo *getNullTypeSourceInfo() { return &NullTypeSourceInfo; }
1975
1976   /// \brief Add a deallocation callback that will be invoked when the 
1977   /// ASTContext is destroyed.
1978   ///
1979   /// \param Callback A callback function that will be invoked on destruction.
1980   ///
1981   /// \param Data Pointer data that will be provided to the callback function
1982   /// when it is called.
1983   void AddDeallocation(void (*Callback)(void*), void *Data);
1984
1985   GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD);
1986   GVALinkage GetGVALinkageForVariable(const VarDecl *VD);
1987
1988   /// \brief Determines if the decl can be CodeGen'ed or deserialized from PCH
1989   /// lazily, only when used; this is only relevant for function or file scoped
1990   /// var definitions.
1991   ///
1992   /// \returns true if the function/var must be CodeGen'ed/deserialized even if
1993   /// it is not used.
1994   bool DeclMustBeEmitted(const Decl *D);
1995
1996   /// \brief Retrieve the lambda mangling number for a lambda expression.
1997   unsigned getLambdaManglingNumber(CXXMethodDecl *CallOperator);
1998   
1999   /// \brief Used by ParmVarDecl to store on the side the
2000   /// index of the parameter when it exceeds the size of the normal bitfield.
2001   void setParameterIndex(const ParmVarDecl *D, unsigned index);
2002
2003   /// \brief Used by ParmVarDecl to retrieve on the side the
2004   /// index of the parameter when it exceeds the size of the normal bitfield.
2005   unsigned getParameterIndex(const ParmVarDecl *D) const;
2006   
2007   //===--------------------------------------------------------------------===//
2008   //                    Statistics
2009   //===--------------------------------------------------------------------===//
2010
2011   /// \brief The number of implicitly-declared default constructors.
2012   static unsigned NumImplicitDefaultConstructors;
2013   
2014   /// \brief The number of implicitly-declared default constructors for 
2015   /// which declarations were built.
2016   static unsigned NumImplicitDefaultConstructorsDeclared;
2017
2018   /// \brief The number of implicitly-declared copy constructors.
2019   static unsigned NumImplicitCopyConstructors;
2020   
2021   /// \brief The number of implicitly-declared copy constructors for 
2022   /// which declarations were built.
2023   static unsigned NumImplicitCopyConstructorsDeclared;
2024
2025   /// \brief The number of implicitly-declared move constructors.
2026   static unsigned NumImplicitMoveConstructors;
2027
2028   /// \brief The number of implicitly-declared move constructors for
2029   /// which declarations were built.
2030   static unsigned NumImplicitMoveConstructorsDeclared;
2031
2032   /// \brief The number of implicitly-declared copy assignment operators.
2033   static unsigned NumImplicitCopyAssignmentOperators;
2034   
2035   /// \brief The number of implicitly-declared copy assignment operators for 
2036   /// which declarations were built.
2037   static unsigned NumImplicitCopyAssignmentOperatorsDeclared;
2038
2039   /// \brief The number of implicitly-declared move assignment operators.
2040   static unsigned NumImplicitMoveAssignmentOperators;
2041   
2042   /// \brief The number of implicitly-declared move assignment operators for 
2043   /// which declarations were built.
2044   static unsigned NumImplicitMoveAssignmentOperatorsDeclared;
2045
2046   /// \brief The number of implicitly-declared destructors.
2047   static unsigned NumImplicitDestructors;
2048   
2049   /// \brief The number of implicitly-declared destructors for which 
2050   /// declarations were built.
2051   static unsigned NumImplicitDestructorsDeclared;
2052   
2053 private:
2054   ASTContext(const ASTContext &) LLVM_DELETED_FUNCTION;
2055   void operator=(const ASTContext &) LLVM_DELETED_FUNCTION;
2056
2057 public:
2058   /// \brief Initialize built-in types.
2059   ///
2060   /// This routine may only be invoked once for a given ASTContext object.
2061   /// It is normally invoked by the ASTContext constructor. However, the
2062   /// constructor can be asked to delay initialization, which places the burden
2063   /// of calling this function on the user of that object.
2064   ///
2065   /// \param Target The target 
2066   void InitBuiltinTypes(const TargetInfo &Target);
2067   
2068 private:
2069   void InitBuiltinType(CanQualType &R, BuiltinType::Kind K);
2070
2071   // Return the Objective-C type encoding for a given type.
2072   void getObjCEncodingForTypeImpl(QualType t, std::string &S,
2073                                   bool ExpandPointedToStructures,
2074                                   bool ExpandStructures,
2075                                   const FieldDecl *Field,
2076                                   bool OutermostType = false,
2077                                   bool EncodingProperty = false,
2078                                   bool StructField = false,
2079                                   bool EncodeBlockParameters = false,
2080                                   bool EncodeClassNames = false) const;
2081
2082   // Adds the encoding of the structure's members.
2083   void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S,
2084                                        const FieldDecl *Field,
2085                                        bool includeVBases = true) const;
2086
2087   // Adds the encoding of a method parameter or return type.
2088   void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
2089                                          QualType T, std::string& S,
2090                                          bool Extended) const;
2091
2092   const ASTRecordLayout &
2093   getObjCLayout(const ObjCInterfaceDecl *D,
2094                 const ObjCImplementationDecl *Impl) const;
2095
2096 private:
2097   /// \brief A set of deallocations that should be performed when the 
2098   /// ASTContext is destroyed.
2099   SmallVector<std::pair<void (*)(void*), void *>, 16> Deallocations;
2100                                        
2101   // FIXME: This currently contains the set of StoredDeclMaps used
2102   // by DeclContext objects.  This probably should not be in ASTContext,
2103   // but we include it here so that ASTContext can quickly deallocate them.
2104   llvm::PointerIntPair<StoredDeclsMap*,1> LastSDM;
2105
2106   /// \brief A counter used to uniquely identify "blocks".
2107   mutable unsigned int UniqueBlockByRefTypeID;
2108   
2109   friend class DeclContext;
2110   friend class DeclarationNameTable;
2111   void ReleaseDeclContextMaps();
2112 };
2113   
2114 /// \brief Utility function for constructing a nullary selector.
2115 static inline Selector GetNullarySelector(StringRef name, ASTContext& Ctx) {
2116   IdentifierInfo* II = &Ctx.Idents.get(name);
2117   return Ctx.Selectors.getSelector(0, &II);
2118 }
2119
2120 /// \brief Utility function for constructing an unary selector.
2121 static inline Selector GetUnarySelector(StringRef name, ASTContext& Ctx) {
2122   IdentifierInfo* II = &Ctx.Idents.get(name);
2123   return Ctx.Selectors.getSelector(1, &II);
2124 }
2125
2126 }  // end namespace clang
2127
2128 // operator new and delete aren't allowed inside namespaces.
2129
2130 /// @brief Placement new for using the ASTContext's allocator.
2131 ///
2132 /// This placement form of operator new uses the ASTContext's allocator for
2133 /// obtaining memory.
2134 ///
2135 /// IMPORTANT: These are also declared in clang/AST/Attr.h! Any changes here
2136 /// need to also be made there.
2137 ///
2138 /// We intentionally avoid using a nothrow specification here so that the calls
2139 /// to this operator will not perform a null check on the result -- the
2140 /// underlying allocator never returns null pointers.
2141 ///
2142 /// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
2143 /// @code
2144 /// // Default alignment (8)
2145 /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
2146 /// // Specific alignment
2147 /// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
2148 /// @endcode
2149 /// Please note that you cannot use delete on the pointer; it must be
2150 /// deallocated using an explicit destructor call followed by
2151 /// @c Context.Deallocate(Ptr).
2152 ///
2153 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
2154 /// @param C The ASTContext that provides the allocator.
2155 /// @param Alignment The alignment of the allocated memory (if the underlying
2156 ///                  allocator supports it).
2157 /// @return The allocated memory. Could be NULL.
2158 inline void *operator new(size_t Bytes, const clang::ASTContext &C,
2159                           size_t Alignment) {
2160   return C.Allocate(Bytes, Alignment);
2161 }
2162 /// @brief Placement delete companion to the new above.
2163 ///
2164 /// This operator is just a companion to the new above. There is no way of
2165 /// invoking it directly; see the new operator for more details. This operator
2166 /// is called implicitly by the compiler if a placement new expression using
2167 /// the ASTContext throws in the object constructor.
2168 inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t) {
2169   C.Deallocate(Ptr);
2170 }
2171
2172 /// This placement form of operator new[] uses the ASTContext's allocator for
2173 /// obtaining memory.
2174 ///
2175 /// We intentionally avoid using a nothrow specification here so that the calls
2176 /// to this operator will not perform a null check on the result -- the
2177 /// underlying allocator never returns null pointers.
2178 ///
2179 /// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
2180 /// @code
2181 /// // Default alignment (8)
2182 /// char *data = new (Context) char[10];
2183 /// // Specific alignment
2184 /// char *data = new (Context, 4) char[10];
2185 /// @endcode
2186 /// Please note that you cannot use delete on the pointer; it must be
2187 /// deallocated using an explicit destructor call followed by
2188 /// @c Context.Deallocate(Ptr).
2189 ///
2190 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
2191 /// @param C The ASTContext that provides the allocator.
2192 /// @param Alignment The alignment of the allocated memory (if the underlying
2193 ///                  allocator supports it).
2194 /// @return The allocated memory. Could be NULL.
2195 inline void *operator new[](size_t Bytes, const clang::ASTContext& C,
2196                             size_t Alignment = 8) {
2197   return C.Allocate(Bytes, Alignment);
2198 }
2199
2200 /// @brief Placement delete[] companion to the new[] above.
2201 ///
2202 /// This operator is just a companion to the new[] above. There is no way of
2203 /// invoking it directly; see the new[] operator for more details. This operator
2204 /// is called implicitly by the compiler if a placement new[] expression using
2205 /// the ASTContext throws in the object constructor.
2206 inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_t) {
2207   C.Deallocate(Ptr);
2208 }
2209
2210 #endif