ASTContext.h revision b2dbbb99e12806eaaf53b7ccabc32f42b5719443
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/AST/Attr.h"
20#include "clang/AST/Builtins.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/NestedNameSpecifier.h"
23#include "clang/AST/TemplateName.h"
24#include "clang/AST/Type.h"
25#include "clang/Basic/SourceLocation.h"
26#include "llvm/ADT/DenseMap.h"
27#include "llvm/ADT/FoldingSet.h"
28#include "llvm/ADT/OwningPtr.h"
29#include "llvm/Support/Allocator.h"
30#include <vector>
31
32namespace llvm {
33  struct fltSemantics;
34}
35
36namespace clang {
37  class FileManager;
38  class ASTRecordLayout;
39  class Expr;
40  class ExternalASTSource;
41  class IdentifierTable;
42  class SelectorTable;
43  class SourceManager;
44  class TargetInfo;
45  // Decls
46  class Decl;
47  class ObjCPropertyDecl;
48  class RecordDecl;
49  class TagDecl;
50  class TranslationUnitDecl;
51  class TypeDecl;
52  class TypedefDecl;
53  class TemplateTypeParmDecl;
54  class FieldDecl;
55  class ObjCIvarRefExpr;
56  class ObjCIvarDecl;
57
58/// ASTContext - This class holds long-lived AST nodes (such as types and
59/// decls) that can be referred to throughout the semantic analysis of a file.
60class ASTContext {
61  std::vector<Type*> Types;
62  llvm::FoldingSet<ExtQualType> ExtQualTypes;
63  llvm::FoldingSet<ComplexType> ComplexTypes;
64  llvm::FoldingSet<PointerType> PointerTypes;
65  llvm::FoldingSet<BlockPointerType> BlockPointerTypes;
66  llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes;
67  llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes;
68  llvm::FoldingSet<MemberPointerType> MemberPointerTypes;
69  llvm::FoldingSet<ConstantArrayType> ConstantArrayTypes;
70  llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
71  std::vector<VariableArrayType*> VariableArrayTypes;
72  std::vector<DependentSizedArrayType*> DependentSizedArrayTypes;
73  llvm::FoldingSet<VectorType> VectorTypes;
74  llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes;
75  llvm::FoldingSet<FunctionProtoType> FunctionProtoTypes;
76  llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes;
77  llvm::FoldingSet<TemplateSpecializationType> TemplateSpecializationTypes;
78  llvm::FoldingSet<QualifiedNameType> QualifiedNameTypes;
79  llvm::FoldingSet<TypenameType> TypenameTypes;
80  llvm::FoldingSet<ObjCQualifiedInterfaceType> ObjCQualifiedInterfaceTypes;
81  llvm::FoldingSet<ObjCQualifiedIdType> ObjCQualifiedIdTypes;
82
83  llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames;
84  llvm::FoldingSet<DependentTemplateName> DependentTemplateNames;
85
86  /// \brief The set of nested name specifiers.
87  ///
88  /// This set is managed by the NestedNameSpecifier class.
89  llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers;
90  NestedNameSpecifier *GlobalNestedNameSpecifier;
91  friend class NestedNameSpecifier;
92
93  /// ASTRecordLayouts - A cache mapping from RecordDecls to ASTRecordLayouts.
94  ///  This is lazily created.  This is intentionally not serialized.
95  llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*> ASTRecordLayouts;
96  llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*> ObjCLayouts;
97
98  llvm::DenseMap<unsigned, FixedWidthIntType*> SignedFixedWidthIntTypes;
99  llvm::DenseMap<unsigned, FixedWidthIntType*> UnsignedFixedWidthIntTypes;
100
101  // FIXME: ASTRecordForInterface/ASTFieldForIvarRef and addRecordToClass and
102  // getFieldDecl be part of the backend (i.e. CodeGenTypes)?
103  llvm::DenseMap<const ObjCInterfaceDecl*, RecordDecl*> ASTRecordForInterface;
104
105  /// BuiltinVaListType - built-in va list type.
106  /// This is initially null and set by Sema::LazilyCreateBuiltin when
107  /// a builtin that takes a valist is encountered.
108  QualType BuiltinVaListType;
109
110  /// ObjCIdType - a pseudo built-in typedef type (set by Sema).
111  QualType ObjCIdType;
112  const RecordType *IdStructType;
113
114  /// ObjCSelType - another pseudo built-in typedef type (set by Sema).
115  QualType ObjCSelType;
116  const RecordType *SelStructType;
117
118  /// ObjCProtoType - another pseudo built-in typedef type (set by Sema).
119  QualType ObjCProtoType;
120  const RecordType *ProtoStructType;
121
122  /// ObjCClassType - another pseudo built-in typedef type (set by Sema).
123  QualType ObjCClassType;
124  const RecordType *ClassStructType;
125
126  QualType ObjCConstantStringType;
127  RecordDecl *CFConstantStringTypeDecl;
128
129  RecordDecl *ObjCFastEnumerationStateTypeDecl;
130
131  TranslationUnitDecl *TUDecl;
132
133  /// SourceMgr - The associated SourceManager object.
134  SourceManager &SourceMgr;
135
136  /// LangOpts - The language options used to create the AST associated with
137  ///  this ASTContext object.
138  LangOptions LangOpts;
139
140  /// MallocAlloc/BumpAlloc - The allocator objects used to create AST objects.
141  bool FreeMemory;
142  llvm::MallocAllocator MallocAlloc;
143  llvm::BumpPtrAllocator BumpAlloc;
144public:
145  TargetInfo &Target;
146  IdentifierTable &Idents;
147  SelectorTable &Selectors;
148  DeclarationNameTable DeclarationNames;
149  llvm::OwningPtr<ExternalASTSource> ExternalSource;
150
151  SourceManager& getSourceManager() { return SourceMgr; }
152  const SourceManager& getSourceManager() const { return SourceMgr; }
153  void *Allocate(unsigned Size, unsigned Align = 8) {
154    return FreeMemory ? MallocAlloc.Allocate(Size, Align) :
155                        BumpAlloc.Allocate(Size, Align);
156  }
157  void Deallocate(void *Ptr) {
158    if (FreeMemory)
159      MallocAlloc.Deallocate(Ptr);
160  }
161  const LangOptions& getLangOptions() const { return LangOpts; }
162
163  FullSourceLoc getFullLoc(SourceLocation Loc) const {
164    return FullSourceLoc(Loc,SourceMgr);
165  }
166
167  TranslationUnitDecl *getTranslationUnitDecl() const { return TUDecl; }
168
169  Builtin::Context BuiltinInfo;
170
171  // Builtin Types.
172  QualType VoidTy;
173  QualType BoolTy;
174  QualType CharTy;
175  QualType WCharTy; // [C++ 3.9.1p5], integer type in C99.
176  QualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty;
177  QualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy;
178  QualType UnsignedLongLongTy, UnsignedInt128Ty;
179  QualType FloatTy, DoubleTy, LongDoubleTy;
180  QualType FloatComplexTy, DoubleComplexTy, LongDoubleComplexTy;
181  QualType VoidPtrTy;
182  QualType OverloadTy;
183  QualType DependentTy;
184
185  ASTContext(const LangOptions& LOpts, SourceManager &SM, TargetInfo &t,
186             IdentifierTable &idents, SelectorTable &sels,
187             bool FreeMemory = true, unsigned size_reserve=0,
188             bool InitializeBuiltins = true);
189
190  ~ASTContext();
191
192  /// \brief Initialize builtins.
193  ///
194  /// Typically, this routine will be called automatically by the
195  /// constructor. However, in certain cases (e.g., when there is a
196  /// PCH file to be loaded), the constructor does not perform
197  /// initialization for builtins. This routine can be called to
198  /// perform the initialization.
199  void InitializeBuiltins(IdentifierTable &idents);
200
201  /// \brief Attach an external AST source to the AST context.
202  ///
203  /// The external AST source provides the ability to load parts of
204  /// the abstract syntax tree as needed from some external storage,
205  /// e.g., a precompiled header.
206  void setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source);
207
208  /// \brief Retrieve a pointer to the external AST source associated
209  /// with this AST context, if any.
210  ExternalASTSource *getExternalSource() const { return ExternalSource.get(); }
211
212  void PrintStats() const;
213  const std::vector<Type*>& getTypes() const { return Types; }
214
215  //===--------------------------------------------------------------------===//
216  //                           Type Constructors
217  //===--------------------------------------------------------------------===//
218
219  /// getAddSpaceQualType - Return the uniqued reference to the type for an
220  /// address space qualified type with the specified type and address space.
221  /// The resulting type has a union of the qualifiers from T and the address
222  /// space. If T already has an address space specifier, it is silently
223  /// replaced.
224  QualType getAddrSpaceQualType(QualType T, unsigned AddressSpace);
225
226  /// getObjCGCQualType - Returns the uniqued reference to the type for an
227  /// objc gc qualified type. The retulting type has a union of the qualifiers
228  /// from T and the gc attribute.
229  QualType getObjCGCQualType(QualType T, QualType::GCAttrTypes gcAttr);
230
231  /// getComplexType - Return the uniqued reference to the type for a complex
232  /// number with the specified element type.
233  QualType getComplexType(QualType T);
234
235  /// getPointerType - Return the uniqued reference to the type for a pointer to
236  /// the specified type.
237  QualType getPointerType(QualType T);
238
239  /// getBlockPointerType - Return the uniqued reference to the type for a block
240  /// of the specified type.
241  QualType getBlockPointerType(QualType T);
242
243  /// getLValueReferenceType - Return the uniqued reference to the type for an
244  /// lvalue reference to the specified type.
245  QualType getLValueReferenceType(QualType T);
246
247  /// getRValueReferenceType - Return the uniqued reference to the type for an
248  /// rvalue reference to the specified type.
249  QualType getRValueReferenceType(QualType T);
250
251  /// getMemberPointerType - Return the uniqued reference to the type for a
252  /// member pointer to the specified type in the specified class. The class
253  /// is a Type because it could be a dependent name.
254  QualType getMemberPointerType(QualType T, const Type *Cls);
255
256  /// getVariableArrayType - Returns a non-unique reference to the type for a
257  /// variable array of the specified element type.
258  QualType getVariableArrayType(QualType EltTy, Expr *NumElts,
259                                ArrayType::ArraySizeModifier ASM,
260                                unsigned EltTypeQuals);
261
262  /// getDependentSizedArrayType - Returns a non-unique reference to
263  /// the type for a dependently-sized array of the specified element
264  /// type. FIXME: We will need these to be uniqued, or at least
265  /// comparable, at some point.
266  QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
267                                      ArrayType::ArraySizeModifier ASM,
268                                      unsigned EltTypeQuals);
269
270  /// getIncompleteArrayType - Returns a unique reference to the type for a
271  /// incomplete array of the specified element type.
272  QualType getIncompleteArrayType(QualType EltTy,
273                                  ArrayType::ArraySizeModifier ASM,
274                                  unsigned EltTypeQuals);
275
276  /// getConstantArrayType - Return the unique reference to the type for a
277  /// constant array of the specified element type.
278  QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize,
279                                ArrayType::ArraySizeModifier ASM,
280                                unsigned EltTypeQuals);
281
282  /// getVectorType - Return the unique reference to a vector type of
283  /// the specified element type and size. VectorType must be a built-in type.
284  QualType getVectorType(QualType VectorType, unsigned NumElts);
285
286  /// getExtVectorType - Return the unique reference to an extended vector type
287  /// of the specified element type and size.  VectorType must be a built-in
288  /// type.
289  QualType getExtVectorType(QualType VectorType, unsigned NumElts);
290
291  /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
292  ///
293  QualType getFunctionNoProtoType(QualType ResultTy);
294
295  /// getFunctionType - Return a normal function type with a typed argument
296  /// list.  isVariadic indicates whether the argument list includes '...'.
297  QualType getFunctionType(QualType ResultTy, const QualType *ArgArray,
298                           unsigned NumArgs, bool isVariadic,
299                           unsigned TypeQuals, bool hasExceptionSpec = false,
300                           bool hasAnyExceptionSpec = false,
301                           unsigned NumExs = 0, const QualType *ExArray = 0);
302
303  /// getTypeDeclType - Return the unique reference to the type for
304  /// the specified type declaration.
305  QualType getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl=0);
306
307  /// getTypedefType - Return the unique reference to the type for the
308  /// specified typename decl.
309  QualType getTypedefType(TypedefDecl *Decl);
310  QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl);
311
312  QualType getTemplateTypeParmType(unsigned Depth, unsigned Index,
313                                   IdentifierInfo *Name = 0);
314
315  QualType getTemplateSpecializationType(TemplateName T,
316                                         const TemplateArgument *Args,
317                                         unsigned NumArgs,
318                                         QualType Canon = QualType());
319
320  QualType getQualifiedNameType(NestedNameSpecifier *NNS,
321                                QualType NamedType);
322  QualType getTypenameType(NestedNameSpecifier *NNS,
323                           const IdentifierInfo *Name,
324                           QualType Canon = QualType());
325  QualType getTypenameType(NestedNameSpecifier *NNS,
326                           const TemplateSpecializationType *TemplateId,
327                           QualType Canon = QualType());
328
329  /// getObjCQualifiedInterfaceType - Return a
330  /// ObjCQualifiedInterfaceType type for the given interface decl and
331  /// the conforming protocol list.
332  QualType getObjCQualifiedInterfaceType(ObjCInterfaceDecl *Decl,
333                                         ObjCProtocolDecl **ProtocolList,
334                                         unsigned NumProtocols);
335
336  /// getObjCQualifiedIdType - Return an ObjCQualifiedIdType for a
337  /// given 'id' and conforming protocol list.
338  QualType getObjCQualifiedIdType(ObjCProtocolDecl **ProtocolList,
339                                  unsigned NumProtocols);
340
341
342  /// getTypeOfType - GCC extension.
343  QualType getTypeOfExprType(Expr *e);
344  QualType getTypeOfType(QualType t);
345
346  /// getTagDeclType - Return the unique reference to the type for the
347  /// specified TagDecl (struct/union/class/enum) decl.
348  QualType getTagDeclType(TagDecl *Decl);
349
350  /// getSizeType - Return the unique type for "size_t" (C99 7.17), defined
351  /// in <stddef.h>. The sizeof operator requires this (C99 6.5.3.4p4).
352  QualType getSizeType() const;
353
354  /// getWCharType - In C++, this returns the unique wchar_t type.  In C99, this
355  /// returns a type compatible with the type defined in <stddef.h> as defined
356  /// by the target.
357  QualType getWCharType() const { return WCharTy; }
358
359  /// getSignedWCharType - Return the type of "signed wchar_t".
360  /// Used when in C++, as a GCC extension.
361  QualType getSignedWCharType() const;
362
363  /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
364  /// Used when in C++, as a GCC extension.
365  QualType getUnsignedWCharType() const;
366
367  /// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
368  /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
369  QualType getPointerDiffType() const;
370
371  // getCFConstantStringType - Return the C structure type used to represent
372  // constant CFStrings.
373  QualType getCFConstantStringType();
374
375  /// Get the structure type used to representation CFStrings, or NULL
376  /// if it hasn't yet been built.
377  QualType getRawCFConstantStringType() {
378    if (CFConstantStringTypeDecl)
379      return getTagDeclType(CFConstantStringTypeDecl);
380    return QualType();
381  }
382  void setCFConstantStringType(QualType T);
383
384  // This setter/getter represents the ObjC type for an NSConstantString.
385  void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl);
386  QualType getObjCConstantStringInterface() const {
387    return ObjCConstantStringType;
388  }
389
390  //// This gets the struct used to keep track of fast enumerations.
391  QualType getObjCFastEnumerationStateType();
392
393  /// Get the ObjCFastEnumerationState type, or NULL if it hasn't yet
394  /// been built.
395  QualType getRawObjCFastEnumerationStateType() {
396    if (ObjCFastEnumerationStateTypeDecl)
397      return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
398    return QualType();
399  }
400
401  void setObjCFastEnumerationStateType(QualType T);
402
403  /// getObjCEncodingForType - Emit the ObjC type encoding for the
404  /// given type into \arg S. If \arg NameFields is specified then
405  /// record field names are also encoded.
406  void getObjCEncodingForType(QualType t, std::string &S,
407                              const FieldDecl *Field=0);
408
409  void getLegacyIntegralTypeEncoding(QualType &t) const;
410
411  // Put the string version of type qualifiers into S.
412  void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
413                                       std::string &S) const;
414
415  /// getObjCEncodingForMethodDecl - Return the encoded type for this method
416  /// declaration.
417  void getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, std::string &S);
418
419  /// getObjCEncodingForPropertyDecl - Return the encoded type for
420  /// this method declaration. If non-NULL, Container must be either
421  /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
422  /// only be NULL when getting encodings for protocol properties.
423  void getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
424                                      const Decl *Container,
425                                      std::string &S);
426
427  /// getObjCEncodingTypeSize returns size of type for objective-c encoding
428  /// purpose.
429  int getObjCEncodingTypeSize(QualType t);
430
431  /// This setter/getter represents the ObjC 'id' type. It is setup lazily, by
432  /// Sema.  id is always a (typedef for a) pointer type, a pointer to a struct.
433  QualType getObjCIdType() const { return ObjCIdType; }
434  void setObjCIdType(QualType T);
435
436  void setObjCSelType(QualType T);
437  QualType getObjCSelType() const { return ObjCSelType; }
438
439  void setObjCProtoType(QualType QT);
440  QualType getObjCProtoType() const { return ObjCProtoType; }
441
442  /// This setter/getter repreents the ObjC 'Class' type. It is setup lazily, by
443  /// Sema.  'Class' is always a (typedef for a) pointer type, a pointer to a
444  /// struct.
445  QualType getObjCClassType() const { return ObjCClassType; }
446  void setObjCClassType(QualType T);
447
448  void setBuiltinVaListType(QualType T);
449  QualType getBuiltinVaListType() const { return BuiltinVaListType; }
450
451  QualType getFixedWidthIntType(unsigned Width, bool Signed);
452
453  TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
454                                        bool TemplateKeyword,
455                                        TemplateDecl *Template);
456
457  TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
458                                        const IdentifierInfo *Name);
459
460private:
461  QualType getFromTargetType(unsigned Type) const;
462
463  //===--------------------------------------------------------------------===//
464  //                         Type Predicates.
465  //===--------------------------------------------------------------------===//
466
467public:
468  /// isObjCObjectPointerType - Returns true if type is an Objective-C pointer
469  /// to an object type.  This includes "id" and "Class" (two 'special' pointers
470  /// to struct), Interface* (pointer to ObjCInterfaceType) and id<P> (qualified
471  /// ID type).
472  bool isObjCObjectPointerType(QualType Ty) const;
473
474  /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
475  /// garbage collection attribute.
476  ///
477  QualType::GCAttrTypes getObjCGCAttrKind(const QualType &Ty) const;
478
479  /// isObjCNSObjectType - Return true if this is an NSObject object with
480  /// its NSObject attribute set.
481  bool isObjCNSObjectType(QualType Ty) const;
482
483  //===--------------------------------------------------------------------===//
484  //                         Type Sizing and Analysis
485  //===--------------------------------------------------------------------===//
486
487  /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
488  /// scalar floating point type.
489  const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
490
491  /// getTypeInfo - Get the size and alignment of the specified complete type in
492  /// bits.
493  std::pair<uint64_t, unsigned> getTypeInfo(const Type *T);
494  std::pair<uint64_t, unsigned> getTypeInfo(QualType T) {
495    return getTypeInfo(T.getTypePtr());
496  }
497
498  /// getTypeSize - Return the size of the specified type, in bits.  This method
499  /// does not work on incomplete types.
500  uint64_t getTypeSize(QualType T) {
501    return getTypeInfo(T).first;
502  }
503  uint64_t getTypeSize(const Type *T) {
504    return getTypeInfo(T).first;
505  }
506
507  /// getTypeAlign - Return the ABI-specified alignment of a type, in bits.
508  /// This method does not work on incomplete types.
509  unsigned getTypeAlign(QualType T) {
510    return getTypeInfo(T).second;
511  }
512  unsigned getTypeAlign(const Type *T) {
513    return getTypeInfo(T).second;
514  }
515
516  /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
517  /// type for the current target in bits.  This can be different than the ABI
518  /// alignment in cases where it is beneficial for performance to overalign
519  /// a data type.
520  unsigned getPreferredTypeAlign(const Type *T);
521
522  /// getDeclAlignInBytes - Return the alignment of the specified decl
523  /// that should be returned by __alignof().  Note that bitfields do
524  /// not have a valid alignment, so this method will assert on them.
525  unsigned getDeclAlignInBytes(const Decl *D);
526
527  /// getASTRecordLayout - Get or compute information about the layout of the
528  /// specified record (struct/union/class), which indicates its size and field
529  /// position information.
530  const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D);
531
532  /// getASTObjCInterfaceLayout - Get or compute information about the
533  /// layout of the specified Objective-C interface.
534  const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D);
535
536  /// getASTObjCImplementationLayout - Get or compute information about
537  /// the layout of the specified Objective-C implementation. This may
538  /// differ from the interface if synthesized ivars are present.
539  const ASTRecordLayout &
540  getASTObjCImplementationLayout(const ObjCImplementationDecl *D);
541
542  const RecordDecl *addRecordToClass(const ObjCInterfaceDecl *D);
543  void CollectObjCIvars(const ObjCInterfaceDecl *OI,
544                        llvm::SmallVectorImpl<FieldDecl*> &Fields);
545
546  //===--------------------------------------------------------------------===//
547  //                            Type Operators
548  //===--------------------------------------------------------------------===//
549
550  /// getCanonicalType - Return the canonical (structural) type corresponding to
551  /// the specified potentially non-canonical type.  The non-canonical version
552  /// of a type may have many "decorated" versions of types.  Decorators can
553  /// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
554  /// to be free of any of these, allowing two canonical types to be compared
555  /// for exact equality with a simple pointer comparison.
556  QualType getCanonicalType(QualType T);
557  const Type *getCanonicalType(const Type *T) {
558    return T->getCanonicalTypeInternal().getTypePtr();
559  }
560
561  /// \brief Determine whether the given types are equivalent.
562  bool hasSameType(QualType T1, QualType T2) {
563    return getCanonicalType(T1) == getCanonicalType(T2);
564  }
565
566  /// \brief Determine whether the given types are equivalent after
567  /// cvr-qualifiers have been removed.
568  bool hasSameUnqualifiedType(QualType T1, QualType T2) {
569    T1 = getCanonicalType(T1);
570    T2 = getCanonicalType(T2);
571    return T1.getUnqualifiedType() == T2.getUnqualifiedType();
572  }
573
574  /// \brief Retrieves the "canonical" declaration of the given tag
575  /// declaration.
576  ///
577  /// The canonical declaration for the given tag declaration is
578  /// either the definition of the tag (if it is a complete type) or
579  /// the first declaration of that tag.
580  TagDecl *getCanonicalDecl(TagDecl *Tag) {
581    QualType T = getTagDeclType(Tag);
582    return cast<TagDecl>(cast<TagType>(T.getTypePtr()->CanonicalType)
583                           ->getDecl());
584  }
585
586  /// \brief Retrieves the "canonical" nested name specifier for a
587  /// given nested name specifier.
588  ///
589  /// The canonical nested name specifier is a nested name specifier
590  /// that uniquely identifies a type or namespace within the type
591  /// system. For example, given:
592  ///
593  /// \code
594  /// namespace N {
595  ///   struct S {
596  ///     template<typename T> struct X { typename T* type; };
597  ///   };
598  /// }
599  ///
600  /// template<typename T> struct Y {
601  ///   typename N::S::X<T>::type member;
602  /// };
603  /// \endcode
604  ///
605  /// Here, the nested-name-specifier for N::S::X<T>:: will be
606  /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined
607  /// by declarations in the type system and the canonical type for
608  /// the template type parameter 'T' is template-param-0-0.
609  NestedNameSpecifier *
610  getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS);
611
612  /// Type Query functions.  If the type is an instance of the specified class,
613  /// return the Type pointer for the underlying maximally pretty type.  This
614  /// is a member of ASTContext because this may need to do some amount of
615  /// canonicalization, e.g. to move type qualifiers into the element type.
616  const ArrayType *getAsArrayType(QualType T);
617  const ConstantArrayType *getAsConstantArrayType(QualType T) {
618    return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T));
619  }
620  const VariableArrayType *getAsVariableArrayType(QualType T) {
621    return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T));
622  }
623  const IncompleteArrayType *getAsIncompleteArrayType(QualType T) {
624    return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
625  }
626
627  /// getBaseElementType - Returns the innermost element type of a variable
628  /// length array type. For example, will return "int" for int[m][n]
629  QualType getBaseElementType(const VariableArrayType *VAT);
630
631  /// getArrayDecayedType - Return the properly qualified result of decaying the
632  /// specified array type to a pointer.  This operation is non-trivial when
633  /// handling typedefs etc.  The canonical type of "T" must be an array type,
634  /// this returns a pointer to a properly qualified element of the array.
635  ///
636  /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
637  QualType getArrayDecayedType(QualType T);
638
639  /// getIntegerTypeOrder - Returns the highest ranked integer type:
640  /// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
641  /// LHS < RHS, return -1.
642  int getIntegerTypeOrder(QualType LHS, QualType RHS);
643
644  /// getFloatingTypeOrder - Compare the rank of the two specified floating
645  /// point types, ignoring the domain of the type (i.e. 'double' ==
646  /// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
647  /// LHS < RHS, return -1.
648  int getFloatingTypeOrder(QualType LHS, QualType RHS);
649
650  /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
651  /// point or a complex type (based on typeDomain/typeSize).
652  /// 'typeDomain' is a real floating point or complex type.
653  /// 'typeSize' is a real floating point or complex type.
654  QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
655                                             QualType typeDomain) const;
656
657private:
658  // Helper for integer ordering
659  unsigned getIntegerRank(Type* T);
660
661public:
662
663  //===--------------------------------------------------------------------===//
664  //                    Type Compatibility Predicates
665  //===--------------------------------------------------------------------===//
666
667  /// Compatibility predicates used to check assignment expressions.
668  bool typesAreCompatible(QualType, QualType); // C99 6.2.7p1
669  bool typesAreBlockCompatible(QualType lhs, QualType rhs);
670
671  bool isObjCIdType(QualType T) const {
672    return T == ObjCIdType;
673  }
674  bool isObjCIdStructType(QualType T) const {
675    if (!IdStructType) // ObjC isn't enabled
676      return false;
677    return T->getAsStructureType() == IdStructType;
678  }
679  bool isObjCClassType(QualType T) const {
680    return T == ObjCClassType;
681  }
682  bool isObjCClassStructType(QualType T) const {
683    if (!ClassStructType) // ObjC isn't enabled
684      return false;
685    return T->getAsStructureType() == ClassStructType;
686  }
687  bool isObjCSelType(QualType T) const {
688    assert(SelStructType && "isObjCSelType used before 'SEL' type is built");
689    return T->getAsStructureType() == SelStructType;
690  }
691
692  // Check the safety of assignment from LHS to RHS
693  bool canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
694                               const ObjCInterfaceType *RHS);
695  bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
696
697  // Functions for calculating composite types
698  QualType mergeTypes(QualType, QualType);
699  QualType mergeFunctionTypes(QualType, QualType);
700
701  //===--------------------------------------------------------------------===//
702  //                    Integer Predicates
703  //===--------------------------------------------------------------------===//
704
705  // The width of an integer, as defined in C99 6.2.6.2. This is the number
706  // of bits in an integer type excluding any padding bits.
707  unsigned getIntWidth(QualType T);
708
709  // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
710  // unsigned integer type.  This method takes a signed type, and returns the
711  // corresponding unsigned integer type.
712  QualType getCorrespondingUnsignedType(QualType T);
713
714  //===--------------------------------------------------------------------===//
715  //                    Type Iterators.
716  //===--------------------------------------------------------------------===//
717
718  typedef std::vector<Type*>::iterator       type_iterator;
719  typedef std::vector<Type*>::const_iterator const_type_iterator;
720
721  type_iterator types_begin() { return Types.begin(); }
722  type_iterator types_end() { return Types.end(); }
723  const_type_iterator types_begin() const { return Types.begin(); }
724  const_type_iterator types_end() const { return Types.end(); }
725
726  //===--------------------------------------------------------------------===//
727  //                    Integer Values
728  //===--------------------------------------------------------------------===//
729
730  /// MakeIntValue - Make an APSInt of the appropriate width and
731  /// signedness for the given \arg Value and integer \arg Type.
732  llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) {
733    llvm::APSInt Res(getIntWidth(Type), !Type->isSignedIntegerType());
734    Res = Value;
735    return Res;
736  }
737
738private:
739  ASTContext(const ASTContext&); // DO NOT IMPLEMENT
740  void operator=(const ASTContext&); // DO NOT IMPLEMENT
741
742  void InitBuiltinTypes();
743  void InitBuiltinType(QualType &R, BuiltinType::Kind K);
744
745  // Return the ObjC type encoding for a given type.
746  void getObjCEncodingForTypeImpl(QualType t, std::string &S,
747                                  bool ExpandPointedToStructures,
748                                  bool ExpandStructures,
749                                  const FieldDecl *Field,
750                                  bool OutermostType = false,
751                                  bool EncodingProperty = false);
752
753  const ASTRecordLayout &getObjCLayout(const ObjCInterfaceDecl *D,
754                                       const ObjCImplementationDecl *Impl);
755};
756
757}  // end namespace clang
758
759// operator new and delete aren't allowed inside namespaces.
760// The throw specifications are mandated by the standard.
761/// @brief Placement new for using the ASTContext's allocator.
762///
763/// This placement form of operator new uses the ASTContext's allocator for
764/// obtaining memory. It is a non-throwing new, which means that it returns
765/// null on error. (If that is what the allocator does. The current does, so if
766/// this ever changes, this operator will have to be changed, too.)
767/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
768/// @code
769/// // Default alignment (16)
770/// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
771/// // Specific alignment
772/// IntegerLiteral *Ex2 = new (Context, 8) IntegerLiteral(arguments);
773/// @endcode
774/// Please note that you cannot use delete on the pointer; it must be
775/// deallocated using an explicit destructor call followed by
776/// @c Context.Deallocate(Ptr).
777///
778/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
779/// @param C The ASTContext that provides the allocator.
780/// @param Alignment The alignment of the allocated memory (if the underlying
781///                  allocator supports it).
782/// @return The allocated memory. Could be NULL.
783inline void *operator new(size_t Bytes, clang::ASTContext &C,
784                          size_t Alignment) throw () {
785  return C.Allocate(Bytes, Alignment);
786}
787/// @brief Placement delete companion to the new above.
788///
789/// This operator is just a companion to the new above. There is no way of
790/// invoking it directly; see the new operator for more details. This operator
791/// is called implicitly by the compiler if a placement new expression using
792/// the ASTContext throws in the object constructor.
793inline void operator delete(void *Ptr, clang::ASTContext &C, size_t)
794              throw () {
795  C.Deallocate(Ptr);
796}
797
798/// This placement form of operator new[] uses the ASTContext's allocator for
799/// obtaining memory. It is a non-throwing new[], which means that it returns
800/// null on error.
801/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
802/// @code
803/// // Default alignment (16)
804/// char *data = new (Context) char[10];
805/// // Specific alignment
806/// char *data = new (Context, 8) char[10];
807/// @endcode
808/// Please note that you cannot use delete on the pointer; it must be
809/// deallocated using an explicit destructor call followed by
810/// @c Context.Deallocate(Ptr).
811///
812/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
813/// @param C The ASTContext that provides the allocator.
814/// @param Alignment The alignment of the allocated memory (if the underlying
815///                  allocator supports it).
816/// @return The allocated memory. Could be NULL.
817inline void *operator new[](size_t Bytes, clang::ASTContext& C,
818                            size_t Alignment = 16) throw () {
819  return C.Allocate(Bytes, Alignment);
820}
821
822/// @brief Placement delete[] companion to the new[] above.
823///
824/// This operator is just a companion to the new[] above. There is no way of
825/// invoking it directly; see the new[] operator for more details. This operator
826/// is called implicitly by the compiler if a placement new[] expression using
827/// the ASTContext throws in the object constructor.
828inline void operator delete[](void *Ptr, clang::ASTContext &C) throw () {
829  C.Deallocate(Ptr);
830}
831
832#endif
833