ASTContext.h revision a6c66cedc022c9e5d45a937d6b8cff491a6bf81b
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/AddressSpaces.h"
18#include "clang/Basic/IdentifierTable.h"
19#include "clang/Basic/LangOptions.h"
20#include "clang/Basic/OperatorKinds.h"
21#include "clang/Basic/PartialDiagnostic.h"
22#include "clang/Basic/VersionTuple.h"
23#include "clang/AST/Decl.h"
24#include "clang/AST/LambdaMangleContext.h"
25#include "clang/AST/NestedNameSpecifier.h"
26#include "clang/AST/PrettyPrinter.h"
27#include "clang/AST/TemplateName.h"
28#include "clang/AST/Type.h"
29#include "clang/AST/CanonicalType.h"
30#include "clang/AST/RawCommentList.h"
31#include "llvm/ADT/DenseMap.h"
32#include "llvm/ADT/FoldingSet.h"
33#include "llvm/ADT/IntrusiveRefCntPtr.h"
34#include "llvm/ADT/OwningPtr.h"
35#include "llvm/ADT/SmallPtrSet.h"
36#include "llvm/ADT/TinyPtrVector.h"
37#include "llvm/Support/Allocator.h"
38#include <vector>
39
40namespace llvm {
41  struct fltSemantics;
42}
43
44namespace clang {
45  class FileManager;
46  class ASTRecordLayout;
47  class BlockExpr;
48  class CharUnits;
49  class DiagnosticsEngine;
50  class Expr;
51  class ExternalASTSource;
52  class ASTMutationListener;
53  class IdentifierTable;
54  class SelectorTable;
55  class TargetInfo;
56  class CXXABI;
57  // Decls
58  class DeclContext;
59  class CXXConversionDecl;
60  class CXXMethodDecl;
61  class CXXRecordDecl;
62  class Decl;
63  class FieldDecl;
64  class MangleContext;
65  class ObjCIvarDecl;
66  class ObjCIvarRefExpr;
67  class ObjCPropertyDecl;
68  class ParmVarDecl;
69  class RecordDecl;
70  class StoredDeclsMap;
71  class TagDecl;
72  class TemplateTemplateParmDecl;
73  class TemplateTypeParmDecl;
74  class TranslationUnitDecl;
75  class TypeDecl;
76  class TypedefNameDecl;
77  class UsingDecl;
78  class UsingShadowDecl;
79  class UnresolvedSetIterator;
80
81  namespace Builtin { class Context; }
82
83  namespace comments {
84    class FullComment;
85  }
86
87/// ASTContext - This class holds long-lived AST nodes (such as types and
88/// decls) that can be referred to throughout the semantic analysis of a file.
89class ASTContext : public RefCountedBase<ASTContext> {
90  ASTContext &this_() { return *this; }
91
92  mutable std::vector<Type*> Types;
93  mutable llvm::FoldingSet<ExtQuals> ExtQualNodes;
94  mutable llvm::FoldingSet<ComplexType> ComplexTypes;
95  mutable llvm::FoldingSet<PointerType> PointerTypes;
96  mutable llvm::FoldingSet<BlockPointerType> BlockPointerTypes;
97  mutable llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes;
98  mutable llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes;
99  mutable llvm::FoldingSet<MemberPointerType> MemberPointerTypes;
100  mutable llvm::FoldingSet<ConstantArrayType> ConstantArrayTypes;
101  mutable llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
102  mutable std::vector<VariableArrayType*> VariableArrayTypes;
103  mutable llvm::FoldingSet<DependentSizedArrayType> DependentSizedArrayTypes;
104  mutable llvm::FoldingSet<DependentSizedExtVectorType>
105    DependentSizedExtVectorTypes;
106  mutable llvm::FoldingSet<VectorType> VectorTypes;
107  mutable llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes;
108  mutable llvm::ContextualFoldingSet<FunctionProtoType, ASTContext&>
109    FunctionProtoTypes;
110  mutable llvm::FoldingSet<DependentTypeOfExprType> DependentTypeOfExprTypes;
111  mutable llvm::FoldingSet<DependentDecltypeType> DependentDecltypeTypes;
112  mutable llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes;
113  mutable llvm::FoldingSet<SubstTemplateTypeParmType>
114    SubstTemplateTypeParmTypes;
115  mutable llvm::FoldingSet<SubstTemplateTypeParmPackType>
116    SubstTemplateTypeParmPackTypes;
117  mutable llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&>
118    TemplateSpecializationTypes;
119  mutable llvm::FoldingSet<ParenType> ParenTypes;
120  mutable llvm::FoldingSet<ElaboratedType> ElaboratedTypes;
121  mutable llvm::FoldingSet<DependentNameType> DependentNameTypes;
122  mutable llvm::ContextualFoldingSet<DependentTemplateSpecializationType,
123                                     ASTContext&>
124    DependentTemplateSpecializationTypes;
125  llvm::FoldingSet<PackExpansionType> PackExpansionTypes;
126  mutable llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes;
127  mutable llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes;
128  mutable llvm::FoldingSet<AutoType> AutoTypes;
129  mutable llvm::FoldingSet<AtomicType> AtomicTypes;
130  llvm::FoldingSet<AttributedType> AttributedTypes;
131
132  mutable llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames;
133  mutable llvm::FoldingSet<DependentTemplateName> DependentTemplateNames;
134  mutable llvm::FoldingSet<SubstTemplateTemplateParmStorage>
135    SubstTemplateTemplateParms;
136  mutable llvm::ContextualFoldingSet<SubstTemplateTemplateParmPackStorage,
137                                     ASTContext&>
138    SubstTemplateTemplateParmPacks;
139
140  /// \brief The set of nested name specifiers.
141  ///
142  /// This set is managed by the NestedNameSpecifier class.
143  mutable llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers;
144  mutable NestedNameSpecifier *GlobalNestedNameSpecifier;
145  friend class NestedNameSpecifier;
146
147  /// ASTRecordLayouts - A cache mapping from RecordDecls to ASTRecordLayouts.
148  ///  This is lazily created.  This is intentionally not serialized.
149  mutable llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>
150    ASTRecordLayouts;
151  mutable llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>
152    ObjCLayouts;
153
154  /// TypeInfoMap - A cache from types to size and alignment information.
155  typedef llvm::DenseMap<const Type*,
156                         std::pair<uint64_t, unsigned> > TypeInfoMap;
157  mutable TypeInfoMap MemoizedTypeInfo;
158
159  /// KeyFunctions - A cache mapping from CXXRecordDecls to key functions.
160  llvm::DenseMap<const CXXRecordDecl*, const CXXMethodDecl*> KeyFunctions;
161
162  /// \brief Mapping from ObjCContainers to their ObjCImplementations.
163  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls;
164
165  /// \brief Mapping from ObjCMethod to its duplicate declaration in the same
166  /// interface.
167  llvm::DenseMap<const ObjCMethodDecl*,const ObjCMethodDecl*> ObjCMethodRedecls;
168
169  /// \brief Mapping from __block VarDecls to their copy initialization expr.
170  llvm::DenseMap<const VarDecl*, Expr*> BlockVarCopyInits;
171
172  /// \brief Mapping from class scope functions specialization to their
173  ///  template patterns.
174  llvm::DenseMap<const FunctionDecl*, FunctionDecl*>
175    ClassScopeSpecializationPattern;
176
177  /// \brief Representation of a "canonical" template template parameter that
178  /// is used in canonical template names.
179  class CanonicalTemplateTemplateParm : public llvm::FoldingSetNode {
180    TemplateTemplateParmDecl *Parm;
181
182  public:
183    CanonicalTemplateTemplateParm(TemplateTemplateParmDecl *Parm)
184      : Parm(Parm) { }
185
186    TemplateTemplateParmDecl *getParam() const { return Parm; }
187
188    void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, Parm); }
189
190    static void Profile(llvm::FoldingSetNodeID &ID,
191                        TemplateTemplateParmDecl *Parm);
192  };
193  mutable llvm::FoldingSet<CanonicalTemplateTemplateParm>
194    CanonTemplateTemplateParms;
195
196  TemplateTemplateParmDecl *
197    getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const;
198
199  /// \brief The typedef for the __int128_t type.
200  mutable TypedefDecl *Int128Decl;
201
202  /// \brief The typedef for the __uint128_t type.
203  mutable TypedefDecl *UInt128Decl;
204
205  /// \brief The typedef for the target specific predefined
206  /// __builtin_va_list type.
207  mutable TypedefDecl *BuiltinVaListDecl;
208
209  /// \brief The typedef for the predefined 'id' type.
210  mutable TypedefDecl *ObjCIdDecl;
211
212  /// \brief The typedef for the predefined 'SEL' type.
213  mutable TypedefDecl *ObjCSelDecl;
214
215  /// \brief The typedef for the predefined 'Class' type.
216  mutable TypedefDecl *ObjCClassDecl;
217
218  /// \brief The typedef for the predefined 'Protocol' class in Objective-C.
219  mutable ObjCInterfaceDecl *ObjCProtocolClassDecl;
220
221  /// \brief The typedef for the predefined 'BOOL' type.
222  mutable TypedefDecl *BOOLDecl;
223
224  // Typedefs which may be provided defining the structure of Objective-C
225  // pseudo-builtins
226  QualType ObjCIdRedefinitionType;
227  QualType ObjCClassRedefinitionType;
228  QualType ObjCSelRedefinitionType;
229
230  QualType ObjCConstantStringType;
231  mutable RecordDecl *CFConstantStringTypeDecl;
232
233  QualType ObjCNSStringType;
234
235  /// \brief The typedef declaration for the Objective-C "instancetype" type.
236  TypedefDecl *ObjCInstanceTypeDecl;
237
238  /// \brief The type for the C FILE type.
239  TypeDecl *FILEDecl;
240
241  /// \brief The type for the C jmp_buf type.
242  TypeDecl *jmp_bufDecl;
243
244  /// \brief The type for the C sigjmp_buf type.
245  TypeDecl *sigjmp_bufDecl;
246
247  /// \brief The type for the C ucontext_t type.
248  TypeDecl *ucontext_tDecl;
249
250  /// \brief Type for the Block descriptor for Blocks CodeGen.
251  ///
252  /// Since this is only used for generation of debug info, it is not
253  /// serialized.
254  mutable RecordDecl *BlockDescriptorType;
255
256  /// \brief Type for the Block descriptor for Blocks CodeGen.
257  ///
258  /// Since this is only used for generation of debug info, it is not
259  /// serialized.
260  mutable RecordDecl *BlockDescriptorExtendedType;
261
262  /// \brief Declaration for the CUDA cudaConfigureCall function.
263  FunctionDecl *cudaConfigureCallDecl;
264
265  TypeSourceInfo NullTypeSourceInfo;
266
267  /// \brief Keeps track of all declaration attributes.
268  ///
269  /// Since so few decls have attrs, we keep them in a hash map instead of
270  /// wasting space in the Decl class.
271  llvm::DenseMap<const Decl*, AttrVec*> DeclAttrs;
272
273  /// \brief Keeps track of the static data member templates from which
274  /// static data members of class template specializations were instantiated.
275  ///
276  /// This data structure stores the mapping from instantiations of static
277  /// data members to the static data member representations within the
278  /// class template from which they were instantiated along with the kind
279  /// of instantiation or specialization (a TemplateSpecializationKind - 1).
280  ///
281  /// Given the following example:
282  ///
283  /// \code
284  /// template<typename T>
285  /// struct X {
286  ///   static T value;
287  /// };
288  ///
289  /// template<typename T>
290  ///   T X<T>::value = T(17);
291  ///
292  /// int *x = &X<int>::value;
293  /// \endcode
294  ///
295  /// This mapping will contain an entry that maps from the VarDecl for
296  /// X<int>::value to the corresponding VarDecl for X<T>::value (within the
297  /// class template X) and will be marked TSK_ImplicitInstantiation.
298  llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>
299    InstantiatedFromStaticDataMember;
300
301  /// \brief Keeps track of the declaration from which a UsingDecl was
302  /// created during instantiation.  The source declaration is always
303  /// a UsingDecl, an UnresolvedUsingValueDecl, or an
304  /// UnresolvedUsingTypenameDecl.
305  ///
306  /// For example:
307  /// \code
308  /// template<typename T>
309  /// struct A {
310  ///   void f();
311  /// };
312  ///
313  /// template<typename T>
314  /// struct B : A<T> {
315  ///   using A<T>::f;
316  /// };
317  ///
318  /// template struct B<int>;
319  /// \endcode
320  ///
321  /// This mapping will contain an entry that maps from the UsingDecl in
322  /// B<int> to the UnresolvedUsingDecl in B<T>.
323  llvm::DenseMap<UsingDecl *, NamedDecl *> InstantiatedFromUsingDecl;
324
325  llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>
326    InstantiatedFromUsingShadowDecl;
327
328  llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl;
329
330  /// \brief Mapping that stores the methods overridden by a given C++
331  /// member function.
332  ///
333  /// Since most C++ member functions aren't virtual and therefore
334  /// don't override anything, we store the overridden functions in
335  /// this map on the side rather than within the CXXMethodDecl structure.
336  typedef llvm::TinyPtrVector<const CXXMethodDecl*> CXXMethodVector;
337  llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector> OverriddenMethods;
338
339  /// \brief Mapping from each declaration context to its corresponding lambda
340  /// mangling context.
341  llvm::DenseMap<const DeclContext *, LambdaMangleContext> LambdaMangleContexts;
342
343  /// \brief Mapping that stores parameterIndex values for ParmVarDecls
344  /// when that value exceeds the bitfield size of
345  /// ParmVarDeclBits.ParameterIndex.
346  typedef llvm::DenseMap<const VarDecl *, unsigned> ParameterIndexTable;
347  ParameterIndexTable ParamIndices;
348
349  ImportDecl *FirstLocalImport;
350  ImportDecl *LastLocalImport;
351
352  TranslationUnitDecl *TUDecl;
353
354  /// SourceMgr - The associated SourceManager object.
355  SourceManager &SourceMgr;
356
357  /// LangOpts - The language options used to create the AST associated with
358  ///  this ASTContext object.
359  LangOptions &LangOpts;
360
361  /// \brief The allocator used to create AST objects.
362  ///
363  /// AST objects are never destructed; rather, all memory associated with the
364  /// AST objects will be released when the ASTContext itself is destroyed.
365  mutable llvm::BumpPtrAllocator BumpAlloc;
366
367  /// \brief Allocator for partial diagnostics.
368  PartialDiagnostic::StorageAllocator DiagAllocator;
369
370  /// \brief The current C++ ABI.
371  OwningPtr<CXXABI> ABI;
372  CXXABI *createCXXABI(const TargetInfo &T);
373
374  /// \brief The logical -> physical address space map.
375  const LangAS::Map *AddrSpaceMap;
376
377  friend class ASTDeclReader;
378  friend class ASTReader;
379  friend class ASTWriter;
380  friend class CXXRecordDecl;
381
382  const TargetInfo *Target;
383  clang::PrintingPolicy PrintingPolicy;
384
385public:
386  IdentifierTable &Idents;
387  SelectorTable &Selectors;
388  Builtin::Context &BuiltinInfo;
389  mutable DeclarationNameTable DeclarationNames;
390  OwningPtr<ExternalASTSource> ExternalSource;
391  ASTMutationListener *Listener;
392
393  clang::PrintingPolicy getPrintingPolicy() const { return PrintingPolicy; }
394
395  void setPrintingPolicy(clang::PrintingPolicy Policy) {
396    PrintingPolicy = Policy;
397  }
398
399  SourceManager& getSourceManager() { return SourceMgr; }
400  const SourceManager& getSourceManager() const { return SourceMgr; }
401
402  llvm::BumpPtrAllocator &getAllocator() const {
403    return BumpAlloc;
404  }
405
406  void *Allocate(unsigned Size, unsigned Align = 8) const {
407    return BumpAlloc.Allocate(Size, Align);
408  }
409  void Deallocate(void *Ptr) const { }
410
411  /// Return the total amount of physical memory allocated for representing
412  /// AST nodes and type information.
413  size_t getASTAllocatedMemory() const {
414    return BumpAlloc.getTotalMemory();
415  }
416  /// Return the total memory used for various side tables.
417  size_t getSideTableAllocatedMemory() const;
418
419  PartialDiagnostic::StorageAllocator &getDiagAllocator() {
420    return DiagAllocator;
421  }
422
423  const TargetInfo &getTargetInfo() const { return *Target; }
424
425  const LangOptions& getLangOpts() const { return LangOpts; }
426
427  DiagnosticsEngine &getDiagnostics() const;
428
429  FullSourceLoc getFullLoc(SourceLocation Loc) const {
430    return FullSourceLoc(Loc,SourceMgr);
431  }
432
433  /// \brief All comments in this translation unit.
434  RawCommentList Comments;
435
436  /// \brief True if comments are already loaded from ExternalASTSource.
437  mutable bool CommentsLoaded;
438
439  class RawCommentAndCacheFlags {
440  public:
441    enum Kind {
442      /// We searched for a comment attached to the particular declaration, but
443      /// didn't find any.
444      ///
445      /// getRaw() == 0.
446      NoCommentInDecl = 0,
447
448      /// We have found a comment attached to this particular declaration.
449      ///
450      /// getRaw() != 0.
451      FromDecl,
452
453      /// This declaration does not have an attached comment, and we have
454      /// searched the redeclaration chain.
455      ///
456      /// If getRaw() == 0, the whole redeclaration chain does not have any
457      /// comments.
458      ///
459      /// If getRaw() != 0, it is a comment propagated from other
460      /// redeclaration.
461      FromRedecl
462    };
463
464    Kind getKind() const LLVM_READONLY {
465      return Data.getInt();
466    }
467
468    void setKind(Kind K) {
469      Data.setInt(K);
470    }
471
472    const RawComment *getRaw() const LLVM_READONLY {
473      return Data.getPointer();
474    }
475
476    void setRaw(const RawComment *RC) {
477      Data.setPointer(RC);
478    }
479
480    const Decl *getOriginalDecl() const LLVM_READONLY {
481      return OriginalDecl;
482    }
483
484    void setOriginalDecl(const Decl *Orig) {
485      OriginalDecl = Orig;
486    }
487
488  private:
489    llvm::PointerIntPair<const RawComment *, 2, Kind> Data;
490    const Decl *OriginalDecl;
491  };
492
493  /// \brief Mapping from declarations to comments attached to any
494  /// redeclaration.
495  ///
496  /// Raw comments are owned by Comments list.  This mapping is populated
497  /// lazily.
498  mutable llvm::DenseMap<const Decl *, RawCommentAndCacheFlags> RedeclComments;
499
500  /// \brief Mapping from declarations to parsed comments attached to any
501  /// redeclaration.
502  mutable llvm::DenseMap<const Decl *, comments::FullComment *> ParsedComments;
503
504  /// \brief Return the documentation comment attached to a given declaration,
505  /// without looking into cache.
506  RawComment *getRawCommentForDeclNoCache(const Decl *D) const;
507
508public:
509  RawCommentList &getRawCommentList() {
510    return Comments;
511  }
512
513  void addComment(const RawComment &RC) {
514    Comments.addComment(RC, BumpAlloc);
515  }
516
517  /// \brief Return the documentation comment attached to a given declaration.
518  /// Returns NULL if no comment is attached.
519  ///
520  /// \param OriginalDecl if not NULL, is set to declaration AST node that had
521  /// the comment, if the comment we found comes from a redeclaration.
522  const RawComment *getRawCommentForAnyRedecl(
523                                      const Decl *D,
524                                      const Decl **OriginalDecl = NULL) const;
525
526  /// Return parsed documentation comment attached to a given declaration.
527  /// Returns NULL if no comment is attached.
528  comments::FullComment *getCommentForDecl(const Decl *D) const;
529
530  /// \brief Retrieve the attributes for the given declaration.
531  AttrVec& getDeclAttrs(const Decl *D);
532
533  /// \brief Erase the attributes corresponding to the given declaration.
534  void eraseDeclAttrs(const Decl *D);
535
536  /// \brief If this variable is an instantiated static data member of a
537  /// class template specialization, returns the templated static data member
538  /// from which it was instantiated.
539  MemberSpecializationInfo *getInstantiatedFromStaticDataMember(
540                                                           const VarDecl *Var);
541
542  FunctionDecl *getClassScopeSpecializationPattern(const FunctionDecl *FD);
543
544  void setClassScopeSpecializationPattern(FunctionDecl *FD,
545                                          FunctionDecl *Pattern);
546
547  /// \brief Note that the static data member \p Inst is an instantiation of
548  /// the static data member template \p Tmpl of a class template.
549  void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
550                                           TemplateSpecializationKind TSK,
551                        SourceLocation PointOfInstantiation = SourceLocation());
552
553  /// \brief If the given using decl is an instantiation of a
554  /// (possibly unresolved) using decl from a template instantiation,
555  /// return it.
556  NamedDecl *getInstantiatedFromUsingDecl(UsingDecl *Inst);
557
558  /// \brief Remember that the using decl \p Inst is an instantiation
559  /// of the using decl \p Pattern of a class template.
560  void setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern);
561
562  void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
563                                          UsingShadowDecl *Pattern);
564  UsingShadowDecl *getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst);
565
566  FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field);
567
568  void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl);
569
570  /// ZeroBitfieldFollowsNonBitfield - return 'true" if 'FD' is a zero-length
571  /// bitfield which follows the non-bitfield 'LastFD'.
572  bool ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
573                                      const FieldDecl *LastFD) const;
574
575  /// ZeroBitfieldFollowsBitfield - return 'true" if 'FD' is a zero-length
576  /// bitfield which follows the bitfield 'LastFD'.
577  bool ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
578                                   const FieldDecl *LastFD) const;
579
580  /// BitfieldFollowsBitfield - return 'true" if 'FD' is a
581  /// bitfield which follows the bitfield 'LastFD'.
582  bool BitfieldFollowsBitfield(const FieldDecl *FD,
583                               const FieldDecl *LastFD) const;
584
585  /// NonBitfieldFollowsBitfield - return 'true" if 'FD' is not a
586  /// bitfield which follows the bitfield 'LastFD'.
587  bool NonBitfieldFollowsBitfield(const FieldDecl *FD,
588                                  const FieldDecl *LastFD) const;
589
590  /// BitfieldFollowsNonBitfield - return 'true" if 'FD' is a
591  /// bitfield which follows the none bitfield 'LastFD'.
592  bool BitfieldFollowsNonBitfield(const FieldDecl *FD,
593                                  const FieldDecl *LastFD) const;
594
595  // Access to the set of methods overridden by the given C++ method.
596  typedef CXXMethodVector::const_iterator overridden_cxx_method_iterator;
597  overridden_cxx_method_iterator
598  overridden_methods_begin(const CXXMethodDecl *Method) const;
599
600  overridden_cxx_method_iterator
601  overridden_methods_end(const CXXMethodDecl *Method) const;
602
603  unsigned overridden_methods_size(const CXXMethodDecl *Method) const;
604
605  /// \brief Note that the given C++ \p Method overrides the given \p
606  /// Overridden method.
607  void addOverriddenMethod(const CXXMethodDecl *Method,
608                           const CXXMethodDecl *Overridden);
609
610  /// \brief Notify the AST context that a new import declaration has been
611  /// parsed or implicitly created within this translation unit.
612  void addedLocalImportDecl(ImportDecl *Import);
613
614  static ImportDecl *getNextLocalImport(ImportDecl *Import) {
615    return Import->NextLocalImport;
616  }
617
618  /// \brief Iterator that visits import declarations.
619  class import_iterator {
620    ImportDecl *Import;
621
622  public:
623    typedef ImportDecl               *value_type;
624    typedef ImportDecl               *reference;
625    typedef ImportDecl               *pointer;
626    typedef int                       difference_type;
627    typedef std::forward_iterator_tag iterator_category;
628
629    import_iterator() : Import() { }
630    explicit import_iterator(ImportDecl *Import) : Import(Import) { }
631
632    reference operator*() const { return Import; }
633    pointer operator->() const { return Import; }
634
635    import_iterator &operator++() {
636      Import = ASTContext::getNextLocalImport(Import);
637      return *this;
638    }
639
640    import_iterator operator++(int) {
641      import_iterator Other(*this);
642      ++(*this);
643      return Other;
644    }
645
646    friend bool operator==(import_iterator X, import_iterator Y) {
647      return X.Import == Y.Import;
648    }
649
650    friend bool operator!=(import_iterator X, import_iterator Y) {
651      return X.Import != Y.Import;
652    }
653  };
654
655  import_iterator local_import_begin() const {
656    return import_iterator(FirstLocalImport);
657  }
658  import_iterator local_import_end() const { return import_iterator(); }
659
660  TranslationUnitDecl *getTranslationUnitDecl() const { return TUDecl; }
661
662
663  // Builtin Types.
664  CanQualType VoidTy;
665  CanQualType BoolTy;
666  CanQualType CharTy;
667  CanQualType WCharTy;  // [C++ 3.9.1p5], integer type in C99.
668  CanQualType WIntTy;   // [C99 7.24.1], integer type unchanged by default promotions.
669  CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99.
670  CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99.
671  CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty;
672  CanQualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy;
673  CanQualType UnsignedLongLongTy, UnsignedInt128Ty;
674  CanQualType FloatTy, DoubleTy, LongDoubleTy;
675  CanQualType HalfTy; // [OpenCL 6.1.1.1], ARM NEON
676  CanQualType FloatComplexTy, DoubleComplexTy, LongDoubleComplexTy;
677  CanQualType VoidPtrTy, NullPtrTy;
678  CanQualType DependentTy, OverloadTy, BoundMemberTy, UnknownAnyTy;
679  CanQualType BuiltinFnTy;
680  CanQualType PseudoObjectTy, ARCUnbridgedCastTy;
681  CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy;
682  CanQualType ObjCBuiltinBoolTy;
683
684  // Types for deductions in C++0x [stmt.ranged]'s desugaring. Built on demand.
685  mutable QualType AutoDeductTy;     // Deduction against 'auto'.
686  mutable QualType AutoRRefDeductTy; // Deduction against 'auto &&'.
687
688  // Type used to help define __builtin_va_list for some targets.
689  // The type is built when constructing 'BuiltinVaListDecl'.
690  mutable QualType VaListTagTy;
691
692  ASTContext(LangOptions& LOpts, SourceManager &SM, const TargetInfo *t,
693             IdentifierTable &idents, SelectorTable &sels,
694             Builtin::Context &builtins,
695             unsigned size_reserve,
696             bool DelayInitialization = false);
697
698  ~ASTContext();
699
700  /// \brief Attach an external AST source to the AST context.
701  ///
702  /// The external AST source provides the ability to load parts of
703  /// the abstract syntax tree as needed from some external storage,
704  /// e.g., a precompiled header.
705  void setExternalSource(OwningPtr<ExternalASTSource> &Source);
706
707  /// \brief Retrieve a pointer to the external AST source associated
708  /// with this AST context, if any.
709  ExternalASTSource *getExternalSource() const { return ExternalSource.get(); }
710
711  /// \brief Attach an AST mutation listener to the AST context.
712  ///
713  /// The AST mutation listener provides the ability to track modifications to
714  /// the abstract syntax tree entities committed after they were initially
715  /// created.
716  void setASTMutationListener(ASTMutationListener *Listener) {
717    this->Listener = Listener;
718  }
719
720  /// \brief Retrieve a pointer to the AST mutation listener associated
721  /// with this AST context, if any.
722  ASTMutationListener *getASTMutationListener() const { return Listener; }
723
724  void PrintStats() const;
725  const std::vector<Type*>& getTypes() const { return Types; }
726
727  /// \brief Retrieve the declaration for the 128-bit signed integer type.
728  TypedefDecl *getInt128Decl() const;
729
730  /// \brief Retrieve the declaration for the 128-bit unsigned integer type.
731  TypedefDecl *getUInt128Decl() const;
732
733  //===--------------------------------------------------------------------===//
734  //                           Type Constructors
735  //===--------------------------------------------------------------------===//
736
737private:
738  /// getExtQualType - Return a type with extended qualifiers.
739  QualType getExtQualType(const Type *Base, Qualifiers Quals) const;
740
741  QualType getTypeDeclTypeSlow(const TypeDecl *Decl) const;
742
743public:
744  /// getAddSpaceQualType - Return the uniqued reference to the type for an
745  /// address space qualified type with the specified type and address space.
746  /// The resulting type has a union of the qualifiers from T and the address
747  /// space. If T already has an address space specifier, it is silently
748  /// replaced.
749  QualType getAddrSpaceQualType(QualType T, unsigned AddressSpace) const;
750
751  /// getObjCGCQualType - Returns the uniqued reference to the type for an
752  /// objc gc qualified type. The retulting type has a union of the qualifiers
753  /// from T and the gc attribute.
754  QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const;
755
756  /// getRestrictType - Returns the uniqued reference to the type for a
757  /// 'restrict' qualified type.  The resulting type has a union of the
758  /// qualifiers from T and 'restrict'.
759  QualType getRestrictType(QualType T) const {
760    return T.withFastQualifiers(Qualifiers::Restrict);
761  }
762
763  /// getVolatileType - Returns the uniqued reference to the type for a
764  /// 'volatile' qualified type.  The resulting type has a union of the
765  /// qualifiers from T and 'volatile'.
766  QualType getVolatileType(QualType T) const {
767    return T.withFastQualifiers(Qualifiers::Volatile);
768  }
769
770  /// getConstType - Returns the uniqued reference to the type for a
771  /// 'const' qualified type.  The resulting type has a union of the
772  /// qualifiers from T and 'const'.
773  ///
774  /// It can be reasonably expected that this will always be
775  /// equivalent to calling T.withConst().
776  QualType getConstType(QualType T) const { return T.withConst(); }
777
778  /// adjustFunctionType - Change the ExtInfo on a function type.
779  const FunctionType *adjustFunctionType(const FunctionType *Fn,
780                                         FunctionType::ExtInfo EInfo);
781
782  /// getComplexType - Return the uniqued reference to the type for a complex
783  /// number with the specified element type.
784  QualType getComplexType(QualType T) const;
785  CanQualType getComplexType(CanQualType T) const {
786    return CanQualType::CreateUnsafe(getComplexType((QualType) T));
787  }
788
789  /// getPointerType - Return the uniqued reference to the type for a pointer to
790  /// the specified type.
791  QualType getPointerType(QualType T) const;
792  CanQualType getPointerType(CanQualType T) const {
793    return CanQualType::CreateUnsafe(getPointerType((QualType) T));
794  }
795
796  /// getAtomicType - Return the uniqued reference to the atomic type for
797  /// the specified type.
798  QualType getAtomicType(QualType T) const;
799
800  /// getBlockPointerType - Return the uniqued reference to the type for a block
801  /// of the specified type.
802  QualType getBlockPointerType(QualType T) const;
803
804  /// This gets the struct used to keep track of the descriptor for pointer to
805  /// blocks.
806  QualType getBlockDescriptorType() const;
807
808  /// This gets the struct used to keep track of the extended descriptor for
809  /// pointer to blocks.
810  QualType getBlockDescriptorExtendedType() const;
811
812  void setcudaConfigureCallDecl(FunctionDecl *FD) {
813    cudaConfigureCallDecl = FD;
814  }
815  FunctionDecl *getcudaConfigureCallDecl() {
816    return cudaConfigureCallDecl;
817  }
818
819  /// This builds the struct used for __block variables.
820  QualType BuildByRefType(StringRef DeclName, QualType Ty) const;
821
822  /// Returns true iff we need copy/dispose helpers for the given type.
823  bool BlockRequiresCopying(QualType Ty) const;
824
825  /// getLValueReferenceType - Return the uniqued reference to the type for an
826  /// lvalue reference to the specified type.
827  QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true)
828    const;
829
830  /// getRValueReferenceType - Return the uniqued reference to the type for an
831  /// rvalue reference to the specified type.
832  QualType getRValueReferenceType(QualType T) const;
833
834  /// getMemberPointerType - Return the uniqued reference to the type for a
835  /// member pointer to the specified type in the specified class. The class
836  /// is a Type because it could be a dependent name.
837  QualType getMemberPointerType(QualType T, const Type *Cls) const;
838
839  /// getVariableArrayType - Returns a non-unique reference to the type for a
840  /// variable array of the specified element type.
841  QualType getVariableArrayType(QualType EltTy, Expr *NumElts,
842                                ArrayType::ArraySizeModifier ASM,
843                                unsigned IndexTypeQuals,
844                                SourceRange Brackets) const;
845
846  /// getDependentSizedArrayType - Returns a non-unique reference to
847  /// the type for a dependently-sized array of the specified element
848  /// type. FIXME: We will need these to be uniqued, or at least
849  /// comparable, at some point.
850  QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
851                                      ArrayType::ArraySizeModifier ASM,
852                                      unsigned IndexTypeQuals,
853                                      SourceRange Brackets) const;
854
855  /// getIncompleteArrayType - Returns a unique reference to the type for a
856  /// incomplete array of the specified element type.
857  QualType getIncompleteArrayType(QualType EltTy,
858                                  ArrayType::ArraySizeModifier ASM,
859                                  unsigned IndexTypeQuals) const;
860
861  /// getConstantArrayType - Return the unique reference to the type for a
862  /// constant array of the specified element type.
863  QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize,
864                                ArrayType::ArraySizeModifier ASM,
865                                unsigned IndexTypeQuals) const;
866
867  /// getVariableArrayDecayedType - Returns a vla type where known sizes
868  /// are replaced with [*].
869  QualType getVariableArrayDecayedType(QualType Ty) const;
870
871  /// getVectorType - Return the unique reference to a vector type of
872  /// the specified element type and size. VectorType must be a built-in type.
873  QualType getVectorType(QualType VectorType, unsigned NumElts,
874                         VectorType::VectorKind VecKind) const;
875
876  /// getExtVectorType - Return the unique reference to an extended vector type
877  /// of the specified element type and size.  VectorType must be a built-in
878  /// type.
879  QualType getExtVectorType(QualType VectorType, unsigned NumElts) const;
880
881  /// getDependentSizedExtVectorType - Returns a non-unique reference to
882  /// the type for a dependently-sized vector of the specified element
883  /// type. FIXME: We will need these to be uniqued, or at least
884  /// comparable, at some point.
885  QualType getDependentSizedExtVectorType(QualType VectorType,
886                                          Expr *SizeExpr,
887                                          SourceLocation AttrLoc) const;
888
889  /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
890  ///
891  QualType getFunctionNoProtoType(QualType ResultTy,
892                                  const FunctionType::ExtInfo &Info) const;
893
894  QualType getFunctionNoProtoType(QualType ResultTy) const {
895    return getFunctionNoProtoType(ResultTy, FunctionType::ExtInfo());
896  }
897
898  /// getFunctionType - Return a normal function type with a typed
899  /// argument list.
900  QualType getFunctionType(QualType ResultTy,
901                           const QualType *Args, unsigned NumArgs,
902                           const FunctionProtoType::ExtProtoInfo &EPI) const;
903
904  /// getTypeDeclType - Return the unique reference to the type for
905  /// the specified type declaration.
906  QualType getTypeDeclType(const TypeDecl *Decl,
907                           const TypeDecl *PrevDecl = 0) const {
908    assert(Decl && "Passed null for Decl param");
909    if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
910
911    if (PrevDecl) {
912      assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
913      Decl->TypeForDecl = PrevDecl->TypeForDecl;
914      return QualType(PrevDecl->TypeForDecl, 0);
915    }
916
917    return getTypeDeclTypeSlow(Decl);
918  }
919
920  /// getTypedefType - Return the unique reference to the type for the
921  /// specified typedef-name decl.
922  QualType getTypedefType(const TypedefNameDecl *Decl,
923                          QualType Canon = QualType()) const;
924
925  QualType getRecordType(const RecordDecl *Decl) const;
926
927  QualType getEnumType(const EnumDecl *Decl) const;
928
929  QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const;
930
931  QualType getAttributedType(AttributedType::Kind attrKind,
932                             QualType modifiedType,
933                             QualType equivalentType);
934
935  QualType getSubstTemplateTypeParmType(const TemplateTypeParmType *Replaced,
936                                        QualType Replacement) const;
937  QualType getSubstTemplateTypeParmPackType(
938                                          const TemplateTypeParmType *Replaced,
939                                            const TemplateArgument &ArgPack);
940
941  QualType getTemplateTypeParmType(unsigned Depth, unsigned Index,
942                                   bool ParameterPack,
943                                   TemplateTypeParmDecl *ParmDecl = 0) const;
944
945  QualType getTemplateSpecializationType(TemplateName T,
946                                         const TemplateArgument *Args,
947                                         unsigned NumArgs,
948                                         QualType Canon = QualType()) const;
949
950  QualType getCanonicalTemplateSpecializationType(TemplateName T,
951                                                  const TemplateArgument *Args,
952                                                  unsigned NumArgs) const;
953
954  QualType getTemplateSpecializationType(TemplateName T,
955                                         const TemplateArgumentListInfo &Args,
956                                         QualType Canon = QualType()) const;
957
958  TypeSourceInfo *
959  getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc,
960                                    const TemplateArgumentListInfo &Args,
961                                    QualType Canon = QualType()) const;
962
963  QualType getParenType(QualType NamedType) const;
964
965  QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
966                             NestedNameSpecifier *NNS,
967                             QualType NamedType) const;
968  QualType getDependentNameType(ElaboratedTypeKeyword Keyword,
969                                NestedNameSpecifier *NNS,
970                                const IdentifierInfo *Name,
971                                QualType Canon = QualType()) const;
972
973  QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
974                                                  NestedNameSpecifier *NNS,
975                                                  const IdentifierInfo *Name,
976                                    const TemplateArgumentListInfo &Args) const;
977  QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
978                                                  NestedNameSpecifier *NNS,
979                                                  const IdentifierInfo *Name,
980                                                  unsigned NumArgs,
981                                            const TemplateArgument *Args) const;
982
983  QualType getPackExpansionType(QualType Pattern,
984                                llvm::Optional<unsigned> NumExpansions);
985
986  QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
987                                ObjCInterfaceDecl *PrevDecl = 0) const;
988
989  QualType getObjCObjectType(QualType Base,
990                             ObjCProtocolDecl * const *Protocols,
991                             unsigned NumProtocols) const;
992
993  /// getObjCObjectPointerType - Return a ObjCObjectPointerType type
994  /// for the given ObjCObjectType.
995  QualType getObjCObjectPointerType(QualType OIT) const;
996
997  /// getTypeOfType - GCC extension.
998  QualType getTypeOfExprType(Expr *e) const;
999  QualType getTypeOfType(QualType t) const;
1000
1001  /// getDecltypeType - C++0x decltype.
1002  QualType getDecltypeType(Expr *e, QualType UnderlyingType) const;
1003
1004  /// getUnaryTransformType - unary type transforms
1005  QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
1006                                 UnaryTransformType::UTTKind UKind) const;
1007
1008  /// getAutoType - C++0x deduced auto type.
1009  QualType getAutoType(QualType DeducedType) const;
1010
1011  /// getAutoDeductType - C++0x deduction pattern for 'auto' type.
1012  QualType getAutoDeductType() const;
1013
1014  /// getAutoRRefDeductType - C++0x deduction pattern for 'auto &&' type.
1015  QualType getAutoRRefDeductType() const;
1016
1017  /// getTagDeclType - Return the unique reference to the type for the
1018  /// specified TagDecl (struct/union/class/enum) decl.
1019  QualType getTagDeclType(const TagDecl *Decl) const;
1020
1021  /// getSizeType - Return the unique type for "size_t" (C99 7.17), defined
1022  /// in <stddef.h>. The sizeof operator requires this (C99 6.5.3.4p4).
1023  CanQualType getSizeType() const;
1024
1025  /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5),
1026  /// defined in <stdint.h>.
1027  CanQualType getIntMaxType() const;
1028
1029  /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5),
1030  /// defined in <stdint.h>.
1031  CanQualType getUIntMaxType() const;
1032
1033  /// getWCharType - In C++, this returns the unique wchar_t type.  In C99, this
1034  /// returns a type compatible with the type defined in <stddef.h> as defined
1035  /// by the target.
1036  QualType getWCharType() const { return WCharTy; }
1037
1038  /// getSignedWCharType - Return the type of "signed wchar_t".
1039  /// Used when in C++, as a GCC extension.
1040  QualType getSignedWCharType() const;
1041
1042  /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
1043  /// Used when in C++, as a GCC extension.
1044  QualType getUnsignedWCharType() const;
1045
1046  /// getWIntType - In C99, this returns a type compatible with the type
1047  /// defined in <stddef.h> as defined by the target.
1048  QualType getWIntType() const { return WIntTy; }
1049
1050  /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
1051  /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1052  QualType getPointerDiffType() const;
1053
1054  // getCFConstantStringType - Return the C structure type used to represent
1055  // constant CFStrings.
1056  QualType getCFConstantStringType() const;
1057
1058  /// Get the structure type used to representation CFStrings, or NULL
1059  /// if it hasn't yet been built.
1060  QualType getRawCFConstantStringType() const {
1061    if (CFConstantStringTypeDecl)
1062      return getTagDeclType(CFConstantStringTypeDecl);
1063    return QualType();
1064  }
1065  void setCFConstantStringType(QualType T);
1066
1067  // This setter/getter represents the ObjC type for an NSConstantString.
1068  void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl);
1069  QualType getObjCConstantStringInterface() const {
1070    return ObjCConstantStringType;
1071  }
1072
1073  QualType getObjCNSStringType() const {
1074    return ObjCNSStringType;
1075  }
1076
1077  void setObjCNSStringType(QualType T) {
1078    ObjCNSStringType = T;
1079  }
1080
1081  /// \brief Retrieve the type that 'id' has been defined to, which may be
1082  /// different from the built-in 'id' if 'id' has been typedef'd.
1083  QualType getObjCIdRedefinitionType() const {
1084    if (ObjCIdRedefinitionType.isNull())
1085      return getObjCIdType();
1086    return ObjCIdRedefinitionType;
1087  }
1088
1089  /// \brief Set the user-written type that redefines 'id'.
1090  void setObjCIdRedefinitionType(QualType RedefType) {
1091    ObjCIdRedefinitionType = RedefType;
1092  }
1093
1094  /// \brief Retrieve the type that 'Class' has been defined to, which may be
1095  /// different from the built-in 'Class' if 'Class' has been typedef'd.
1096  QualType getObjCClassRedefinitionType() const {
1097    if (ObjCClassRedefinitionType.isNull())
1098      return getObjCClassType();
1099    return ObjCClassRedefinitionType;
1100  }
1101
1102  /// \brief Set the user-written type that redefines 'SEL'.
1103  void setObjCClassRedefinitionType(QualType RedefType) {
1104    ObjCClassRedefinitionType = RedefType;
1105  }
1106
1107  /// \brief Retrieve the type that 'SEL' has been defined to, which may be
1108  /// different from the built-in 'SEL' if 'SEL' has been typedef'd.
1109  QualType getObjCSelRedefinitionType() const {
1110    if (ObjCSelRedefinitionType.isNull())
1111      return getObjCSelType();
1112    return ObjCSelRedefinitionType;
1113  }
1114
1115
1116  /// \brief Set the user-written type that redefines 'SEL'.
1117  void setObjCSelRedefinitionType(QualType RedefType) {
1118    ObjCSelRedefinitionType = RedefType;
1119  }
1120
1121  /// \brief Retrieve the Objective-C "instancetype" type, if already known;
1122  /// otherwise, returns a NULL type;
1123  QualType getObjCInstanceType() {
1124    return getTypeDeclType(getObjCInstanceTypeDecl());
1125  }
1126
1127  /// \brief Retrieve the typedef declaration corresponding to the Objective-C
1128  /// "instancetype" type.
1129  TypedefDecl *getObjCInstanceTypeDecl();
1130
1131  /// \brief Set the type for the C FILE type.
1132  void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; }
1133
1134  /// \brief Retrieve the C FILE type.
1135  QualType getFILEType() const {
1136    if (FILEDecl)
1137      return getTypeDeclType(FILEDecl);
1138    return QualType();
1139  }
1140
1141  /// \brief Set the type for the C jmp_buf type.
1142  void setjmp_bufDecl(TypeDecl *jmp_bufDecl) {
1143    this->jmp_bufDecl = jmp_bufDecl;
1144  }
1145
1146  /// \brief Retrieve the C jmp_buf type.
1147  QualType getjmp_bufType() const {
1148    if (jmp_bufDecl)
1149      return getTypeDeclType(jmp_bufDecl);
1150    return QualType();
1151  }
1152
1153  /// \brief Set the type for the C sigjmp_buf type.
1154  void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) {
1155    this->sigjmp_bufDecl = sigjmp_bufDecl;
1156  }
1157
1158  /// \brief Retrieve the C sigjmp_buf type.
1159  QualType getsigjmp_bufType() const {
1160    if (sigjmp_bufDecl)
1161      return getTypeDeclType(sigjmp_bufDecl);
1162    return QualType();
1163  }
1164
1165  /// \brief Set the type for the C ucontext_t type.
1166  void setucontext_tDecl(TypeDecl *ucontext_tDecl) {
1167    this->ucontext_tDecl = ucontext_tDecl;
1168  }
1169
1170  /// \brief Retrieve the C ucontext_t type.
1171  QualType getucontext_tType() const {
1172    if (ucontext_tDecl)
1173      return getTypeDeclType(ucontext_tDecl);
1174    return QualType();
1175  }
1176
1177  /// \brief The result type of logical operations, '<', '>', '!=', etc.
1178  QualType getLogicalOperationType() const {
1179    return getLangOpts().CPlusPlus ? BoolTy : IntTy;
1180  }
1181
1182  /// getObjCEncodingForType - Emit the ObjC type encoding for the
1183  /// given type into \arg S. If \arg NameFields is specified then
1184  /// record field names are also encoded.
1185  void getObjCEncodingForType(QualType t, std::string &S,
1186                              const FieldDecl *Field=0) const;
1187
1188  void getLegacyIntegralTypeEncoding(QualType &t) const;
1189
1190  // Put the string version of type qualifiers into S.
1191  void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
1192                                       std::string &S) const;
1193
1194  /// getObjCEncodingForFunctionDecl - Returns the encoded type for this
1195  /// function.  This is in the same format as Objective-C method encodings.
1196  ///
1197  /// \returns true if an error occurred (e.g., because one of the parameter
1198  /// types is incomplete), false otherwise.
1199  bool getObjCEncodingForFunctionDecl(const FunctionDecl *Decl, std::string& S);
1200
1201  /// getObjCEncodingForMethodDecl - Return the encoded type for this method
1202  /// declaration.
1203  ///
1204  /// \returns true if an error occurred (e.g., because one of the parameter
1205  /// types is incomplete), false otherwise.
1206  bool getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, std::string &S,
1207                                    bool Extended = false)
1208    const;
1209
1210  /// getObjCEncodingForBlock - Return the encoded type for this block
1211  /// declaration.
1212  std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const;
1213
1214  /// getObjCEncodingForPropertyDecl - Return the encoded type for
1215  /// this method declaration. If non-NULL, Container must be either
1216  /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
1217  /// only be NULL when getting encodings for protocol properties.
1218  void getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
1219                                      const Decl *Container,
1220                                      std::string &S) const;
1221
1222  bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
1223                                      ObjCProtocolDecl *rProto) const;
1224
1225  /// getObjCEncodingTypeSize returns size of type for objective-c encoding
1226  /// purpose in characters.
1227  CharUnits getObjCEncodingTypeSize(QualType t) const;
1228
1229  /// \brief Retrieve the typedef corresponding to the predefined 'id' type
1230  /// in Objective-C.
1231  TypedefDecl *getObjCIdDecl() const;
1232
1233  /// This setter/getter represents the ObjC 'id' type. It is setup lazily, by
1234  /// Sema.  id is always a (typedef for a) pointer type, a pointer to a struct.
1235  QualType getObjCIdType() const {
1236    return getTypeDeclType(getObjCIdDecl());
1237  }
1238
1239  /// \brief Retrieve the typedef corresponding to the predefined 'SEL' type
1240  /// in Objective-C.
1241  TypedefDecl *getObjCSelDecl() const;
1242
1243  /// \brief Retrieve the type that corresponds to the predefined Objective-C
1244  /// 'SEL' type.
1245  QualType getObjCSelType() const {
1246    return getTypeDeclType(getObjCSelDecl());
1247  }
1248
1249  /// \brief Retrieve the typedef declaration corresponding to the predefined
1250  /// Objective-C 'Class' type.
1251  TypedefDecl *getObjCClassDecl() const;
1252
1253  /// This setter/getter repreents the ObjC 'Class' type. It is setup lazily, by
1254  /// Sema.  'Class' is always a (typedef for a) pointer type, a pointer to a
1255  /// struct.
1256  QualType getObjCClassType() const {
1257    return getTypeDeclType(getObjCClassDecl());
1258  }
1259
1260  /// \brief Retrieve the Objective-C class declaration corresponding to
1261  /// the predefined 'Protocol' class.
1262  ObjCInterfaceDecl *getObjCProtocolDecl() const;
1263
1264  /// \brief Retrieve declaration of 'BOOL' typedef
1265  TypedefDecl *getBOOLDecl() const {
1266    return BOOLDecl;
1267  }
1268
1269  /// \brief Save declaration of 'BOOL' typedef
1270  void setBOOLDecl(TypedefDecl *TD) {
1271    BOOLDecl = TD;
1272  }
1273
1274  /// \brief type of 'BOOL' type.
1275  QualType getBOOLType() const {
1276    return getTypeDeclType(getBOOLDecl());
1277  }
1278
1279  /// \brief Retrieve the type of the Objective-C "Protocol" class.
1280  QualType getObjCProtoType() const {
1281    return getObjCInterfaceType(getObjCProtocolDecl());
1282  }
1283
1284  /// \brief Retrieve the C type declaration corresponding to the predefined
1285  /// __builtin_va_list type.
1286  TypedefDecl *getBuiltinVaListDecl() const;
1287
1288  /// \brief Retrieve the type of the __builtin_va_list type.
1289  QualType getBuiltinVaListType() const {
1290    return getTypeDeclType(getBuiltinVaListDecl());
1291  }
1292
1293  /// \brief Retrieve the C type declaration corresponding to the predefined
1294  /// __va_list_tag type used to help define the __builtin_va_list type for
1295  /// some targets.
1296  QualType getVaListTagType() const;
1297
1298  /// getCVRQualifiedType - Returns a type with additional const,
1299  /// volatile, or restrict qualifiers.
1300  QualType getCVRQualifiedType(QualType T, unsigned CVR) const {
1301    return getQualifiedType(T, Qualifiers::fromCVRMask(CVR));
1302  }
1303
1304  /// getQualifiedType - Un-split a SplitQualType.
1305  QualType getQualifiedType(SplitQualType split) const {
1306    return getQualifiedType(split.Ty, split.Quals);
1307  }
1308
1309  /// getQualifiedType - Returns a type with additional qualifiers.
1310  QualType getQualifiedType(QualType T, Qualifiers Qs) const {
1311    if (!Qs.hasNonFastQualifiers())
1312      return T.withFastQualifiers(Qs.getFastQualifiers());
1313    QualifierCollector Qc(Qs);
1314    const Type *Ptr = Qc.strip(T);
1315    return getExtQualType(Ptr, Qc);
1316  }
1317
1318  /// getQualifiedType - Returns a type with additional qualifiers.
1319  QualType getQualifiedType(const Type *T, Qualifiers Qs) const {
1320    if (!Qs.hasNonFastQualifiers())
1321      return QualType(T, Qs.getFastQualifiers());
1322    return getExtQualType(T, Qs);
1323  }
1324
1325  /// getLifetimeQualifiedType - Returns a type with the given
1326  /// lifetime qualifier.
1327  QualType getLifetimeQualifiedType(QualType type,
1328                                    Qualifiers::ObjCLifetime lifetime) {
1329    assert(type.getObjCLifetime() == Qualifiers::OCL_None);
1330    assert(lifetime != Qualifiers::OCL_None);
1331
1332    Qualifiers qs;
1333    qs.addObjCLifetime(lifetime);
1334    return getQualifiedType(type, qs);
1335  }
1336
1337  DeclarationNameInfo getNameForTemplate(TemplateName Name,
1338                                         SourceLocation NameLoc) const;
1339
1340  TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin,
1341                                         UnresolvedSetIterator End) const;
1342
1343  TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
1344                                        bool TemplateKeyword,
1345                                        TemplateDecl *Template) const;
1346
1347  TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1348                                        const IdentifierInfo *Name) const;
1349  TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1350                                        OverloadedOperatorKind Operator) const;
1351  TemplateName getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
1352                                            TemplateName replacement) const;
1353  TemplateName getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
1354                                        const TemplateArgument &ArgPack) const;
1355
1356  enum GetBuiltinTypeError {
1357    GE_None,              ///< No error
1358    GE_Missing_stdio,     ///< Missing a type from <stdio.h>
1359    GE_Missing_setjmp,    ///< Missing a type from <setjmp.h>
1360    GE_Missing_ucontext   ///< Missing a type from <ucontext.h>
1361  };
1362
1363  /// GetBuiltinType - Return the type for the specified builtin.  If
1364  /// IntegerConstantArgs is non-null, it is filled in with a bitmask of
1365  /// arguments to the builtin that are required to be integer constant
1366  /// expressions.
1367  QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error,
1368                          unsigned *IntegerConstantArgs = 0) const;
1369
1370private:
1371  CanQualType getFromTargetType(unsigned Type) const;
1372  std::pair<uint64_t, unsigned> getTypeInfoImpl(const Type *T) const;
1373
1374  //===--------------------------------------------------------------------===//
1375  //                         Type Predicates.
1376  //===--------------------------------------------------------------------===//
1377
1378public:
1379  /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
1380  /// garbage collection attribute.
1381  ///
1382  Qualifiers::GC getObjCGCAttrKind(QualType Ty) const;
1383
1384  /// areCompatibleVectorTypes - Return true if the given vector types
1385  /// are of the same unqualified type or if they are equivalent to the same
1386  /// GCC vector type, ignoring whether they are target-specific (AltiVec or
1387  /// Neon) types.
1388  bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec);
1389
1390  /// isObjCNSObjectType - Return true if this is an NSObject object with
1391  /// its NSObject attribute set.
1392  static bool isObjCNSObjectType(QualType Ty) {
1393    return Ty->isObjCNSObjectType();
1394  }
1395
1396  //===--------------------------------------------------------------------===//
1397  //                         Type Sizing and Analysis
1398  //===--------------------------------------------------------------------===//
1399
1400  /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1401  /// scalar floating point type.
1402  const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
1403
1404  /// getTypeInfo - Get the size and alignment of the specified complete type in
1405  /// bits.
1406  std::pair<uint64_t, unsigned> getTypeInfo(const Type *T) const;
1407  std::pair<uint64_t, unsigned> getTypeInfo(QualType T) const {
1408    return getTypeInfo(T.getTypePtr());
1409  }
1410
1411  /// getTypeSize - Return the size of the specified type, in bits.  This method
1412  /// does not work on incomplete types.
1413  uint64_t getTypeSize(QualType T) const {
1414    return getTypeInfo(T).first;
1415  }
1416  uint64_t getTypeSize(const Type *T) const {
1417    return getTypeInfo(T).first;
1418  }
1419
1420  /// getCharWidth - Return the size of the character type, in bits
1421  uint64_t getCharWidth() const {
1422    return getTypeSize(CharTy);
1423  }
1424
1425  /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1426  CharUnits toCharUnitsFromBits(int64_t BitSize) const;
1427
1428  /// toBits - Convert a size in characters to a size in bits.
1429  int64_t toBits(CharUnits CharSize) const;
1430
1431  /// getTypeSizeInChars - Return the size of the specified type, in characters.
1432  /// This method does not work on incomplete types.
1433  CharUnits getTypeSizeInChars(QualType T) const;
1434  CharUnits getTypeSizeInChars(const Type *T) const;
1435
1436  /// getTypeAlign - Return the ABI-specified alignment of a type, in bits.
1437  /// This method does not work on incomplete types.
1438  unsigned getTypeAlign(QualType T) const {
1439    return getTypeInfo(T).second;
1440  }
1441  unsigned getTypeAlign(const Type *T) const {
1442    return getTypeInfo(T).second;
1443  }
1444
1445  /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
1446  /// characters. This method does not work on incomplete types.
1447  CharUnits getTypeAlignInChars(QualType T) const;
1448  CharUnits getTypeAlignInChars(const Type *T) const;
1449
1450  // getTypeInfoDataSizeInChars - Return the size of a type, in chars. If the
1451  // type is a record, its data size is returned.
1452  std::pair<CharUnits, CharUnits> getTypeInfoDataSizeInChars(QualType T) const;
1453
1454  std::pair<CharUnits, CharUnits> getTypeInfoInChars(const Type *T) const;
1455  std::pair<CharUnits, CharUnits> getTypeInfoInChars(QualType T) const;
1456
1457  /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1458  /// type for the current target in bits.  This can be different than the ABI
1459  /// alignment in cases where it is beneficial for performance to overalign
1460  /// a data type.
1461  unsigned getPreferredTypeAlign(const Type *T) const;
1462
1463  /// getDeclAlign - Return a conservative estimate of the alignment of
1464  /// the specified decl.  Note that bitfields do not have a valid alignment, so
1465  /// this method will assert on them.
1466  /// If @p RefAsPointee, references are treated like their underlying type
1467  /// (for alignof), else they're treated like pointers (for CodeGen).
1468  CharUnits getDeclAlign(const Decl *D, bool RefAsPointee = false) const;
1469
1470  /// getASTRecordLayout - Get or compute information about the layout of the
1471  /// specified record (struct/union/class), which indicates its size and field
1472  /// position information.
1473  const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D) const;
1474
1475  /// getASTObjCInterfaceLayout - Get or compute information about the
1476  /// layout of the specified Objective-C interface.
1477  const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D)
1478    const;
1479
1480  void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS,
1481                        bool Simple = false) const;
1482
1483  /// getASTObjCImplementationLayout - Get or compute information about
1484  /// the layout of the specified Objective-C implementation. This may
1485  /// differ from the interface if synthesized ivars are present.
1486  const ASTRecordLayout &
1487  getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const;
1488
1489  /// getKeyFunction - Get the key function for the given record decl, or NULL
1490  /// if there isn't one.  The key function is, according to the Itanium C++ ABI
1491  /// section 5.2.3:
1492  ///
1493  /// ...the first non-pure virtual function that is not inline at the point
1494  /// of class definition.
1495  const CXXMethodDecl *getKeyFunction(const CXXRecordDecl *RD);
1496
1497  /// Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
1498  uint64_t getFieldOffset(const ValueDecl *FD) const;
1499
1500  bool isNearlyEmpty(const CXXRecordDecl *RD) const;
1501
1502  MangleContext *createMangleContext();
1503
1504  void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass,
1505                            SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const;
1506
1507  unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const;
1508  void CollectInheritedProtocols(const Decl *CDecl,
1509                          llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols);
1510
1511  //===--------------------------------------------------------------------===//
1512  //                            Type Operators
1513  //===--------------------------------------------------------------------===//
1514
1515  /// getCanonicalType - Return the canonical (structural) type corresponding to
1516  /// the specified potentially non-canonical type.  The non-canonical version
1517  /// of a type may have many "decorated" versions of types.  Decorators can
1518  /// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
1519  /// to be free of any of these, allowing two canonical types to be compared
1520  /// for exact equality with a simple pointer comparison.
1521  CanQualType getCanonicalType(QualType T) const {
1522    return CanQualType::CreateUnsafe(T.getCanonicalType());
1523  }
1524
1525  const Type *getCanonicalType(const Type *T) const {
1526    return T->getCanonicalTypeInternal().getTypePtr();
1527  }
1528
1529  /// getCanonicalParamType - Return the canonical parameter type
1530  /// corresponding to the specific potentially non-canonical one.
1531  /// Qualifiers are stripped off, functions are turned into function
1532  /// pointers, and arrays decay one level into pointers.
1533  CanQualType getCanonicalParamType(QualType T) const;
1534
1535  /// \brief Determine whether the given types are equivalent.
1536  bool hasSameType(QualType T1, QualType T2) const {
1537    return getCanonicalType(T1) == getCanonicalType(T2);
1538  }
1539
1540  /// \brief Returns this type as a completely-unqualified array type,
1541  /// capturing the qualifiers in Quals. This will remove the minimal amount of
1542  /// sugaring from the types, similar to the behavior of
1543  /// QualType::getUnqualifiedType().
1544  ///
1545  /// \param T is the qualified type, which may be an ArrayType
1546  ///
1547  /// \param Quals will receive the full set of qualifiers that were
1548  /// applied to the array.
1549  ///
1550  /// \returns if this is an array type, the completely unqualified array type
1551  /// that corresponds to it. Otherwise, returns T.getUnqualifiedType().
1552  QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals);
1553
1554  /// \brief Determine whether the given types are equivalent after
1555  /// cvr-qualifiers have been removed.
1556  bool hasSameUnqualifiedType(QualType T1, QualType T2) const {
1557    return getCanonicalType(T1).getTypePtr() ==
1558           getCanonicalType(T2).getTypePtr();
1559  }
1560
1561  bool UnwrapSimilarPointerTypes(QualType &T1, QualType &T2);
1562
1563  /// \brief Retrieves the "canonical" nested name specifier for a
1564  /// given nested name specifier.
1565  ///
1566  /// The canonical nested name specifier is a nested name specifier
1567  /// that uniquely identifies a type or namespace within the type
1568  /// system. For example, given:
1569  ///
1570  /// \code
1571  /// namespace N {
1572  ///   struct S {
1573  ///     template<typename T> struct X { typename T* type; };
1574  ///   };
1575  /// }
1576  ///
1577  /// template<typename T> struct Y {
1578  ///   typename N::S::X<T>::type member;
1579  /// };
1580  /// \endcode
1581  ///
1582  /// Here, the nested-name-specifier for N::S::X<T>:: will be
1583  /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined
1584  /// by declarations in the type system and the canonical type for
1585  /// the template type parameter 'T' is template-param-0-0.
1586  NestedNameSpecifier *
1587  getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const;
1588
1589  /// \brief Retrieves the default calling convention to use for
1590  /// C++ instance methods.
1591  CallingConv getDefaultCXXMethodCallConv(bool isVariadic);
1592
1593  /// \brief Retrieves the canonical representation of the given
1594  /// calling convention.
1595  CallingConv getCanonicalCallConv(CallingConv CC) const;
1596
1597  /// \brief Determines whether two calling conventions name the same
1598  /// calling convention.
1599  bool isSameCallConv(CallingConv lcc, CallingConv rcc) {
1600    return (getCanonicalCallConv(lcc) == getCanonicalCallConv(rcc));
1601  }
1602
1603  /// \brief Retrieves the "canonical" template name that refers to a
1604  /// given template.
1605  ///
1606  /// The canonical template name is the simplest expression that can
1607  /// be used to refer to a given template. For most templates, this
1608  /// expression is just the template declaration itself. For example,
1609  /// the template std::vector can be referred to via a variety of
1610  /// names---std::vector, \::std::vector, vector (if vector is in
1611  /// scope), etc.---but all of these names map down to the same
1612  /// TemplateDecl, which is used to form the canonical template name.
1613  ///
1614  /// Dependent template names are more interesting. Here, the
1615  /// template name could be something like T::template apply or
1616  /// std::allocator<T>::template rebind, where the nested name
1617  /// specifier itself is dependent. In this case, the canonical
1618  /// template name uses the shortest form of the dependent
1619  /// nested-name-specifier, which itself contains all canonical
1620  /// types, values, and templates.
1621  TemplateName getCanonicalTemplateName(TemplateName Name) const;
1622
1623  /// \brief Determine whether the given template names refer to the same
1624  /// template.
1625  bool hasSameTemplateName(TemplateName X, TemplateName Y);
1626
1627  /// \brief Retrieve the "canonical" template argument.
1628  ///
1629  /// The canonical template argument is the simplest template argument
1630  /// (which may be a type, value, expression, or declaration) that
1631  /// expresses the value of the argument.
1632  TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg)
1633    const;
1634
1635  /// Type Query functions.  If the type is an instance of the specified class,
1636  /// return the Type pointer for the underlying maximally pretty type.  This
1637  /// is a member of ASTContext because this may need to do some amount of
1638  /// canonicalization, e.g. to move type qualifiers into the element type.
1639  const ArrayType *getAsArrayType(QualType T) const;
1640  const ConstantArrayType *getAsConstantArrayType(QualType T) const {
1641    return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T));
1642  }
1643  const VariableArrayType *getAsVariableArrayType(QualType T) const {
1644    return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T));
1645  }
1646  const IncompleteArrayType *getAsIncompleteArrayType(QualType T) const {
1647    return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
1648  }
1649  const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T)
1650    const {
1651    return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T));
1652  }
1653
1654  /// getBaseElementType - Returns the innermost element type of an array type.
1655  /// For example, will return "int" for int[m][n]
1656  QualType getBaseElementType(const ArrayType *VAT) const;
1657
1658  /// getBaseElementType - Returns the innermost element type of a type
1659  /// (which needn't actually be an array type).
1660  QualType getBaseElementType(QualType QT) const;
1661
1662  /// getConstantArrayElementCount - Returns number of constant array elements.
1663  uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const;
1664
1665  /// \brief Perform adjustment on the parameter type of a function.
1666  ///
1667  /// This routine adjusts the given parameter type @p T to the actual
1668  /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
1669  /// C++ [dcl.fct]p3). The adjusted parameter type is returned.
1670  QualType getAdjustedParameterType(QualType T) const;
1671
1672  /// \brief Retrieve the parameter type as adjusted for use in the signature
1673  /// of a function, decaying array and function types and removing top-level
1674  /// cv-qualifiers.
1675  QualType getSignatureParameterType(QualType T) const;
1676
1677  /// getArrayDecayedType - Return the properly qualified result of decaying the
1678  /// specified array type to a pointer.  This operation is non-trivial when
1679  /// handling typedefs etc.  The canonical type of "T" must be an array type,
1680  /// this returns a pointer to a properly qualified element of the array.
1681  ///
1682  /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
1683  QualType getArrayDecayedType(QualType T) const;
1684
1685  /// getPromotedIntegerType - Returns the type that Promotable will
1686  /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
1687  /// integer type.
1688  QualType getPromotedIntegerType(QualType PromotableType) const;
1689
1690  /// \brief Recurses in pointer/array types until it finds an objc retainable
1691  /// type and returns its ownership.
1692  Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const;
1693
1694  /// \brief Whether this is a promotable bitfield reference according
1695  /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
1696  ///
1697  /// \returns the type this bit-field will promote to, or NULL if no
1698  /// promotion occurs.
1699  QualType isPromotableBitField(Expr *E) const;
1700
1701  /// getIntegerTypeOrder - Returns the highest ranked integer type:
1702  /// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
1703  /// LHS < RHS, return -1.
1704  int getIntegerTypeOrder(QualType LHS, QualType RHS) const;
1705
1706  /// getFloatingTypeOrder - Compare the rank of the two specified floating
1707  /// point types, ignoring the domain of the type (i.e. 'double' ==
1708  /// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
1709  /// LHS < RHS, return -1.
1710  int getFloatingTypeOrder(QualType LHS, QualType RHS) const;
1711
1712  /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
1713  /// point or a complex type (based on typeDomain/typeSize).
1714  /// 'typeDomain' is a real floating point or complex type.
1715  /// 'typeSize' is a real floating point or complex type.
1716  QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
1717                                             QualType typeDomain) const;
1718
1719  unsigned getTargetAddressSpace(QualType T) const {
1720    return getTargetAddressSpace(T.getQualifiers());
1721  }
1722
1723  unsigned getTargetAddressSpace(Qualifiers Q) const {
1724    return getTargetAddressSpace(Q.getAddressSpace());
1725  }
1726
1727  unsigned getTargetAddressSpace(unsigned AS) const {
1728    if (AS < LangAS::Offset || AS >= LangAS::Offset + LangAS::Count)
1729      return AS;
1730    else
1731      return (*AddrSpaceMap)[AS - LangAS::Offset];
1732  }
1733
1734private:
1735  // Helper for integer ordering
1736  unsigned getIntegerRank(const Type *T) const;
1737
1738public:
1739
1740  //===--------------------------------------------------------------------===//
1741  //                    Type Compatibility Predicates
1742  //===--------------------------------------------------------------------===//
1743
1744  /// Compatibility predicates used to check assignment expressions.
1745  bool typesAreCompatible(QualType T1, QualType T2,
1746                          bool CompareUnqualified = false); // C99 6.2.7p1
1747
1748  bool propertyTypesAreCompatible(QualType, QualType);
1749  bool typesAreBlockPointerCompatible(QualType, QualType);
1750
1751  bool isObjCIdType(QualType T) const {
1752    return T == getObjCIdType();
1753  }
1754  bool isObjCClassType(QualType T) const {
1755    return T == getObjCClassType();
1756  }
1757  bool isObjCSelType(QualType T) const {
1758    return T == getObjCSelType();
1759  }
1760  bool QualifiedIdConformsQualifiedId(QualType LHS, QualType RHS);
1761  bool ObjCQualifiedIdTypesAreCompatible(QualType LHS, QualType RHS,
1762                                         bool ForCompare);
1763
1764  bool ObjCQualifiedClassTypesAreCompatible(QualType LHS, QualType RHS);
1765
1766  // Check the safety of assignment from LHS to RHS
1767  bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
1768                               const ObjCObjectPointerType *RHSOPT);
1769  bool canAssignObjCInterfaces(const ObjCObjectType *LHS,
1770                               const ObjCObjectType *RHS);
1771  bool canAssignObjCInterfacesInBlockPointer(
1772                                          const ObjCObjectPointerType *LHSOPT,
1773                                          const ObjCObjectPointerType *RHSOPT,
1774                                          bool BlockReturnType);
1775  bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
1776  QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT,
1777                                   const ObjCObjectPointerType *RHSOPT);
1778  bool canBindObjCObjectType(QualType To, QualType From);
1779
1780  // Functions for calculating composite types
1781  QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false,
1782                      bool Unqualified = false, bool BlockReturnType = false);
1783  QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false,
1784                              bool Unqualified = false);
1785  QualType mergeFunctionArgumentTypes(QualType, QualType,
1786                                      bool OfBlockPointer=false,
1787                                      bool Unqualified = false);
1788  QualType mergeTransparentUnionType(QualType, QualType,
1789                                     bool OfBlockPointer=false,
1790                                     bool Unqualified = false);
1791
1792  QualType mergeObjCGCQualifiers(QualType, QualType);
1793
1794  bool FunctionTypesMatchOnNSConsumedAttrs(
1795         const FunctionProtoType *FromFunctionType,
1796         const FunctionProtoType *ToFunctionType);
1797
1798  void ResetObjCLayout(const ObjCContainerDecl *CD) {
1799    ObjCLayouts[CD] = 0;
1800  }
1801
1802  //===--------------------------------------------------------------------===//
1803  //                    Integer Predicates
1804  //===--------------------------------------------------------------------===//
1805
1806  // The width of an integer, as defined in C99 6.2.6.2. This is the number
1807  // of bits in an integer type excluding any padding bits.
1808  unsigned getIntWidth(QualType T) const;
1809
1810  // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
1811  // unsigned integer type.  This method takes a signed type, and returns the
1812  // corresponding unsigned integer type.
1813  QualType getCorrespondingUnsignedType(QualType T);
1814
1815  //===--------------------------------------------------------------------===//
1816  //                    Type Iterators.
1817  //===--------------------------------------------------------------------===//
1818
1819  typedef std::vector<Type*>::iterator       type_iterator;
1820  typedef std::vector<Type*>::const_iterator const_type_iterator;
1821
1822  type_iterator types_begin() { return Types.begin(); }
1823  type_iterator types_end() { return Types.end(); }
1824  const_type_iterator types_begin() const { return Types.begin(); }
1825  const_type_iterator types_end() const { return Types.end(); }
1826
1827  //===--------------------------------------------------------------------===//
1828  //                    Integer Values
1829  //===--------------------------------------------------------------------===//
1830
1831  /// MakeIntValue - Make an APSInt of the appropriate width and
1832  /// signedness for the given \arg Value and integer \arg Type.
1833  llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const {
1834    llvm::APSInt Res(getIntWidth(Type),
1835                     !Type->isSignedIntegerOrEnumerationType());
1836    Res = Value;
1837    return Res;
1838  }
1839
1840  bool isSentinelNullExpr(const Expr *E);
1841
1842  /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1843  ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D);
1844  /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1845  ObjCCategoryImplDecl   *getObjCImplementation(ObjCCategoryDecl *D);
1846
1847  /// \brief returns true if there is at least one \@implementation in TU.
1848  bool AnyObjCImplementation() {
1849    return !ObjCImpls.empty();
1850  }
1851
1852  /// \brief Set the implementation of ObjCInterfaceDecl.
1853  void setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1854                             ObjCImplementationDecl *ImplD);
1855  /// \brief Set the implementation of ObjCCategoryDecl.
1856  void setObjCImplementation(ObjCCategoryDecl *CatD,
1857                             ObjCCategoryImplDecl *ImplD);
1858
1859  /// \brief Get the duplicate declaration of a ObjCMethod in the same
1860  /// interface, or null if non exists.
1861  const ObjCMethodDecl *getObjCMethodRedeclaration(
1862                                               const ObjCMethodDecl *MD) const {
1863    return ObjCMethodRedecls.lookup(MD);
1864  }
1865
1866  void setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
1867                                  const ObjCMethodDecl *Redecl) {
1868    assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
1869    ObjCMethodRedecls[MD] = Redecl;
1870  }
1871
1872  /// \brief Returns the objc interface that \arg ND belongs to if it is a
1873  /// objc method/property/ivar etc. that is part of an interface,
1874  /// otherwise returns null.
1875  ObjCInterfaceDecl *getObjContainingInterface(NamedDecl *ND) const;
1876
1877  /// \brief Set the copy inialization expression of a block var decl.
1878  void setBlockVarCopyInits(VarDecl*VD, Expr* Init);
1879  /// \brief Get the copy initialization expression of VarDecl,or NULL if
1880  /// none exists.
1881  Expr *getBlockVarCopyInits(const VarDecl*VD);
1882
1883  /// \brief Allocate an uninitialized TypeSourceInfo.
1884  ///
1885  /// The caller should initialize the memory held by TypeSourceInfo using
1886  /// the TypeLoc wrappers.
1887  ///
1888  /// \param T the type that will be the basis for type source info. This type
1889  /// should refer to how the declarator was written in source code, not to
1890  /// what type semantic analysis resolved the declarator to.
1891  ///
1892  /// \param Size the size of the type info to create, or 0 if the size
1893  /// should be calculated based on the type.
1894  TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0) const;
1895
1896  /// \brief Allocate a TypeSourceInfo where all locations have been
1897  /// initialized to a given location, which defaults to the empty
1898  /// location.
1899  TypeSourceInfo *
1900  getTrivialTypeSourceInfo(QualType T,
1901                           SourceLocation Loc = SourceLocation()) const;
1902
1903  TypeSourceInfo *getNullTypeSourceInfo() { return &NullTypeSourceInfo; }
1904
1905  /// \brief Add a deallocation callback that will be invoked when the
1906  /// ASTContext is destroyed.
1907  ///
1908  /// \param Callback A callback function that will be invoked on destruction.
1909  ///
1910  /// \param Data Pointer data that will be provided to the callback function
1911  /// when it is called.
1912  void AddDeallocation(void (*Callback)(void*), void *Data);
1913
1914  GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD);
1915  GVALinkage GetGVALinkageForVariable(const VarDecl *VD);
1916
1917  /// \brief Determines if the decl can be CodeGen'ed or deserialized from PCH
1918  /// lazily, only when used; this is only relevant for function or file scoped
1919  /// var definitions.
1920  ///
1921  /// \returns true if the function/var must be CodeGen'ed/deserialized even if
1922  /// it is not used.
1923  bool DeclMustBeEmitted(const Decl *D);
1924
1925  /// \brief Retrieve the lambda mangling number for a lambda expression.
1926  unsigned getLambdaManglingNumber(CXXMethodDecl *CallOperator);
1927
1928  /// \brief Used by ParmVarDecl to store on the side the
1929  /// index of the parameter when it exceeds the size of the normal bitfield.
1930  void setParameterIndex(const ParmVarDecl *D, unsigned index);
1931
1932  /// \brief Used by ParmVarDecl to retrieve on the side the
1933  /// index of the parameter when it exceeds the size of the normal bitfield.
1934  unsigned getParameterIndex(const ParmVarDecl *D) const;
1935
1936  //===--------------------------------------------------------------------===//
1937  //                    Statistics
1938  //===--------------------------------------------------------------------===//
1939
1940  /// \brief The number of implicitly-declared default constructors.
1941  static unsigned NumImplicitDefaultConstructors;
1942
1943  /// \brief The number of implicitly-declared default constructors for
1944  /// which declarations were built.
1945  static unsigned NumImplicitDefaultConstructorsDeclared;
1946
1947  /// \brief The number of implicitly-declared copy constructors.
1948  static unsigned NumImplicitCopyConstructors;
1949
1950  /// \brief The number of implicitly-declared copy constructors for
1951  /// which declarations were built.
1952  static unsigned NumImplicitCopyConstructorsDeclared;
1953
1954  /// \brief The number of implicitly-declared move constructors.
1955  static unsigned NumImplicitMoveConstructors;
1956
1957  /// \brief The number of implicitly-declared move constructors for
1958  /// which declarations were built.
1959  static unsigned NumImplicitMoveConstructorsDeclared;
1960
1961  /// \brief The number of implicitly-declared copy assignment operators.
1962  static unsigned NumImplicitCopyAssignmentOperators;
1963
1964  /// \brief The number of implicitly-declared copy assignment operators for
1965  /// which declarations were built.
1966  static unsigned NumImplicitCopyAssignmentOperatorsDeclared;
1967
1968  /// \brief The number of implicitly-declared move assignment operators.
1969  static unsigned NumImplicitMoveAssignmentOperators;
1970
1971  /// \brief The number of implicitly-declared move assignment operators for
1972  /// which declarations were built.
1973  static unsigned NumImplicitMoveAssignmentOperatorsDeclared;
1974
1975  /// \brief The number of implicitly-declared destructors.
1976  static unsigned NumImplicitDestructors;
1977
1978  /// \brief The number of implicitly-declared destructors for which
1979  /// declarations were built.
1980  static unsigned NumImplicitDestructorsDeclared;
1981
1982private:
1983  ASTContext(const ASTContext&); // DO NOT IMPLEMENT
1984  void operator=(const ASTContext&); // DO NOT IMPLEMENT
1985
1986public:
1987  /// \brief Initialize built-in types.
1988  ///
1989  /// This routine may only be invoked once for a given ASTContext object.
1990  /// It is normally invoked by the ASTContext constructor. However, the
1991  /// constructor can be asked to delay initialization, which places the burden
1992  /// of calling this function on the user of that object.
1993  ///
1994  /// \param Target The target
1995  void InitBuiltinTypes(const TargetInfo &Target);
1996
1997private:
1998  void InitBuiltinType(CanQualType &R, BuiltinType::Kind K);
1999
2000  // Return the ObjC type encoding for a given type.
2001  void getObjCEncodingForTypeImpl(QualType t, std::string &S,
2002                                  bool ExpandPointedToStructures,
2003                                  bool ExpandStructures,
2004                                  const FieldDecl *Field,
2005                                  bool OutermostType = false,
2006                                  bool EncodingProperty = false,
2007                                  bool StructField = false,
2008                                  bool EncodeBlockParameters = false,
2009                                  bool EncodeClassNames = false) const;
2010
2011  // Adds the encoding of the structure's members.
2012  void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S,
2013                                       const FieldDecl *Field,
2014                                       bool includeVBases = true) const;
2015
2016  // Adds the encoding of a method parameter or return type.
2017  void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
2018                                         QualType T, std::string& S,
2019                                         bool Extended) const;
2020
2021  const ASTRecordLayout &
2022  getObjCLayout(const ObjCInterfaceDecl *D,
2023                const ObjCImplementationDecl *Impl) const;
2024
2025private:
2026  /// \brief A set of deallocations that should be performed when the
2027  /// ASTContext is destroyed.
2028  SmallVector<std::pair<void (*)(void*), void *>, 16> Deallocations;
2029
2030  // FIXME: This currently contains the set of StoredDeclMaps used
2031  // by DeclContext objects.  This probably should not be in ASTContext,
2032  // but we include it here so that ASTContext can quickly deallocate them.
2033  llvm::PointerIntPair<StoredDeclsMap*,1> LastSDM;
2034
2035  /// \brief A counter used to uniquely identify "blocks".
2036  mutable unsigned int UniqueBlockByRefTypeID;
2037
2038  friend class DeclContext;
2039  friend class DeclarationNameTable;
2040  void ReleaseDeclContextMaps();
2041};
2042
2043/// @brief Utility function for constructing a nullary selector.
2044static inline Selector GetNullarySelector(StringRef name, ASTContext& Ctx) {
2045  IdentifierInfo* II = &Ctx.Idents.get(name);
2046  return Ctx.Selectors.getSelector(0, &II);
2047}
2048
2049/// @brief Utility function for constructing an unary selector.
2050static inline Selector GetUnarySelector(StringRef name, ASTContext& Ctx) {
2051  IdentifierInfo* II = &Ctx.Idents.get(name);
2052  return Ctx.Selectors.getSelector(1, &II);
2053}
2054
2055}  // end namespace clang
2056
2057// operator new and delete aren't allowed inside namespaces.
2058
2059/// @brief Placement new for using the ASTContext's allocator.
2060///
2061/// This placement form of operator new uses the ASTContext's allocator for
2062/// obtaining memory.
2063///
2064/// IMPORTANT: These are also declared in clang/AST/Attr.h! Any changes here
2065/// need to also be made there.
2066///
2067/// We intentionally avoid using a nothrow specification here so that the calls
2068/// to this operator will not perform a null check on the result -- the
2069/// underlying allocator never returns null pointers.
2070///
2071/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
2072/// @code
2073/// // Default alignment (8)
2074/// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
2075/// // Specific alignment
2076/// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
2077/// @endcode
2078/// Please note that you cannot use delete on the pointer; it must be
2079/// deallocated using an explicit destructor call followed by
2080/// @c Context.Deallocate(Ptr).
2081///
2082/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
2083/// @param C The ASTContext that provides the allocator.
2084/// @param Alignment The alignment of the allocated memory (if the underlying
2085///                  allocator supports it).
2086/// @return The allocated memory. Could be NULL.
2087inline void *operator new(size_t Bytes, const clang::ASTContext &C,
2088                          size_t Alignment) {
2089  return C.Allocate(Bytes, Alignment);
2090}
2091/// @brief Placement delete companion to the new above.
2092///
2093/// This operator is just a companion to the new above. There is no way of
2094/// invoking it directly; see the new operator for more details. This operator
2095/// is called implicitly by the compiler if a placement new expression using
2096/// the ASTContext throws in the object constructor.
2097inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t) {
2098  C.Deallocate(Ptr);
2099}
2100
2101/// This placement form of operator new[] uses the ASTContext's allocator for
2102/// obtaining memory.
2103///
2104/// We intentionally avoid using a nothrow specification here so that the calls
2105/// to this operator will not perform a null check on the result -- the
2106/// underlying allocator never returns null pointers.
2107///
2108/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
2109/// @code
2110/// // Default alignment (8)
2111/// char *data = new (Context) char[10];
2112/// // Specific alignment
2113/// char *data = new (Context, 4) char[10];
2114/// @endcode
2115/// Please note that you cannot use delete on the pointer; it must be
2116/// deallocated using an explicit destructor call followed by
2117/// @c Context.Deallocate(Ptr).
2118///
2119/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
2120/// @param C The ASTContext that provides the allocator.
2121/// @param Alignment The alignment of the allocated memory (if the underlying
2122///                  allocator supports it).
2123/// @return The allocated memory. Could be NULL.
2124inline void *operator new[](size_t Bytes, const clang::ASTContext& C,
2125                            size_t Alignment = 8) {
2126  return C.Allocate(Bytes, Alignment);
2127}
2128
2129/// @brief Placement delete[] companion to the new[] above.
2130///
2131/// This operator is just a companion to the new[] above. There is no way of
2132/// invoking it directly; see the new[] operator for more details. This operator
2133/// is called implicitly by the compiler if a placement new[] expression using
2134/// the ASTContext throws in the object constructor.
2135inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_t) {
2136  C.Deallocate(Ptr);
2137}
2138
2139#endif
2140