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