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