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