ASTContext.h revision dae0cb52e4e3d46bbfc9a4510909522197a92e54
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//  This file defines the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_ASTCONTEXT_H
15#define LLVM_CLANG_AST_ASTCONTEXT_H
16
17#include "clang/Basic/IdentifierTable.h"
18#include "clang/Basic/LangOptions.h"
19#include "clang/Basic/OperatorKinds.h"
20#include "clang/Basic/PartialDiagnostic.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/NestedNameSpecifier.h"
23#include "clang/AST/PrettyPrinter.h"
24#include "clang/AST/TemplateName.h"
25#include "clang/AST/Type.h"
26#include "clang/AST/CanonicalType.h"
27#include "clang/AST/UsuallyTinyPtrVector.h"
28#include "llvm/ADT/DenseMap.h"
29#include "llvm/ADT/FoldingSet.h"
30#include "llvm/ADT/OwningPtr.h"
31#include "llvm/ADT/SmallPtrSet.h"
32#include "llvm/Support/Allocator.h"
33#include <vector>
34
35namespace llvm {
36  struct fltSemantics;
37  class raw_ostream;
38}
39
40namespace clang {
41  class FileManager;
42  class ASTRecordLayout;
43  class BlockExpr;
44  class CharUnits;
45  class Diagnostic;
46  class Expr;
47  class ExternalASTSource;
48  class ASTMutationListener;
49  class IdentifierTable;
50  class SelectorTable;
51  class SourceManager;
52  class TargetInfo;
53  class CXXABI;
54  // Decls
55  class DeclContext;
56  class CXXMethodDecl;
57  class CXXRecordDecl;
58  class Decl;
59  class FieldDecl;
60  class ObjCIvarDecl;
61  class ObjCIvarRefExpr;
62  class ObjCPropertyDecl;
63  class RecordDecl;
64  class StoredDeclsMap;
65  class TagDecl;
66  class TemplateTemplateParmDecl;
67  class TemplateTypeParmDecl;
68  class TranslationUnitDecl;
69  class TypeDecl;
70  class TypedefDecl;
71  class UsingDecl;
72  class UsingShadowDecl;
73  class UnresolvedSetIterator;
74
75  namespace Builtin { class Context; }
76
77/// ASTContext - This class holds long-lived AST nodes (such as types and
78/// decls) that can be referred to throughout the semantic analysis of a file.
79class ASTContext {
80  ASTContext &this_() { return *this; }
81
82  std::vector<Type*> Types;
83  llvm::FoldingSet<ExtQuals> ExtQualNodes;
84  llvm::FoldingSet<ComplexType> ComplexTypes;
85  llvm::FoldingSet<PointerType> PointerTypes;
86  llvm::FoldingSet<BlockPointerType> BlockPointerTypes;
87  llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes;
88  llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes;
89  llvm::FoldingSet<MemberPointerType> MemberPointerTypes;
90  llvm::FoldingSet<ConstantArrayType> ConstantArrayTypes;
91  llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
92  std::vector<VariableArrayType*> VariableArrayTypes;
93  llvm::FoldingSet<DependentSizedArrayType> DependentSizedArrayTypes;
94  llvm::FoldingSet<DependentSizedExtVectorType> DependentSizedExtVectorTypes;
95  llvm::FoldingSet<VectorType> VectorTypes;
96  llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes;
97  llvm::FoldingSet<FunctionProtoType> FunctionProtoTypes;
98  llvm::FoldingSet<DependentTypeOfExprType> DependentTypeOfExprTypes;
99  llvm::FoldingSet<DependentDecltypeType> DependentDecltypeTypes;
100  llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes;
101  llvm::FoldingSet<SubstTemplateTypeParmType> SubstTemplateTypeParmTypes;
102  llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&>
103    TemplateSpecializationTypes;
104  llvm::FoldingSet<ElaboratedType> ElaboratedTypes;
105  llvm::FoldingSet<DependentNameType> DependentNameTypes;
106  llvm::ContextualFoldingSet<DependentTemplateSpecializationType, ASTContext&>
107    DependentTemplateSpecializationTypes;
108  llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes;
109  llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes;
110
111  llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames;
112  llvm::FoldingSet<DependentTemplateName> DependentTemplateNames;
113
114  /// \brief The set of nested name specifiers.
115  ///
116  /// This set is managed by the NestedNameSpecifier class.
117  llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers;
118  NestedNameSpecifier *GlobalNestedNameSpecifier;
119  friend class NestedNameSpecifier;
120
121  /// ASTRecordLayouts - A cache mapping from RecordDecls to ASTRecordLayouts.
122  ///  This is lazily created.  This is intentionally not serialized.
123  llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*> ASTRecordLayouts;
124  llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*> ObjCLayouts;
125
126  /// KeyFunctions - A cache mapping from CXXRecordDecls to key functions.
127  llvm::DenseMap<const CXXRecordDecl*, const CXXMethodDecl*> KeyFunctions;
128
129  /// \brief Mapping from ObjCContainers to their ObjCImplementations.
130  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls;
131
132  /// \brief Representation of a "canonical" template template parameter that
133  /// is used in canonical template names.
134  class CanonicalTemplateTemplateParm : public llvm::FoldingSetNode {
135    TemplateTemplateParmDecl *Parm;
136
137  public:
138    CanonicalTemplateTemplateParm(TemplateTemplateParmDecl *Parm)
139      : Parm(Parm) { }
140
141    TemplateTemplateParmDecl *getParam() const { return Parm; }
142
143    void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, Parm); }
144
145    static void Profile(llvm::FoldingSetNodeID &ID,
146                        TemplateTemplateParmDecl *Parm);
147  };
148  llvm::FoldingSet<CanonicalTemplateTemplateParm> CanonTemplateTemplateParms;
149
150  TemplateTemplateParmDecl *getCanonicalTemplateTemplateParmDecl(
151                                               TemplateTemplateParmDecl *TTP);
152
153  /// \brief Whether __[u]int128_t identifier is installed.
154  bool IsInt128Installed;
155
156  /// BuiltinVaListType - built-in va list type.
157  /// This is initially null and set by Sema::LazilyCreateBuiltin when
158  /// a builtin that takes a valist is encountered.
159  QualType BuiltinVaListType;
160
161  /// ObjCIdType - a pseudo built-in typedef type (set by Sema).
162  QualType ObjCIdTypedefType;
163
164  /// ObjCSelType - another pseudo built-in typedef type (set by Sema).
165  QualType ObjCSelTypedefType;
166
167  /// ObjCProtoType - another pseudo built-in typedef type (set by Sema).
168  QualType ObjCProtoType;
169  const RecordType *ProtoStructType;
170
171  /// ObjCClassType - another pseudo built-in typedef type (set by Sema).
172  QualType ObjCClassTypedefType;
173
174  QualType ObjCConstantStringType;
175  RecordDecl *CFConstantStringTypeDecl;
176
177  RecordDecl *NSConstantStringTypeDecl;
178
179  RecordDecl *ObjCFastEnumerationStateTypeDecl;
180
181  /// \brief The type for the C FILE type.
182  TypeDecl *FILEDecl;
183
184  /// \brief The type for the C jmp_buf type.
185  TypeDecl *jmp_bufDecl;
186
187  /// \brief The type for the C sigjmp_buf type.
188  TypeDecl *sigjmp_bufDecl;
189
190  /// \brief Type for the Block descriptor for Blocks CodeGen.
191  RecordDecl *BlockDescriptorType;
192
193  /// \brief Type for the Block descriptor for Blocks CodeGen.
194  RecordDecl *BlockDescriptorExtendedType;
195
196  TypeSourceInfo NullTypeSourceInfo;
197
198  /// \brief Keeps track of all declaration attributes.
199  ///
200  /// Since so few decls have attrs, we keep them in a hash map instead of
201  /// wasting space in the Decl class.
202  llvm::DenseMap<const Decl*, AttrVec*> DeclAttrs;
203
204  /// \brief Keeps track of the static data member templates from which
205  /// static data members of class template specializations were instantiated.
206  ///
207  /// This data structure stores the mapping from instantiations of static
208  /// data members to the static data member representations within the
209  /// class template from which they were instantiated along with the kind
210  /// of instantiation or specialization (a TemplateSpecializationKind - 1).
211  ///
212  /// Given the following example:
213  ///
214  /// \code
215  /// template<typename T>
216  /// struct X {
217  ///   static T value;
218  /// };
219  ///
220  /// template<typename T>
221  ///   T X<T>::value = T(17);
222  ///
223  /// int *x = &X<int>::value;
224  /// \endcode
225  ///
226  /// This mapping will contain an entry that maps from the VarDecl for
227  /// X<int>::value to the corresponding VarDecl for X<T>::value (within the
228  /// class template X) and will be marked TSK_ImplicitInstantiation.
229  llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>
230    InstantiatedFromStaticDataMember;
231
232  /// \brief Keeps track of the declaration from which a UsingDecl was
233  /// created during instantiation.  The source declaration is always
234  /// a UsingDecl, an UnresolvedUsingValueDecl, or an
235  /// UnresolvedUsingTypenameDecl.
236  ///
237  /// For example:
238  /// \code
239  /// template<typename T>
240  /// struct A {
241  ///   void f();
242  /// };
243  ///
244  /// template<typename T>
245  /// struct B : A<T> {
246  ///   using A<T>::f;
247  /// };
248  ///
249  /// template struct B<int>;
250  /// \endcode
251  ///
252  /// This mapping will contain an entry that maps from the UsingDecl in
253  /// B<int> to the UnresolvedUsingDecl in B<T>.
254  llvm::DenseMap<UsingDecl *, NamedDecl *> InstantiatedFromUsingDecl;
255
256  llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>
257    InstantiatedFromUsingShadowDecl;
258
259  llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl;
260
261  /// \brief Mapping that stores the methods overridden by a given C++
262  /// member function.
263  ///
264  /// Since most C++ member functions aren't virtual and therefore
265  /// don't override anything, we store the overridden functions in
266  /// this map on the side rather than within the CXXMethodDecl structure.
267  typedef UsuallyTinyPtrVector<const CXXMethodDecl> CXXMethodVector;
268  llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector> OverriddenMethods;
269
270  TranslationUnitDecl *TUDecl;
271
272  /// SourceMgr - The associated SourceManager object.
273  SourceManager &SourceMgr;
274
275  /// LangOpts - The language options used to create the AST associated with
276  ///  this ASTContext object.
277  LangOptions LangOpts;
278
279  /// \brief The allocator used to create AST objects.
280  ///
281  /// AST objects are never destructed; rather, all memory associated with the
282  /// AST objects will be released when the ASTContext itself is destroyed.
283  llvm::BumpPtrAllocator BumpAlloc;
284
285  /// \brief Allocator for partial diagnostics.
286  PartialDiagnostic::StorageAllocator DiagAllocator;
287
288  /// \brief The current C++ ABI.
289  llvm::OwningPtr<CXXABI> ABI;
290  CXXABI *createCXXABI(const TargetInfo &T);
291
292  friend class ASTDeclReader;
293
294public:
295  const TargetInfo &Target;
296  IdentifierTable &Idents;
297  SelectorTable &Selectors;
298  Builtin::Context &BuiltinInfo;
299  DeclarationNameTable DeclarationNames;
300  llvm::OwningPtr<ExternalASTSource> ExternalSource;
301  ASTMutationListener *Listener;
302  clang::PrintingPolicy PrintingPolicy;
303
304  // Typedefs which may be provided defining the structure of Objective-C
305  // pseudo-builtins
306  QualType ObjCIdRedefinitionType;
307  QualType ObjCClassRedefinitionType;
308  QualType ObjCSelRedefinitionType;
309
310  SourceManager& getSourceManager() { return SourceMgr; }
311  const SourceManager& getSourceManager() const { return SourceMgr; }
312  void *Allocate(unsigned Size, unsigned Align = 8) {
313    return BumpAlloc.Allocate(Size, Align);
314  }
315  void Deallocate(void *Ptr) { }
316
317  PartialDiagnostic::StorageAllocator &getDiagAllocator() {
318    return DiagAllocator;
319  }
320
321  const LangOptions& getLangOptions() const { return LangOpts; }
322
323  Diagnostic &getDiagnostics() const;
324
325  FullSourceLoc getFullLoc(SourceLocation Loc) const {
326    return FullSourceLoc(Loc,SourceMgr);
327  }
328
329  /// \brief Retrieve the attributes for the given declaration.
330  AttrVec& getDeclAttrs(const Decl *D);
331
332  /// \brief Erase the attributes corresponding to the given declaration.
333  void eraseDeclAttrs(const Decl *D);
334
335  /// \brief If this variable is an instantiated static data member of a
336  /// class template specialization, returns the templated static data member
337  /// from which it was instantiated.
338  MemberSpecializationInfo *getInstantiatedFromStaticDataMember(
339                                                           const VarDecl *Var);
340
341  /// \brief Note that the static data member \p Inst is an instantiation of
342  /// the static data member template \p Tmpl of a class template.
343  void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
344                                           TemplateSpecializationKind TSK,
345                        SourceLocation PointOfInstantiation = SourceLocation());
346
347  /// \brief If the given using decl is an instantiation of a
348  /// (possibly unresolved) using decl from a template instantiation,
349  /// return it.
350  NamedDecl *getInstantiatedFromUsingDecl(UsingDecl *Inst);
351
352  /// \brief Remember that the using decl \p Inst is an instantiation
353  /// of the using decl \p Pattern of a class template.
354  void setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern);
355
356  void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
357                                          UsingShadowDecl *Pattern);
358  UsingShadowDecl *getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst);
359
360  FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field);
361
362  void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl);
363
364  // Access to the set of methods overridden by the given C++ method.
365  typedef CXXMethodVector::iterator overridden_cxx_method_iterator;
366  overridden_cxx_method_iterator
367  overridden_methods_begin(const CXXMethodDecl *Method) const;
368
369  overridden_cxx_method_iterator
370  overridden_methods_end(const CXXMethodDecl *Method) const;
371
372  unsigned overridden_methods_size(const CXXMethodDecl *Method) const;
373
374  /// \brief Note that the given C++ \p Method overrides the given \p
375  /// Overridden method.
376  void addOverriddenMethod(const CXXMethodDecl *Method,
377                           const CXXMethodDecl *Overridden);
378
379  TranslationUnitDecl *getTranslationUnitDecl() const { return TUDecl; }
380
381
382  // Builtin Types.
383  CanQualType VoidTy;
384  CanQualType BoolTy;
385  CanQualType CharTy;
386  CanQualType WCharTy;  // [C++ 3.9.1p5], integer type in C99.
387  CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99.
388  CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99.
389  CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty;
390  CanQualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy;
391  CanQualType UnsignedLongLongTy, UnsignedInt128Ty;
392  CanQualType FloatTy, DoubleTy, LongDoubleTy;
393  CanQualType FloatComplexTy, DoubleComplexTy, LongDoubleComplexTy;
394  CanQualType VoidPtrTy, NullPtrTy;
395  CanQualType OverloadTy, UndeducedAutoTy;
396  CanQualType DependentTy;
397  CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy;
398
399  ASTContext(const LangOptions& LOpts, SourceManager &SM, const TargetInfo &t,
400             IdentifierTable &idents, SelectorTable &sels,
401             Builtin::Context &builtins,
402             unsigned size_reserve);
403
404  ~ASTContext();
405
406  /// \brief Attach an external AST source to the AST context.
407  ///
408  /// The external AST source provides the ability to load parts of
409  /// the abstract syntax tree as needed from some external storage,
410  /// e.g., a precompiled header.
411  void setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source);
412
413  /// \brief Retrieve a pointer to the external AST source associated
414  /// with this AST context, if any.
415  ExternalASTSource *getExternalSource() const { return ExternalSource.get(); }
416
417  /// \brief Attach an AST mutation listener to the AST context.
418  ///
419  /// The AST mutation listener provides the ability to track modifications to
420  /// the abstract syntax tree entities committed after they were initially
421  /// created.
422  void setASTMutationListener(ASTMutationListener *Listener) {
423    this->Listener = Listener;
424  }
425
426  /// \brief Retrieve a pointer to the AST mutation listener associated
427  /// with this AST context, if any.
428  ASTMutationListener *getASTMutationListener() const { return Listener; }
429
430  void PrintStats() const;
431  const std::vector<Type*>& getTypes() const { return Types; }
432
433  //===--------------------------------------------------------------------===//
434  //                           Type Constructors
435  //===--------------------------------------------------------------------===//
436
437private:
438  /// getExtQualType - Return a type with extended qualifiers.
439  QualType getExtQualType(const Type *Base, Qualifiers Quals);
440
441  QualType getTypeDeclTypeSlow(const TypeDecl *Decl);
442
443public:
444  /// getAddSpaceQualType - Return the uniqued reference to the type for an
445  /// address space qualified type with the specified type and address space.
446  /// The resulting type has a union of the qualifiers from T and the address
447  /// space. If T already has an address space specifier, it is silently
448  /// replaced.
449  QualType getAddrSpaceQualType(QualType T, unsigned AddressSpace);
450
451  /// getObjCGCQualType - Returns the uniqued reference to the type for an
452  /// objc gc qualified type. The retulting type has a union of the qualifiers
453  /// from T and the gc attribute.
454  QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr);
455
456  /// getRestrictType - Returns the uniqued reference to the type for a
457  /// 'restrict' qualified type.  The resulting type has a union of the
458  /// qualifiers from T and 'restrict'.
459  QualType getRestrictType(QualType T) {
460    return T.withFastQualifiers(Qualifiers::Restrict);
461  }
462
463  /// getVolatileType - Returns the uniqued reference to the type for a
464  /// 'volatile' qualified type.  The resulting type has a union of the
465  /// qualifiers from T and 'volatile'.
466  QualType getVolatileType(QualType T);
467
468  /// getConstType - Returns the uniqued reference to the type for a
469  /// 'const' qualified type.  The resulting type has a union of the
470  /// qualifiers from T and 'const'.
471  ///
472  /// It can be reasonably expected that this will always be
473  /// equivalent to calling T.withConst().
474  QualType getConstType(QualType T) { return T.withConst(); }
475
476  /// getNoReturnType - Add or remove the noreturn attribute to the given type
477  /// which must be a FunctionType or a pointer to an allowable type or a
478  /// BlockPointer.
479  QualType getNoReturnType(QualType T, bool AddNoReturn = true);
480
481  /// getCallConvType - Adds the specified calling convention attribute to
482  /// the given type, which must be a FunctionType or a pointer to an
483  /// allowable type.
484  QualType getCallConvType(QualType T, CallingConv CallConv);
485
486  /// getRegParmType - Sets the specified regparm attribute to
487  /// the given type, which must be a FunctionType or a pointer to an
488  /// allowable type.
489  QualType getRegParmType(QualType T, unsigned RegParm);
490
491  /// getComplexType - Return the uniqued reference to the type for a complex
492  /// number with the specified element type.
493  QualType getComplexType(QualType T);
494  CanQualType getComplexType(CanQualType T) {
495    return CanQualType::CreateUnsafe(getComplexType((QualType) T));
496  }
497
498  /// getPointerType - Return the uniqued reference to the type for a pointer to
499  /// the specified type.
500  QualType getPointerType(QualType T);
501  CanQualType getPointerType(CanQualType T) {
502    return CanQualType::CreateUnsafe(getPointerType((QualType) T));
503  }
504
505  /// getBlockPointerType - Return the uniqued reference to the type for a block
506  /// of the specified type.
507  QualType getBlockPointerType(QualType T);
508
509  /// This gets the struct used to keep track of the descriptor for pointer to
510  /// blocks.
511  QualType getBlockDescriptorType();
512
513  // Set the type for a Block descriptor type.
514  void setBlockDescriptorType(QualType T);
515  /// Get the BlockDescriptorType type, or NULL if it hasn't yet been built.
516  QualType getRawBlockdescriptorType() {
517    if (BlockDescriptorType)
518      return getTagDeclType(BlockDescriptorType);
519    return QualType();
520  }
521
522  /// This gets the struct used to keep track of the extended descriptor for
523  /// pointer to blocks.
524  QualType getBlockDescriptorExtendedType();
525
526  // Set the type for a Block descriptor extended type.
527  void setBlockDescriptorExtendedType(QualType T);
528  /// Get the BlockDescriptorExtendedType type, or NULL if it hasn't yet been
529  /// built.
530  QualType getRawBlockdescriptorExtendedType() {
531    if (BlockDescriptorExtendedType)
532      return getTagDeclType(BlockDescriptorExtendedType);
533    return QualType();
534  }
535
536  /// This gets the struct used to keep track of pointer to blocks, complete
537  /// with captured variables.
538  QualType getBlockParmType(bool BlockHasCopyDispose,
539                            llvm::SmallVectorImpl<const Expr *> &Layout);
540
541  /// This builds the struct used for __block variables.
542  QualType BuildByRefType(llvm::StringRef DeclName, QualType Ty);
543
544  /// Returns true iff we need copy/dispose helpers for the given type.
545  bool BlockRequiresCopying(QualType Ty);
546
547  /// getLValueReferenceType - Return the uniqued reference to the type for an
548  /// lvalue reference to the specified type.
549  QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true);
550
551  /// getRValueReferenceType - Return the uniqued reference to the type for an
552  /// rvalue reference to the specified type.
553  QualType getRValueReferenceType(QualType T);
554
555  /// getMemberPointerType - Return the uniqued reference to the type for a
556  /// member pointer to the specified type in the specified class. The class
557  /// is a Type because it could be a dependent name.
558  QualType getMemberPointerType(QualType T, const Type *Cls);
559
560  /// getVariableArrayType - Returns a non-unique reference to the type for a
561  /// variable array of the specified element type.
562  QualType getVariableArrayType(QualType EltTy, Expr *NumElts,
563                                ArrayType::ArraySizeModifier ASM,
564                                unsigned EltTypeQuals,
565                                SourceRange Brackets);
566
567  /// getDependentSizedArrayType - Returns a non-unique reference to
568  /// the type for a dependently-sized array of the specified element
569  /// type. FIXME: We will need these to be uniqued, or at least
570  /// comparable, at some point.
571  QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
572                                      ArrayType::ArraySizeModifier ASM,
573                                      unsigned EltTypeQuals,
574                                      SourceRange Brackets);
575
576  /// getIncompleteArrayType - Returns a unique reference to the type for a
577  /// incomplete array of the specified element type.
578  QualType getIncompleteArrayType(QualType EltTy,
579                                  ArrayType::ArraySizeModifier ASM,
580                                  unsigned EltTypeQuals);
581
582  /// getConstantArrayType - Return the unique reference to the type for a
583  /// constant array of the specified element type.
584  QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize,
585                                ArrayType::ArraySizeModifier ASM,
586                                unsigned EltTypeQuals);
587
588  /// getUnknownSizeVariableArrayType - Return a variable array type with
589  /// all variable indices replaced with unknow [*] size.
590  QualType getUnknownSizeVariableArrayType(QualType Ty);
591
592  /// getVariableArrayDecayedType - Returns a vla type where known sizes
593  /// are replaced with [*]
594  QualType getVariableArrayDecayedType(QualType Ty);
595
596  /// getVectorType - Return the unique reference to a vector type of
597  /// the specified element type and size. VectorType must be a built-in type.
598  QualType getVectorType(QualType VectorType, unsigned NumElts,
599                         VectorType::VectorKind VecKind);
600
601  /// getExtVectorType - Return the unique reference to an extended vector type
602  /// of the specified element type and size.  VectorType must be a built-in
603  /// type.
604  QualType getExtVectorType(QualType VectorType, unsigned NumElts);
605
606  /// getDependentSizedExtVectorType - Returns a non-unique reference to
607  /// the type for a dependently-sized vector of the specified element
608  /// type. FIXME: We will need these to be uniqued, or at least
609  /// comparable, at some point.
610  QualType getDependentSizedExtVectorType(QualType VectorType,
611                                          Expr *SizeExpr,
612                                          SourceLocation AttrLoc);
613
614  /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
615  ///
616  QualType getFunctionNoProtoType(QualType ResultTy,
617                                  const FunctionType::ExtInfo &Info);
618
619  QualType getFunctionNoProtoType(QualType ResultTy) {
620    return getFunctionNoProtoType(ResultTy, FunctionType::ExtInfo());
621  }
622
623  /// getFunctionType - Return a normal function type with a typed argument
624  /// list.  isVariadic indicates whether the argument list includes '...'.
625  QualType getFunctionType(QualType ResultTy, const QualType *ArgArray,
626                           unsigned NumArgs, bool isVariadic,
627                           unsigned TypeQuals, bool hasExceptionSpec,
628                           bool hasAnyExceptionSpec,
629                           unsigned NumExs, const QualType *ExArray,
630                           const FunctionType::ExtInfo &Info);
631
632  /// getTypeDeclType - Return the unique reference to the type for
633  /// the specified type declaration.
634  QualType getTypeDeclType(const TypeDecl *Decl,
635                           const TypeDecl *PrevDecl = 0) {
636    assert(Decl && "Passed null for Decl param");
637    if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
638
639    if (PrevDecl) {
640      assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
641      Decl->TypeForDecl = PrevDecl->TypeForDecl;
642      return QualType(PrevDecl->TypeForDecl, 0);
643    }
644
645    return getTypeDeclTypeSlow(Decl);
646  }
647
648  /// getTypedefType - Return the unique reference to the type for the
649  /// specified typename decl.
650  QualType getTypedefType(const TypedefDecl *Decl, QualType Canon = QualType());
651
652  QualType getRecordType(const RecordDecl *Decl);
653
654  QualType getEnumType(const EnumDecl *Decl);
655
656  QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST);
657
658  QualType getSubstTemplateTypeParmType(const TemplateTypeParmType *Replaced,
659                                        QualType Replacement);
660
661  QualType getTemplateTypeParmType(unsigned Depth, unsigned Index,
662                                   bool ParameterPack,
663                                   IdentifierInfo *Name = 0);
664
665  QualType getTemplateSpecializationType(TemplateName T,
666                                         const TemplateArgument *Args,
667                                         unsigned NumArgs,
668                                         QualType Canon = QualType());
669
670  QualType getCanonicalTemplateSpecializationType(TemplateName T,
671                                                  const TemplateArgument *Args,
672                                                  unsigned NumArgs);
673
674  QualType getTemplateSpecializationType(TemplateName T,
675                                         const TemplateArgumentListInfo &Args,
676                                         QualType Canon = QualType());
677
678  TypeSourceInfo *
679  getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc,
680                                    const TemplateArgumentListInfo &Args,
681                                    QualType Canon = QualType());
682
683  QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
684                             NestedNameSpecifier *NNS,
685                             QualType NamedType);
686  QualType getDependentNameType(ElaboratedTypeKeyword Keyword,
687                                NestedNameSpecifier *NNS,
688                                const IdentifierInfo *Name,
689                                QualType Canon = QualType());
690
691  QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
692                                                  NestedNameSpecifier *NNS,
693                                                  const IdentifierInfo *Name,
694                                          const TemplateArgumentListInfo &Args);
695  QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
696                                                  NestedNameSpecifier *NNS,
697                                                  const IdentifierInfo *Name,
698                                                  unsigned NumArgs,
699                                                  const TemplateArgument *Args);
700
701  QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl);
702
703  QualType getObjCObjectType(QualType Base,
704                             ObjCProtocolDecl * const *Protocols,
705                             unsigned NumProtocols);
706
707  /// getObjCObjectPointerType - Return a ObjCObjectPointerType type
708  /// for the given ObjCObjectType.
709  QualType getObjCObjectPointerType(QualType OIT);
710
711  /// getTypeOfType - GCC extension.
712  QualType getTypeOfExprType(Expr *e);
713  QualType getTypeOfType(QualType t);
714
715  /// getDecltypeType - C++0x decltype.
716  QualType getDecltypeType(Expr *e);
717
718  /// getTagDeclType - Return the unique reference to the type for the
719  /// specified TagDecl (struct/union/class/enum) decl.
720  QualType getTagDeclType(const TagDecl *Decl);
721
722  /// getSizeType - Return the unique type for "size_t" (C99 7.17), defined
723  /// in <stddef.h>. The sizeof operator requires this (C99 6.5.3.4p4).
724  CanQualType getSizeType() const;
725
726  /// getWCharType - In C++, this returns the unique wchar_t type.  In C99, this
727  /// returns a type compatible with the type defined in <stddef.h> as defined
728  /// by the target.
729  QualType getWCharType() const { return WCharTy; }
730
731  /// getSignedWCharType - Return the type of "signed wchar_t".
732  /// Used when in C++, as a GCC extension.
733  QualType getSignedWCharType() const;
734
735  /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
736  /// Used when in C++, as a GCC extension.
737  QualType getUnsignedWCharType() const;
738
739  /// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
740  /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
741  QualType getPointerDiffType() const;
742
743  // getCFConstantStringType - Return the C structure type used to represent
744  // constant CFStrings.
745  QualType getCFConstantStringType();
746
747  // getNSConstantStringType - Return the C structure type used to represent
748  // constant NSStrings.
749  QualType getNSConstantStringType();
750  /// Get the structure type used to representation NSStrings, or NULL
751  /// if it hasn't yet been built.
752  QualType getRawNSConstantStringType() {
753    if (NSConstantStringTypeDecl)
754      return getTagDeclType(NSConstantStringTypeDecl);
755    return QualType();
756  }
757  void setNSConstantStringType(QualType T);
758
759
760  /// Get the structure type used to representation CFStrings, or NULL
761  /// if it hasn't yet been built.
762  QualType getRawCFConstantStringType() {
763    if (CFConstantStringTypeDecl)
764      return getTagDeclType(CFConstantStringTypeDecl);
765    return QualType();
766  }
767  void setCFConstantStringType(QualType T);
768
769  // This setter/getter represents the ObjC type for an NSConstantString.
770  void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl);
771  QualType getObjCConstantStringInterface() const {
772    return ObjCConstantStringType;
773  }
774
775  //// This gets the struct used to keep track of fast enumerations.
776  QualType getObjCFastEnumerationStateType();
777
778  /// Get the ObjCFastEnumerationState type, or NULL if it hasn't yet
779  /// been built.
780  QualType getRawObjCFastEnumerationStateType() {
781    if (ObjCFastEnumerationStateTypeDecl)
782      return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
783    return QualType();
784  }
785
786  void setObjCFastEnumerationStateType(QualType T);
787
788  /// \brief Set the type for the C FILE type.
789  void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; }
790
791  /// \brief Retrieve the C FILE type.
792  QualType getFILEType() {
793    if (FILEDecl)
794      return getTypeDeclType(FILEDecl);
795    return QualType();
796  }
797
798  /// \brief Set the type for the C jmp_buf type.
799  void setjmp_bufDecl(TypeDecl *jmp_bufDecl) {
800    this->jmp_bufDecl = jmp_bufDecl;
801  }
802
803  /// \brief Retrieve the C jmp_buf type.
804  QualType getjmp_bufType() {
805    if (jmp_bufDecl)
806      return getTypeDeclType(jmp_bufDecl);
807    return QualType();
808  }
809
810  /// \brief Set the type for the C sigjmp_buf type.
811  void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) {
812    this->sigjmp_bufDecl = sigjmp_bufDecl;
813  }
814
815  /// \brief Retrieve the C sigjmp_buf type.
816  QualType getsigjmp_bufType() {
817    if (sigjmp_bufDecl)
818      return getTypeDeclType(sigjmp_bufDecl);
819    return QualType();
820  }
821
822  /// getObjCEncodingForType - Emit the ObjC type encoding for the
823  /// given type into \arg S. If \arg NameFields is specified then
824  /// record field names are also encoded.
825  void getObjCEncodingForType(QualType t, std::string &S,
826                              const FieldDecl *Field=0);
827
828  void getLegacyIntegralTypeEncoding(QualType &t) const;
829
830  // Put the string version of type qualifiers into S.
831  void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
832                                       std::string &S) const;
833
834  /// getObjCEncodingForMethodDecl - Return the encoded type for this method
835  /// declaration.
836  void getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, std::string &S);
837
838  /// getObjCEncodingForBlockDecl - Return the encoded type for this block
839  /// declaration.
840  void getObjCEncodingForBlock(const BlockExpr *Expr, std::string& S);
841
842  /// getObjCEncodingForPropertyDecl - Return the encoded type for
843  /// this method declaration. If non-NULL, Container must be either
844  /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
845  /// only be NULL when getting encodings for protocol properties.
846  void getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
847                                      const Decl *Container,
848                                      std::string &S);
849
850  bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
851                                      ObjCProtocolDecl *rProto);
852
853  /// getObjCEncodingTypeSize returns size of type for objective-c encoding
854  /// purpose in characters.
855  CharUnits getObjCEncodingTypeSize(QualType t);
856
857  /// \brief Whether __[u]int128_t identifier is installed.
858  bool isInt128Installed() const { return IsInt128Installed; }
859  void setInt128Installed() { IsInt128Installed = true; }
860
861  /// This setter/getter represents the ObjC 'id' type. It is setup lazily, by
862  /// Sema.  id is always a (typedef for a) pointer type, a pointer to a struct.
863  QualType getObjCIdType() const { return ObjCIdTypedefType; }
864  void setObjCIdType(QualType T);
865
866  void setObjCSelType(QualType T);
867  QualType getObjCSelType() const { return ObjCSelTypedefType; }
868
869  void setObjCProtoType(QualType QT);
870  QualType getObjCProtoType() const { return ObjCProtoType; }
871
872  /// This setter/getter repreents the ObjC 'Class' type. It is setup lazily, by
873  /// Sema.  'Class' is always a (typedef for a) pointer type, a pointer to a
874  /// struct.
875  QualType getObjCClassType() const { return ObjCClassTypedefType; }
876  void setObjCClassType(QualType T);
877
878  void setBuiltinVaListType(QualType T);
879  QualType getBuiltinVaListType() const { return BuiltinVaListType; }
880
881  /// getCVRQualifiedType - Returns a type with additional const,
882  /// volatile, or restrict qualifiers.
883  QualType getCVRQualifiedType(QualType T, unsigned CVR) {
884    return getQualifiedType(T, Qualifiers::fromCVRMask(CVR));
885  }
886
887  /// getQualifiedType - Returns a type with additional qualifiers.
888  QualType getQualifiedType(QualType T, Qualifiers Qs) {
889    if (!Qs.hasNonFastQualifiers())
890      return T.withFastQualifiers(Qs.getFastQualifiers());
891    QualifierCollector Qc(Qs);
892    const Type *Ptr = Qc.strip(T);
893    return getExtQualType(Ptr, Qc);
894  }
895
896  /// getQualifiedType - Returns a type with additional qualifiers.
897  QualType getQualifiedType(const Type *T, Qualifiers Qs) {
898    if (!Qs.hasNonFastQualifiers())
899      return QualType(T, Qs.getFastQualifiers());
900    return getExtQualType(T, Qs);
901  }
902
903  DeclarationNameInfo getNameForTemplate(TemplateName Name,
904                                         SourceLocation NameLoc);
905
906  TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin,
907                                         UnresolvedSetIterator End);
908
909  TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
910                                        bool TemplateKeyword,
911                                        TemplateDecl *Template);
912
913  TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
914                                        const IdentifierInfo *Name);
915  TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
916                                        OverloadedOperatorKind Operator);
917
918  enum GetBuiltinTypeError {
919    GE_None,              //< No error
920    GE_Missing_stdio,     //< Missing a type from <stdio.h>
921    GE_Missing_setjmp     //< Missing a type from <setjmp.h>
922  };
923
924  /// GetBuiltinType - Return the type for the specified builtin.  If
925  /// IntegerConstantArgs is non-null, it is filled in with a bitmask of
926  /// arguments to the builtin that are required to be integer constant
927  /// expressions.
928  QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error,
929                          unsigned *IntegerConstantArgs = 0);
930
931private:
932  CanQualType getFromTargetType(unsigned Type) const;
933
934  //===--------------------------------------------------------------------===//
935  //                         Type Predicates.
936  //===--------------------------------------------------------------------===//
937
938public:
939  /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
940  /// garbage collection attribute.
941  ///
942  Qualifiers::GC getObjCGCAttrKind(const QualType &Ty) const;
943
944  /// areCompatibleVectorTypes - Return true if the given vector types
945  /// are of the same unqualified type or if they are equivalent to the same
946  /// GCC vector type, ignoring whether they are target-specific (AltiVec or
947  /// Neon) types.
948  bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec);
949
950  /// isObjCNSObjectType - Return true if this is an NSObject object with
951  /// its NSObject attribute set.
952  bool isObjCNSObjectType(QualType Ty) const;
953
954  //===--------------------------------------------------------------------===//
955  //                         Type Sizing and Analysis
956  //===--------------------------------------------------------------------===//
957
958  /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
959  /// scalar floating point type.
960  const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
961
962  /// getTypeInfo - Get the size and alignment of the specified complete type in
963  /// bits.
964  std::pair<uint64_t, unsigned> getTypeInfo(const Type *T);
965  std::pair<uint64_t, unsigned> getTypeInfo(QualType T) {
966    return getTypeInfo(T.getTypePtr());
967  }
968
969  /// getTypeSize - Return the size of the specified type, in bits.  This method
970  /// does not work on incomplete types.
971  uint64_t getTypeSize(QualType T) {
972    return getTypeInfo(T).first;
973  }
974  uint64_t getTypeSize(const Type *T) {
975    return getTypeInfo(T).first;
976  }
977
978  /// getCharWidth - Return the size of the character type, in bits
979  uint64_t getCharWidth() {
980    return getTypeSize(CharTy);
981  }
982
983  /// getTypeSizeInChars - Return the size of the specified type, in characters.
984  /// This method does not work on incomplete types.
985  CharUnits getTypeSizeInChars(QualType T);
986  CharUnits getTypeSizeInChars(const Type *T);
987
988  /// getTypeAlign - Return the ABI-specified alignment of a type, in bits.
989  /// This method does not work on incomplete types.
990  unsigned getTypeAlign(QualType T) {
991    return getTypeInfo(T).second;
992  }
993  unsigned getTypeAlign(const Type *T) {
994    return getTypeInfo(T).second;
995  }
996
997  /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
998  /// characters. This method does not work on incomplete types.
999  CharUnits getTypeAlignInChars(QualType T);
1000  CharUnits getTypeAlignInChars(const Type *T);
1001
1002  std::pair<CharUnits, CharUnits> getTypeInfoInChars(const Type *T);
1003  std::pair<CharUnits, CharUnits> getTypeInfoInChars(QualType T);
1004
1005  /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1006  /// type for the current target in bits.  This can be different than the ABI
1007  /// alignment in cases where it is beneficial for performance to overalign
1008  /// a data type.
1009  unsigned getPreferredTypeAlign(const Type *T);
1010
1011  /// getDeclAlign - Return a conservative estimate of the alignment of
1012  /// the specified decl.  Note that bitfields do not have a valid alignment, so
1013  /// this method will assert on them.
1014  /// If @p RefAsPointee, references are treated like their underlying type
1015  /// (for alignof), else they're treated like pointers (for CodeGen).
1016  CharUnits getDeclAlign(const Decl *D, bool RefAsPointee = false);
1017
1018  /// getASTRecordLayout - Get or compute information about the layout of the
1019  /// specified record (struct/union/class), which indicates its size and field
1020  /// position information.
1021  const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D);
1022
1023  /// getASTObjCInterfaceLayout - Get or compute information about the
1024  /// layout of the specified Objective-C interface.
1025  const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D);
1026
1027  void DumpRecordLayout(const RecordDecl *RD, llvm::raw_ostream &OS);
1028
1029  /// getASTObjCImplementationLayout - Get or compute information about
1030  /// the layout of the specified Objective-C implementation. This may
1031  /// differ from the interface if synthesized ivars are present.
1032  const ASTRecordLayout &
1033  getASTObjCImplementationLayout(const ObjCImplementationDecl *D);
1034
1035  /// getKeyFunction - Get the key function for the given record decl, or NULL
1036  /// if there isn't one.  The key function is, according to the Itanium C++ ABI
1037  /// section 5.2.3:
1038  ///
1039  /// ...the first non-pure virtual function that is not inline at the point
1040  /// of class definition.
1041  const CXXMethodDecl *getKeyFunction(const CXXRecordDecl *RD);
1042
1043  bool isNearlyEmpty(const CXXRecordDecl *RD);
1044
1045  void ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
1046                               llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars);
1047
1048  void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass,
1049                            llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars);
1050
1051  unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI);
1052  void CollectInheritedProtocols(const Decl *CDecl,
1053                          llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols);
1054
1055  //===--------------------------------------------------------------------===//
1056  //                            Type Operators
1057  //===--------------------------------------------------------------------===//
1058
1059  /// getCanonicalType - Return the canonical (structural) type corresponding to
1060  /// the specified potentially non-canonical type.  The non-canonical version
1061  /// of a type may have many "decorated" versions of types.  Decorators can
1062  /// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
1063  /// to be free of any of these, allowing two canonical types to be compared
1064  /// for exact equality with a simple pointer comparison.
1065  CanQualType getCanonicalType(QualType T);
1066  const Type *getCanonicalType(const Type *T) {
1067    return T->getCanonicalTypeInternal().getTypePtr();
1068  }
1069
1070  /// getCanonicalParamType - Return the canonical parameter type
1071  /// corresponding to the specific potentially non-canonical one.
1072  /// Qualifiers are stripped off, functions are turned into function
1073  /// pointers, and arrays decay one level into pointers.
1074  CanQualType getCanonicalParamType(QualType T);
1075
1076  /// \brief Determine whether the given types are equivalent.
1077  bool hasSameType(QualType T1, QualType T2) {
1078    return getCanonicalType(T1) == getCanonicalType(T2);
1079  }
1080
1081  /// \brief Returns this type as a completely-unqualified array type,
1082  /// capturing the qualifiers in Quals. This will remove the minimal amount of
1083  /// sugaring from the types, similar to the behavior of
1084  /// QualType::getUnqualifiedType().
1085  ///
1086  /// \param T is the qualified type, which may be an ArrayType
1087  ///
1088  /// \param Quals will receive the full set of qualifiers that were
1089  /// applied to the array.
1090  ///
1091  /// \returns if this is an array type, the completely unqualified array type
1092  /// that corresponds to it. Otherwise, returns T.getUnqualifiedType().
1093  QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals);
1094
1095  /// \brief Determine whether the given types are equivalent after
1096  /// cvr-qualifiers have been removed.
1097  bool hasSameUnqualifiedType(QualType T1, QualType T2) {
1098    CanQualType CT1 = getCanonicalType(T1);
1099    CanQualType CT2 = getCanonicalType(T2);
1100
1101    Qualifiers Quals;
1102    QualType UnqualT1 = getUnqualifiedArrayType(CT1, Quals);
1103    QualType UnqualT2 = getUnqualifiedArrayType(CT2, Quals);
1104    return UnqualT1 == UnqualT2;
1105  }
1106
1107  bool UnwrapSimilarPointerTypes(QualType &T1, QualType &T2);
1108
1109  /// \brief Retrieves the "canonical" nested name specifier for a
1110  /// given nested name specifier.
1111  ///
1112  /// The canonical nested name specifier is a nested name specifier
1113  /// that uniquely identifies a type or namespace within the type
1114  /// system. For example, given:
1115  ///
1116  /// \code
1117  /// namespace N {
1118  ///   struct S {
1119  ///     template<typename T> struct X { typename T* type; };
1120  ///   };
1121  /// }
1122  ///
1123  /// template<typename T> struct Y {
1124  ///   typename N::S::X<T>::type member;
1125  /// };
1126  /// \endcode
1127  ///
1128  /// Here, the nested-name-specifier for N::S::X<T>:: will be
1129  /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined
1130  /// by declarations in the type system and the canonical type for
1131  /// the template type parameter 'T' is template-param-0-0.
1132  NestedNameSpecifier *
1133  getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS);
1134
1135  /// \brief Retrieves the default calling convention to use for
1136  /// C++ instance methods.
1137  CallingConv getDefaultMethodCallConv();
1138
1139  /// \brief Retrieves the canonical representation of the given
1140  /// calling convention.
1141  CallingConv getCanonicalCallConv(CallingConv CC) {
1142    if (CC == CC_C)
1143      return CC_Default;
1144    return CC;
1145  }
1146
1147  /// \brief Determines whether two calling conventions name the same
1148  /// calling convention.
1149  bool isSameCallConv(CallingConv lcc, CallingConv rcc) {
1150    return (getCanonicalCallConv(lcc) == getCanonicalCallConv(rcc));
1151  }
1152
1153  /// \brief Retrieves the "canonical" template name that refers to a
1154  /// given template.
1155  ///
1156  /// The canonical template name is the simplest expression that can
1157  /// be used to refer to a given template. For most templates, this
1158  /// expression is just the template declaration itself. For example,
1159  /// the template std::vector can be referred to via a variety of
1160  /// names---std::vector, ::std::vector, vector (if vector is in
1161  /// scope), etc.---but all of these names map down to the same
1162  /// TemplateDecl, which is used to form the canonical template name.
1163  ///
1164  /// Dependent template names are more interesting. Here, the
1165  /// template name could be something like T::template apply or
1166  /// std::allocator<T>::template rebind, where the nested name
1167  /// specifier itself is dependent. In this case, the canonical
1168  /// template name uses the shortest form of the dependent
1169  /// nested-name-specifier, which itself contains all canonical
1170  /// types, values, and templates.
1171  TemplateName getCanonicalTemplateName(TemplateName Name);
1172
1173  /// \brief Determine whether the given template names refer to the same
1174  /// template.
1175  bool hasSameTemplateName(TemplateName X, TemplateName Y);
1176
1177  /// \brief Retrieve the "canonical" template argument.
1178  ///
1179  /// The canonical template argument is the simplest template argument
1180  /// (which may be a type, value, expression, or declaration) that
1181  /// expresses the value of the argument.
1182  TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg);
1183
1184  /// Type Query functions.  If the type is an instance of the specified class,
1185  /// return the Type pointer for the underlying maximally pretty type.  This
1186  /// is a member of ASTContext because this may need to do some amount of
1187  /// canonicalization, e.g. to move type qualifiers into the element type.
1188  const ArrayType *getAsArrayType(QualType T);
1189  const ConstantArrayType *getAsConstantArrayType(QualType T) {
1190    return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T));
1191  }
1192  const VariableArrayType *getAsVariableArrayType(QualType T) {
1193    return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T));
1194  }
1195  const IncompleteArrayType *getAsIncompleteArrayType(QualType T) {
1196    return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
1197  }
1198  const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T) {
1199    return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T));
1200  }
1201
1202  /// getBaseElementType - Returns the innermost element type of an array type.
1203  /// For example, will return "int" for int[m][n]
1204  QualType getBaseElementType(const ArrayType *VAT);
1205
1206  /// getBaseElementType - Returns the innermost element type of a type
1207  /// (which needn't actually be an array type).
1208  QualType getBaseElementType(QualType QT);
1209
1210  /// getConstantArrayElementCount - Returns number of constant array elements.
1211  uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const;
1212
1213  /// getArrayDecayedType - Return the properly qualified result of decaying the
1214  /// specified array type to a pointer.  This operation is non-trivial when
1215  /// handling typedefs etc.  The canonical type of "T" must be an array type,
1216  /// this returns a pointer to a properly qualified element of the array.
1217  ///
1218  /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
1219  QualType getArrayDecayedType(QualType T);
1220
1221  /// getPromotedIntegerType - Returns the type that Promotable will
1222  /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
1223  /// integer type.
1224  QualType getPromotedIntegerType(QualType PromotableType);
1225
1226  /// \brief Whether this is a promotable bitfield reference according
1227  /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
1228  ///
1229  /// \returns the type this bit-field will promote to, or NULL if no
1230  /// promotion occurs.
1231  QualType isPromotableBitField(Expr *E);
1232
1233  /// getIntegerTypeOrder - Returns the highest ranked integer type:
1234  /// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
1235  /// LHS < RHS, return -1.
1236  int getIntegerTypeOrder(QualType LHS, QualType RHS);
1237
1238  /// getFloatingTypeOrder - Compare the rank of the two specified floating
1239  /// point types, ignoring the domain of the type (i.e. 'double' ==
1240  /// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
1241  /// LHS < RHS, return -1.
1242  int getFloatingTypeOrder(QualType LHS, QualType RHS);
1243
1244  /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
1245  /// point or a complex type (based on typeDomain/typeSize).
1246  /// 'typeDomain' is a real floating point or complex type.
1247  /// 'typeSize' is a real floating point or complex type.
1248  QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
1249                                             QualType typeDomain) const;
1250
1251private:
1252  // Helper for integer ordering
1253  unsigned getIntegerRank(Type* T);
1254
1255public:
1256
1257  //===--------------------------------------------------------------------===//
1258  //                    Type Compatibility Predicates
1259  //===--------------------------------------------------------------------===//
1260
1261  /// Compatibility predicates used to check assignment expressions.
1262  bool typesAreCompatible(QualType T1, QualType T2,
1263                          bool CompareUnqualified = false); // C99 6.2.7p1
1264
1265  bool typesAreBlockPointerCompatible(QualType, QualType);
1266
1267  bool isObjCIdType(QualType T) const {
1268    return T == ObjCIdTypedefType;
1269  }
1270  bool isObjCClassType(QualType T) const {
1271    return T == ObjCClassTypedefType;
1272  }
1273  bool isObjCSelType(QualType T) const {
1274    return T == ObjCSelTypedefType;
1275  }
1276  bool QualifiedIdConformsQualifiedId(QualType LHS, QualType RHS);
1277  bool ObjCQualifiedIdTypesAreCompatible(QualType LHS, QualType RHS,
1278                                         bool ForCompare);
1279
1280  bool ObjCQualifiedClassTypesAreCompatible(QualType LHS, QualType RHS);
1281
1282  // Check the safety of assignment from LHS to RHS
1283  bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
1284                               const ObjCObjectPointerType *RHSOPT);
1285  bool canAssignObjCInterfaces(const ObjCObjectType *LHS,
1286                               const ObjCObjectType *RHS);
1287  bool canAssignObjCInterfacesInBlockPointer(
1288                                          const ObjCObjectPointerType *LHSOPT,
1289                                          const ObjCObjectPointerType *RHSOPT);
1290  bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
1291  QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT,
1292                                   const ObjCObjectPointerType *RHSOPT);
1293  bool canBindObjCObjectType(QualType To, QualType From);
1294
1295  // Functions for calculating composite types
1296  QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false,
1297                      bool Unqualified = false);
1298  QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false,
1299                              bool Unqualified = false);
1300  QualType mergeFunctionArgumentTypes(QualType, QualType,
1301                                      bool OfBlockPointer=false,
1302                                      bool Unqualified = false);
1303  QualType mergeTransparentUnionType(QualType, QualType,
1304                                     bool OfBlockPointer=false,
1305                                     bool Unqualified = false);
1306
1307  QualType mergeObjCGCQualifiers(QualType, QualType);
1308
1309  void ResetObjCLayout(const ObjCContainerDecl *CD) {
1310    ObjCLayouts[CD] = 0;
1311  }
1312
1313  //===--------------------------------------------------------------------===//
1314  //                    Integer Predicates
1315  //===--------------------------------------------------------------------===//
1316
1317  // The width of an integer, as defined in C99 6.2.6.2. This is the number
1318  // of bits in an integer type excluding any padding bits.
1319  unsigned getIntWidth(QualType T);
1320
1321  // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
1322  // unsigned integer type.  This method takes a signed type, and returns the
1323  // corresponding unsigned integer type.
1324  QualType getCorrespondingUnsignedType(QualType T);
1325
1326  //===--------------------------------------------------------------------===//
1327  //                    Type Iterators.
1328  //===--------------------------------------------------------------------===//
1329
1330  typedef std::vector<Type*>::iterator       type_iterator;
1331  typedef std::vector<Type*>::const_iterator const_type_iterator;
1332
1333  type_iterator types_begin() { return Types.begin(); }
1334  type_iterator types_end() { return Types.end(); }
1335  const_type_iterator types_begin() const { return Types.begin(); }
1336  const_type_iterator types_end() const { return Types.end(); }
1337
1338  //===--------------------------------------------------------------------===//
1339  //                    Integer Values
1340  //===--------------------------------------------------------------------===//
1341
1342  /// MakeIntValue - Make an APSInt of the appropriate width and
1343  /// signedness for the given \arg Value and integer \arg Type.
1344  llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) {
1345    llvm::APSInt Res(getIntWidth(Type), !Type->isSignedIntegerType());
1346    Res = Value;
1347    return Res;
1348  }
1349
1350  /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1351  ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D);
1352  /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1353  ObjCCategoryImplDecl   *getObjCImplementation(ObjCCategoryDecl *D);
1354
1355  /// \brief Set the implementation of ObjCInterfaceDecl.
1356  void setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1357                             ObjCImplementationDecl *ImplD);
1358  /// \brief Set the implementation of ObjCCategoryDecl.
1359  void setObjCImplementation(ObjCCategoryDecl *CatD,
1360                             ObjCCategoryImplDecl *ImplD);
1361
1362  /// \brief Allocate an uninitialized TypeSourceInfo.
1363  ///
1364  /// The caller should initialize the memory held by TypeSourceInfo using
1365  /// the TypeLoc wrappers.
1366  ///
1367  /// \param T the type that will be the basis for type source info. This type
1368  /// should refer to how the declarator was written in source code, not to
1369  /// what type semantic analysis resolved the declarator to.
1370  ///
1371  /// \param Size the size of the type info to create, or 0 if the size
1372  /// should be calculated based on the type.
1373  TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0);
1374
1375  /// \brief Allocate a TypeSourceInfo where all locations have been
1376  /// initialized to a given location, which defaults to the empty
1377  /// location.
1378  TypeSourceInfo *
1379  getTrivialTypeSourceInfo(QualType T, SourceLocation Loc = SourceLocation());
1380
1381  TypeSourceInfo *getNullTypeSourceInfo() { return &NullTypeSourceInfo; }
1382
1383  /// \brief Add a deallocation callback that will be invoked when the
1384  /// ASTContext is destroyed.
1385  ///
1386  /// \brief Callback A callback function that will be invoked on destruction.
1387  ///
1388  /// \brief Data Pointer data that will be provided to the callback function
1389  /// when it is called.
1390  void AddDeallocation(void (*Callback)(void*), void *Data);
1391
1392  GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD);
1393  GVALinkage GetGVALinkageForVariable(const VarDecl *VD);
1394
1395  /// \brief Determines if the decl can be CodeGen'ed or deserialized from PCH
1396  /// lazily, only when used; this is only relevant for function or file scoped
1397  /// var definitions.
1398  ///
1399  /// \returns true if the function/var must be CodeGen'ed/deserialized even if
1400  /// it is not used.
1401  bool DeclMustBeEmitted(const Decl *D);
1402
1403  //===--------------------------------------------------------------------===//
1404  //                    Statistics
1405  //===--------------------------------------------------------------------===//
1406
1407  /// \brief The number of implicitly-declared default constructors.
1408  static unsigned NumImplicitDefaultConstructors;
1409
1410  /// \brief The number of implicitly-declared default constructors for
1411  /// which declarations were built.
1412  static unsigned NumImplicitDefaultConstructorsDeclared;
1413
1414  /// \brief The number of implicitly-declared copy constructors.
1415  static unsigned NumImplicitCopyConstructors;
1416
1417  /// \brief The number of implicitly-declared copy constructors for
1418  /// which declarations were built.
1419  static unsigned NumImplicitCopyConstructorsDeclared;
1420
1421  /// \brief The number of implicitly-declared copy assignment operators.
1422  static unsigned NumImplicitCopyAssignmentOperators;
1423
1424  /// \brief The number of implicitly-declared copy assignment operators for
1425  /// which declarations were built.
1426  static unsigned NumImplicitCopyAssignmentOperatorsDeclared;
1427
1428  /// \brief The number of implicitly-declared destructors.
1429  static unsigned NumImplicitDestructors;
1430
1431  /// \brief The number of implicitly-declared destructors for which
1432  /// declarations were built.
1433  static unsigned NumImplicitDestructorsDeclared;
1434
1435private:
1436  ASTContext(const ASTContext&); // DO NOT IMPLEMENT
1437  void operator=(const ASTContext&); // DO NOT IMPLEMENT
1438
1439  void InitBuiltinTypes();
1440  void InitBuiltinType(CanQualType &R, BuiltinType::Kind K);
1441
1442  // Return the ObjC type encoding for a given type.
1443  void getObjCEncodingForTypeImpl(QualType t, std::string &S,
1444                                  bool ExpandPointedToStructures,
1445                                  bool ExpandStructures,
1446                                  const FieldDecl *Field,
1447                                  bool OutermostType = false,
1448                                  bool EncodingProperty = false);
1449
1450  const ASTRecordLayout &getObjCLayout(const ObjCInterfaceDecl *D,
1451                                       const ObjCImplementationDecl *Impl);
1452
1453private:
1454  /// \brief A set of deallocations that should be performed when the
1455  /// ASTContext is destroyed.
1456  llvm::SmallVector<std::pair<void (*)(void*), void *>, 16> Deallocations;
1457
1458  // FIXME: This currently contains the set of StoredDeclMaps used
1459  // by DeclContext objects.  This probably should not be in ASTContext,
1460  // but we include it here so that ASTContext can quickly deallocate them.
1461  llvm::PointerIntPair<StoredDeclsMap*,1> LastSDM;
1462
1463  /// \brief A counter used to uniquely identify "blocks".
1464  unsigned int UniqueBlockByRefTypeID;
1465  unsigned int UniqueBlockParmTypeID;
1466
1467  friend class DeclContext;
1468  friend class DeclarationNameTable;
1469  void ReleaseDeclContextMaps();
1470};
1471
1472/// @brief Utility function for constructing a nullary selector.
1473static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
1474  IdentifierInfo* II = &Ctx.Idents.get(name);
1475  return Ctx.Selectors.getSelector(0, &II);
1476}
1477
1478/// @brief Utility function for constructing an unary selector.
1479static inline Selector GetUnarySelector(const char* name, ASTContext& Ctx) {
1480  IdentifierInfo* II = &Ctx.Idents.get(name);
1481  return Ctx.Selectors.getSelector(1, &II);
1482}
1483
1484}  // end namespace clang
1485
1486// operator new and delete aren't allowed inside namespaces.
1487// The throw specifications are mandated by the standard.
1488/// @brief Placement new for using the ASTContext's allocator.
1489///
1490/// This placement form of operator new uses the ASTContext's allocator for
1491/// obtaining memory. It is a non-throwing new, which means that it returns
1492/// null on error. (If that is what the allocator does. The current does, so if
1493/// this ever changes, this operator will have to be changed, too.)
1494/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
1495/// @code
1496/// // Default alignment (8)
1497/// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
1498/// // Specific alignment
1499/// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
1500/// @endcode
1501/// Please note that you cannot use delete on the pointer; it must be
1502/// deallocated using an explicit destructor call followed by
1503/// @c Context.Deallocate(Ptr).
1504///
1505/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
1506/// @param C The ASTContext that provides the allocator.
1507/// @param Alignment The alignment of the allocated memory (if the underlying
1508///                  allocator supports it).
1509/// @return The allocated memory. Could be NULL.
1510inline void *operator new(size_t Bytes, clang::ASTContext &C,
1511                          size_t Alignment) throw () {
1512  return C.Allocate(Bytes, Alignment);
1513}
1514/// @brief Placement delete companion to the new above.
1515///
1516/// This operator is just a companion to the new above. There is no way of
1517/// invoking it directly; see the new operator for more details. This operator
1518/// is called implicitly by the compiler if a placement new expression using
1519/// the ASTContext throws in the object constructor.
1520inline void operator delete(void *Ptr, clang::ASTContext &C, size_t)
1521              throw () {
1522  C.Deallocate(Ptr);
1523}
1524
1525/// This placement form of operator new[] uses the ASTContext's allocator for
1526/// obtaining memory. It is a non-throwing new[], which means that it returns
1527/// null on error.
1528/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
1529/// @code
1530/// // Default alignment (8)
1531/// char *data = new (Context) char[10];
1532/// // Specific alignment
1533/// char *data = new (Context, 4) char[10];
1534/// @endcode
1535/// Please note that you cannot use delete on the pointer; it must be
1536/// deallocated using an explicit destructor call followed by
1537/// @c Context.Deallocate(Ptr).
1538///
1539/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
1540/// @param C The ASTContext that provides the allocator.
1541/// @param Alignment The alignment of the allocated memory (if the underlying
1542///                  allocator supports it).
1543/// @return The allocated memory. Could be NULL.
1544inline void *operator new[](size_t Bytes, clang::ASTContext& C,
1545                            size_t Alignment = 8) throw () {
1546  return C.Allocate(Bytes, Alignment);
1547}
1548
1549/// @brief Placement delete[] companion to the new[] above.
1550///
1551/// This operator is just a companion to the new[] above. There is no way of
1552/// invoking it directly; see the new[] operator for more details. This operator
1553/// is called implicitly by the compiler if a placement new[] expression using
1554/// the ASTContext throws in the object constructor.
1555inline void operator delete[](void *Ptr, clang::ASTContext &C, size_t)
1556              throw () {
1557  C.Deallocate(Ptr);
1558}
1559
1560#endif
1561