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