1 //===--- ASTContext.h - Context to hold long-lived AST nodes ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief Defines the clang::ASTContext interface.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_AST_ASTCONTEXT_H
16 #define LLVM_CLANG_AST_ASTCONTEXT_H
18 #include "clang/AST/ASTTypeTraits.h"
19 #include "clang/AST/CanonicalType.h"
20 #include "clang/AST/CommentCommandTraits.h"
21 #include "clang/AST/Decl.h"
22 #include "clang/AST/LambdaMangleContext.h"
23 #include "clang/AST/NestedNameSpecifier.h"
24 #include "clang/AST/PrettyPrinter.h"
25 #include "clang/AST/RawCommentList.h"
26 #include "clang/AST/RecursiveASTVisitor.h"
27 #include "clang/AST/TemplateName.h"
28 #include "clang/AST/Type.h"
29 #include "clang/Basic/AddressSpaces.h"
30 #include "clang/Basic/IdentifierTable.h"
31 #include "clang/Basic/LangOptions.h"
32 #include "clang/Basic/OperatorKinds.h"
33 #include "clang/Basic/PartialDiagnostic.h"
34 #include "clang/Basic/VersionTuple.h"
35 #include "llvm/ADT/DenseMap.h"
36 #include "llvm/ADT/FoldingSet.h"
37 #include "llvm/ADT/IntrusiveRefCntPtr.h"
38 #include "llvm/ADT/OwningPtr.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/TinyPtrVector.h"
41 #include "llvm/Support/Allocator.h"
50 class ASTRecordLayout;
53 class DiagnosticsEngine;
55 class ExternalASTSource;
56 class ASTMutationListener;
57 class IdentifierTable;
64 class ObjCPropertyDecl;
65 class UnresolvedSetIterator;
67 class UsingShadowDecl;
69 namespace Builtin { class Context; }
75 /// \brief Holds long-lived AST nodes (such as types and decls) that can be
76 /// referred to throughout the semantic analysis of a file.
77 class ASTContext : public RefCountedBase<ASTContext> {
78 ASTContext &this_() { return *this; }
80 mutable SmallVector<Type *, 0> Types;
81 mutable llvm::FoldingSet<ExtQuals> ExtQualNodes;
82 mutable llvm::FoldingSet<ComplexType> ComplexTypes;
83 mutable llvm::FoldingSet<PointerType> PointerTypes;
84 mutable llvm::FoldingSet<BlockPointerType> BlockPointerTypes;
85 mutable llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes;
86 mutable llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes;
87 mutable llvm::FoldingSet<MemberPointerType> MemberPointerTypes;
88 mutable llvm::FoldingSet<ConstantArrayType> ConstantArrayTypes;
89 mutable llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
90 mutable std::vector<VariableArrayType*> VariableArrayTypes;
91 mutable llvm::FoldingSet<DependentSizedArrayType> DependentSizedArrayTypes;
92 mutable llvm::FoldingSet<DependentSizedExtVectorType>
93 DependentSizedExtVectorTypes;
94 mutable llvm::FoldingSet<VectorType> VectorTypes;
95 mutable llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes;
96 mutable llvm::ContextualFoldingSet<FunctionProtoType, ASTContext&>
98 mutable llvm::FoldingSet<DependentTypeOfExprType> DependentTypeOfExprTypes;
99 mutable llvm::FoldingSet<DependentDecltypeType> DependentDecltypeTypes;
100 mutable llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes;
101 mutable llvm::FoldingSet<SubstTemplateTypeParmType>
102 SubstTemplateTypeParmTypes;
103 mutable llvm::FoldingSet<SubstTemplateTypeParmPackType>
104 SubstTemplateTypeParmPackTypes;
105 mutable llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&>
106 TemplateSpecializationTypes;
107 mutable llvm::FoldingSet<ParenType> ParenTypes;
108 mutable llvm::FoldingSet<ElaboratedType> ElaboratedTypes;
109 mutable llvm::FoldingSet<DependentNameType> DependentNameTypes;
110 mutable llvm::ContextualFoldingSet<DependentTemplateSpecializationType,
112 DependentTemplateSpecializationTypes;
113 llvm::FoldingSet<PackExpansionType> PackExpansionTypes;
114 mutable llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes;
115 mutable llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes;
116 mutable llvm::FoldingSet<AutoType> AutoTypes;
117 mutable llvm::FoldingSet<AtomicType> AtomicTypes;
118 llvm::FoldingSet<AttributedType> AttributedTypes;
120 mutable llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames;
121 mutable llvm::FoldingSet<DependentTemplateName> DependentTemplateNames;
122 mutable llvm::FoldingSet<SubstTemplateTemplateParmStorage>
123 SubstTemplateTemplateParms;
124 mutable llvm::ContextualFoldingSet<SubstTemplateTemplateParmPackStorage,
126 SubstTemplateTemplateParmPacks;
128 /// \brief The set of nested name specifiers.
130 /// This set is managed by the NestedNameSpecifier class.
131 mutable llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers;
132 mutable NestedNameSpecifier *GlobalNestedNameSpecifier;
133 friend class NestedNameSpecifier;
135 /// \brief A cache mapping from RecordDecls to ASTRecordLayouts.
137 /// This is lazily created. This is intentionally not serialized.
138 mutable llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>
140 mutable llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>
143 /// \brief A cache from types to size and alignment information.
144 typedef llvm::DenseMap<const Type*,
145 std::pair<uint64_t, unsigned> > TypeInfoMap;
146 mutable TypeInfoMap MemoizedTypeInfo;
148 /// \brief A cache mapping from CXXRecordDecls to key functions.
149 llvm::DenseMap<const CXXRecordDecl*, const CXXMethodDecl*> KeyFunctions;
151 /// \brief Mapping from ObjCContainers to their ObjCImplementations.
152 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls;
154 /// \brief Mapping from ObjCMethod to its duplicate declaration in the same
156 llvm::DenseMap<const ObjCMethodDecl*,const ObjCMethodDecl*> ObjCMethodRedecls;
158 /// \brief Mapping from __block VarDecls to their copy initialization expr.
159 llvm::DenseMap<const VarDecl*, Expr*> BlockVarCopyInits;
161 /// \brief Mapping from class scope functions specialization to their
162 /// template patterns.
163 llvm::DenseMap<const FunctionDecl*, FunctionDecl*>
164 ClassScopeSpecializationPattern;
166 /// \brief Representation of a "canonical" template template parameter that
167 /// is used in canonical template names.
168 class CanonicalTemplateTemplateParm : public llvm::FoldingSetNode {
169 TemplateTemplateParmDecl *Parm;
172 CanonicalTemplateTemplateParm(TemplateTemplateParmDecl *Parm)
175 TemplateTemplateParmDecl *getParam() const { return Parm; }
177 void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, Parm); }
179 static void Profile(llvm::FoldingSetNodeID &ID,
180 TemplateTemplateParmDecl *Parm);
182 mutable llvm::FoldingSet<CanonicalTemplateTemplateParm>
183 CanonTemplateTemplateParms;
185 TemplateTemplateParmDecl *
186 getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const;
188 /// \brief The typedef for the __int128_t type.
189 mutable TypedefDecl *Int128Decl;
191 /// \brief The typedef for the __uint128_t type.
192 mutable TypedefDecl *UInt128Decl;
194 /// \brief The typedef for the target specific predefined
195 /// __builtin_va_list type.
196 mutable TypedefDecl *BuiltinVaListDecl;
198 /// \brief The typedef for the predefined \c id type.
199 mutable TypedefDecl *ObjCIdDecl;
201 /// \brief The typedef for the predefined \c SEL type.
202 mutable TypedefDecl *ObjCSelDecl;
204 /// \brief The typedef for the predefined \c Class type.
205 mutable TypedefDecl *ObjCClassDecl;
207 /// \brief The typedef for the predefined \c Protocol class in Objective-C.
208 mutable ObjCInterfaceDecl *ObjCProtocolClassDecl;
210 /// \brief The typedef for the predefined 'BOOL' type.
211 mutable TypedefDecl *BOOLDecl;
213 // Typedefs which may be provided defining the structure of Objective-C
215 QualType ObjCIdRedefinitionType;
216 QualType ObjCClassRedefinitionType;
217 QualType ObjCSelRedefinitionType;
219 QualType ObjCConstantStringType;
220 mutable RecordDecl *CFConstantStringTypeDecl;
222 mutable QualType ObjCSuperType;
224 QualType ObjCNSStringType;
226 /// \brief The typedef declaration for the Objective-C "instancetype" type.
227 TypedefDecl *ObjCInstanceTypeDecl;
229 /// \brief The type for the C FILE type.
232 /// \brief The type for the C jmp_buf type.
233 TypeDecl *jmp_bufDecl;
235 /// \brief The type for the C sigjmp_buf type.
236 TypeDecl *sigjmp_bufDecl;
238 /// \brief The type for the C ucontext_t type.
239 TypeDecl *ucontext_tDecl;
241 /// \brief Type for the Block descriptor for Blocks CodeGen.
243 /// Since this is only used for generation of debug info, it is not
245 mutable RecordDecl *BlockDescriptorType;
247 /// \brief Type for the Block descriptor for Blocks CodeGen.
249 /// Since this is only used for generation of debug info, it is not
251 mutable RecordDecl *BlockDescriptorExtendedType;
253 /// \brief Declaration for the CUDA cudaConfigureCall function.
254 FunctionDecl *cudaConfigureCallDecl;
256 TypeSourceInfo NullTypeSourceInfo;
258 /// \brief Keeps track of all declaration attributes.
260 /// Since so few decls have attrs, we keep them in a hash map instead of
261 /// wasting space in the Decl class.
262 llvm::DenseMap<const Decl*, AttrVec*> DeclAttrs;
264 /// \brief Keeps track of the static data member templates from which
265 /// static data members of class template specializations were instantiated.
267 /// This data structure stores the mapping from instantiations of static
268 /// data members to the static data member representations within the
269 /// class template from which they were instantiated along with the kind
270 /// of instantiation or specialization (a TemplateSpecializationKind - 1).
272 /// Given the following example:
275 /// template<typename T>
280 /// template<typename T>
281 /// T X<T>::value = T(17);
283 /// int *x = &X<int>::value;
286 /// This mapping will contain an entry that maps from the VarDecl for
287 /// X<int>::value to the corresponding VarDecl for X<T>::value (within the
288 /// class template X) and will be marked TSK_ImplicitInstantiation.
289 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>
290 InstantiatedFromStaticDataMember;
292 /// \brief Keeps track of the declaration from which a UsingDecl was
293 /// created during instantiation.
295 /// The source declaration is always a UsingDecl, an UnresolvedUsingValueDecl,
296 /// or an UnresolvedUsingTypenameDecl.
300 /// template<typename T>
305 /// template<typename T>
306 /// struct B : A<T> {
310 /// template struct B<int>;
313 /// This mapping will contain an entry that maps from the UsingDecl in
314 /// B<int> to the UnresolvedUsingDecl in B<T>.
315 llvm::DenseMap<UsingDecl *, NamedDecl *> InstantiatedFromUsingDecl;
317 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>
318 InstantiatedFromUsingShadowDecl;
320 llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl;
322 /// \brief Mapping that stores the methods overridden by a given C++
325 /// Since most C++ member functions aren't virtual and therefore
326 /// don't override anything, we store the overridden functions in
327 /// this map on the side rather than within the CXXMethodDecl structure.
328 typedef llvm::TinyPtrVector<const CXXMethodDecl*> CXXMethodVector;
329 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector> OverriddenMethods;
331 /// \brief Mapping from each declaration context to its corresponding lambda
332 /// mangling context.
333 llvm::DenseMap<const DeclContext *, LambdaMangleContext> LambdaMangleContexts;
335 llvm::DenseMap<const DeclContext *, unsigned> UnnamedMangleContexts;
336 llvm::DenseMap<const TagDecl *, unsigned> UnnamedMangleNumbers;
338 /// \brief Mapping that stores parameterIndex values for ParmVarDecls when
339 /// that value exceeds the bitfield size of ParmVarDeclBits.ParameterIndex.
340 typedef llvm::DenseMap<const VarDecl *, unsigned> ParameterIndexTable;
341 ParameterIndexTable ParamIndices;
343 ImportDecl *FirstLocalImport;
344 ImportDecl *LastLocalImport;
346 TranslationUnitDecl *TUDecl;
348 /// \brief The associated SourceManager object.a
349 SourceManager &SourceMgr;
351 /// \brief The language options used to create the AST associated with
352 /// this ASTContext object.
353 LangOptions &LangOpts;
355 /// \brief The allocator used to create AST objects.
357 /// AST objects are never destructed; rather, all memory associated with the
358 /// AST objects will be released when the ASTContext itself is destroyed.
359 mutable llvm::BumpPtrAllocator BumpAlloc;
361 /// \brief Allocator for partial diagnostics.
362 PartialDiagnostic::StorageAllocator DiagAllocator;
364 /// \brief The current C++ ABI.
365 OwningPtr<CXXABI> ABI;
366 CXXABI *createCXXABI(const TargetInfo &T);
368 /// \brief The logical -> physical address space map.
369 const LangAS::Map *AddrSpaceMap;
371 friend class ASTDeclReader;
372 friend class ASTReader;
373 friend class ASTWriter;
374 friend class CXXRecordDecl;
376 const TargetInfo *Target;
377 clang::PrintingPolicy PrintingPolicy;
380 IdentifierTable &Idents;
381 SelectorTable &Selectors;
382 Builtin::Context &BuiltinInfo;
383 mutable DeclarationNameTable DeclarationNames;
384 OwningPtr<ExternalASTSource> ExternalSource;
385 ASTMutationListener *Listener;
387 /// \brief Contains parents of a node.
388 typedef llvm::SmallVector<ast_type_traits::DynTypedNode, 1> ParentVector;
390 /// \brief Maps from a node to its parents.
391 typedef llvm::DenseMap<const void *, ParentVector> ParentMap;
393 /// \brief Returns the parents of the given node.
395 /// Note that this will lazily compute the parents of all nodes
396 /// and store them for later retrieval. Thus, the first call is O(n)
397 /// in the number of AST nodes.
399 /// Caveats and FIXMEs:
400 /// Calculating the parent map over all AST nodes will need to load the
401 /// full AST. This can be undesirable in the case where the full AST is
402 /// expensive to create (for example, when using precompiled header
403 /// preambles). Thus, there are good opportunities for optimization here.
404 /// One idea is to walk the given node downwards, looking for references
405 /// to declaration contexts - once a declaration context is found, compute
406 /// the parent map for the declaration context; if that can satisfy the
407 /// request, loading the whole AST can be avoided. Note that this is made
408 /// more complex by statements in templates having multiple parents - those
409 /// problems can be solved by building closure over the templated parts of
410 /// the AST, which also avoids touching large parts of the AST.
411 /// Additionally, we will want to add an interface to already give a hint
412 /// where to search for the parents, for example when looking at a statement
413 /// inside a certain function.
415 /// 'NodeT' can be one of Decl, Stmt, Type, TypeLoc,
416 /// NestedNameSpecifier or NestedNameSpecifierLoc.
417 template <typename NodeT>
418 ParentVector getParents(const NodeT &Node) {
419 return getParents(ast_type_traits::DynTypedNode::create(Node));
422 ParentVector getParents(const ast_type_traits::DynTypedNode &Node) {
423 assert(Node.getMemoizationData() &&
424 "Invariant broken: only nodes that support memoization may be "
425 "used in the parent map.");
427 // We always need to run over the whole translation unit, as
428 // hasAncestor can escape any subtree.
430 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
432 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
433 if (I == AllParents->end()) {
434 return ParentVector();
439 const clang::PrintingPolicy &getPrintingPolicy() const {
440 return PrintingPolicy;
443 void setPrintingPolicy(const clang::PrintingPolicy &Policy) {
444 PrintingPolicy = Policy;
447 SourceManager& getSourceManager() { return SourceMgr; }
448 const SourceManager& getSourceManager() const { return SourceMgr; }
450 llvm::BumpPtrAllocator &getAllocator() const {
454 void *Allocate(unsigned Size, unsigned Align = 8) const {
455 return BumpAlloc.Allocate(Size, Align);
457 void Deallocate(void *Ptr) const { }
459 /// Return the total amount of physical memory allocated for representing
460 /// AST nodes and type information.
461 size_t getASTAllocatedMemory() const {
462 return BumpAlloc.getTotalMemory();
464 /// Return the total memory used for various side tables.
465 size_t getSideTableAllocatedMemory() const;
467 PartialDiagnostic::StorageAllocator &getDiagAllocator() {
468 return DiagAllocator;
471 const TargetInfo &getTargetInfo() const { return *Target; }
473 const LangOptions& getLangOpts() const { return LangOpts; }
475 DiagnosticsEngine &getDiagnostics() const;
477 FullSourceLoc getFullLoc(SourceLocation Loc) const {
478 return FullSourceLoc(Loc,SourceMgr);
481 /// \brief All comments in this translation unit.
482 RawCommentList Comments;
484 /// \brief True if comments are already loaded from ExternalASTSource.
485 mutable bool CommentsLoaded;
487 class RawCommentAndCacheFlags {
490 /// We searched for a comment attached to the particular declaration, but
496 /// We have found a comment attached to this particular declaration.
501 /// This declaration does not have an attached comment, and we have
502 /// searched the redeclaration chain.
504 /// If getRaw() == 0, the whole redeclaration chain does not have any
507 /// If getRaw() != 0, it is a comment propagated from other
512 Kind getKind() const LLVM_READONLY {
513 return Data.getInt();
516 void setKind(Kind K) {
520 const RawComment *getRaw() const LLVM_READONLY {
521 return Data.getPointer();
524 void setRaw(const RawComment *RC) {
528 const Decl *getOriginalDecl() const LLVM_READONLY {
532 void setOriginalDecl(const Decl *Orig) {
537 llvm::PointerIntPair<const RawComment *, 2, Kind> Data;
538 const Decl *OriginalDecl;
541 /// \brief Mapping from declarations to comments attached to any
544 /// Raw comments are owned by Comments list. This mapping is populated
546 mutable llvm::DenseMap<const Decl *, RawCommentAndCacheFlags> RedeclComments;
548 /// \brief Mapping from declarations to parsed comments attached to any
550 mutable llvm::DenseMap<const Decl *, comments::FullComment *> ParsedComments;
552 /// \brief Return the documentation comment attached to a given declaration,
553 /// without looking into cache.
554 RawComment *getRawCommentForDeclNoCache(const Decl *D) const;
557 RawCommentList &getRawCommentList() {
561 void addComment(const RawComment &RC) {
562 assert(LangOpts.RetainCommentsFromSystemHeaders ||
563 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
564 Comments.addComment(RC, BumpAlloc);
567 /// \brief Return the documentation comment attached to a given declaration.
568 /// Returns NULL if no comment is attached.
570 /// \param OriginalDecl if not NULL, is set to declaration AST node that had
571 /// the comment, if the comment we found comes from a redeclaration.
572 const RawComment *getRawCommentForAnyRedecl(
574 const Decl **OriginalDecl = NULL) const;
576 /// Return parsed documentation comment attached to a given declaration.
577 /// Returns NULL if no comment is attached.
579 /// \param PP the Preprocessor used with this TU. Could be NULL if
580 /// preprocessor is not available.
581 comments::FullComment *getCommentForDecl(const Decl *D,
582 const Preprocessor *PP) const;
584 comments::FullComment *cloneFullComment(comments::FullComment *FC,
585 const Decl *D) const;
588 mutable comments::CommandTraits CommentCommandTraits;
591 comments::CommandTraits &getCommentCommandTraits() const {
592 return CommentCommandTraits;
595 /// \brief Retrieve the attributes for the given declaration.
596 AttrVec& getDeclAttrs(const Decl *D);
598 /// \brief Erase the attributes corresponding to the given declaration.
599 void eraseDeclAttrs(const Decl *D);
601 /// \brief If this variable is an instantiated static data member of a
602 /// class template specialization, returns the templated static data member
603 /// from which it was instantiated.
604 MemberSpecializationInfo *getInstantiatedFromStaticDataMember(
607 FunctionDecl *getClassScopeSpecializationPattern(const FunctionDecl *FD);
609 void setClassScopeSpecializationPattern(FunctionDecl *FD,
610 FunctionDecl *Pattern);
612 /// \brief Note that the static data member \p Inst is an instantiation of
613 /// the static data member template \p Tmpl of a class template.
614 void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
615 TemplateSpecializationKind TSK,
616 SourceLocation PointOfInstantiation = SourceLocation());
618 /// \brief If the given using decl \p Inst is an instantiation of a
619 /// (possibly unresolved) using decl from a template instantiation,
621 NamedDecl *getInstantiatedFromUsingDecl(UsingDecl *Inst);
623 /// \brief Remember that the using decl \p Inst is an instantiation
624 /// of the using decl \p Pattern of a class template.
625 void setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern);
627 void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
628 UsingShadowDecl *Pattern);
629 UsingShadowDecl *getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst);
631 FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field);
633 void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl);
635 /// \brief Return \c true if \p FD is a zero-length bitfield which follows
636 /// the non-bitfield \p LastFD.
637 bool ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
638 const FieldDecl *LastFD) const;
640 /// \brief Return \c true if \p FD is a zero-length bitfield which follows
641 /// the bitfield \p LastFD.
642 bool ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
643 const FieldDecl *LastFD) const;
645 /// \brief Return \c true if \p FD is a bitfield which follows the bitfield
647 bool BitfieldFollowsBitfield(const FieldDecl *FD,
648 const FieldDecl *LastFD) const;
650 /// \brief Return \c true if \p FD is not a bitfield which follows the
651 /// bitfield \p LastFD.
652 bool NonBitfieldFollowsBitfield(const FieldDecl *FD,
653 const FieldDecl *LastFD) const;
655 /// \brief Return \c true if \p FD is a bitfield which follows the
656 /// non-bitfield \p LastFD.
657 bool BitfieldFollowsNonBitfield(const FieldDecl *FD,
658 const FieldDecl *LastFD) const;
660 // Access to the set of methods overridden by the given C++ method.
661 typedef CXXMethodVector::const_iterator overridden_cxx_method_iterator;
662 overridden_cxx_method_iterator
663 overridden_methods_begin(const CXXMethodDecl *Method) const;
665 overridden_cxx_method_iterator
666 overridden_methods_end(const CXXMethodDecl *Method) const;
668 unsigned overridden_methods_size(const CXXMethodDecl *Method) const;
670 /// \brief Note that the given C++ \p Method overrides the given \p
671 /// Overridden method.
672 void addOverriddenMethod(const CXXMethodDecl *Method,
673 const CXXMethodDecl *Overridden);
675 /// \brief Return C++ or ObjC overridden methods for the given \p Method.
677 /// An ObjC method is considered to override any method in the class's
678 /// base classes, its protocols, or its categories' protocols, that has
679 /// the same selector and is of the same kind (class or instance).
680 /// A method in an implementation is not considered as overriding the same
681 /// method in the interface or its categories.
682 void getOverriddenMethods(
683 const NamedDecl *Method,
684 SmallVectorImpl<const NamedDecl *> &Overridden) const;
686 /// \brief Notify the AST context that a new import declaration has been
687 /// parsed or implicitly created within this translation unit.
688 void addedLocalImportDecl(ImportDecl *Import);
690 static ImportDecl *getNextLocalImport(ImportDecl *Import) {
691 return Import->NextLocalImport;
694 /// \brief Iterator that visits import declarations.
695 class import_iterator {
699 typedef ImportDecl *value_type;
700 typedef ImportDecl *reference;
701 typedef ImportDecl *pointer;
702 typedef int difference_type;
703 typedef std::forward_iterator_tag iterator_category;
705 import_iterator() : Import() { }
706 explicit import_iterator(ImportDecl *Import) : Import(Import) { }
708 reference operator*() const { return Import; }
709 pointer operator->() const { return Import; }
711 import_iterator &operator++() {
712 Import = ASTContext::getNextLocalImport(Import);
716 import_iterator operator++(int) {
717 import_iterator Other(*this);
722 friend bool operator==(import_iterator X, import_iterator Y) {
723 return X.Import == Y.Import;
726 friend bool operator!=(import_iterator X, import_iterator Y) {
727 return X.Import != Y.Import;
731 import_iterator local_import_begin() const {
732 return import_iterator(FirstLocalImport);
734 import_iterator local_import_end() const { return import_iterator(); }
736 TranslationUnitDecl *getTranslationUnitDecl() const { return TUDecl; }
743 CanQualType WCharTy; // [C++ 3.9.1p5], integer type in C99.
744 CanQualType WIntTy; // [C99 7.24.1], integer type unchanged by default promotions.
745 CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99.
746 CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99.
747 CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty;
748 CanQualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy;
749 CanQualType UnsignedLongLongTy, UnsignedInt128Ty;
750 CanQualType FloatTy, DoubleTy, LongDoubleTy;
751 CanQualType HalfTy; // [OpenCL 6.1.1.1], ARM NEON
752 CanQualType FloatComplexTy, DoubleComplexTy, LongDoubleComplexTy;
753 CanQualType VoidPtrTy, NullPtrTy;
754 CanQualType DependentTy, OverloadTy, BoundMemberTy, UnknownAnyTy;
755 CanQualType BuiltinFnTy;
756 CanQualType PseudoObjectTy, ARCUnbridgedCastTy;
757 CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy;
758 CanQualType ObjCBuiltinBoolTy;
759 CanQualType OCLImage1dTy, OCLImage1dArrayTy, OCLImage1dBufferTy;
760 CanQualType OCLImage2dTy, OCLImage2dArrayTy;
761 CanQualType OCLImage3dTy;
762 CanQualType OCLSamplerTy, OCLEventTy;
764 // Types for deductions in C++0x [stmt.ranged]'s desugaring. Built on demand.
765 mutable QualType AutoDeductTy; // Deduction against 'auto'.
766 mutable QualType AutoRRefDeductTy; // Deduction against 'auto &&'.
768 // Type used to help define __builtin_va_list for some targets.
769 // The type is built when constructing 'BuiltinVaListDecl'.
770 mutable QualType VaListTagTy;
772 ASTContext(LangOptions& LOpts, SourceManager &SM, const TargetInfo *t,
773 IdentifierTable &idents, SelectorTable &sels,
774 Builtin::Context &builtins,
775 unsigned size_reserve,
776 bool DelayInitialization = false);
780 /// \brief Attach an external AST source to the AST context.
782 /// The external AST source provides the ability to load parts of
783 /// the abstract syntax tree as needed from some external storage,
784 /// e.g., a precompiled header.
785 void setExternalSource(OwningPtr<ExternalASTSource> &Source);
787 /// \brief Retrieve a pointer to the external AST source associated
788 /// with this AST context, if any.
789 ExternalASTSource *getExternalSource() const { return ExternalSource.get(); }
791 /// \brief Attach an AST mutation listener to the AST context.
793 /// The AST mutation listener provides the ability to track modifications to
794 /// the abstract syntax tree entities committed after they were initially
796 void setASTMutationListener(ASTMutationListener *Listener) {
797 this->Listener = Listener;
800 /// \brief Retrieve a pointer to the AST mutation listener associated
801 /// with this AST context, if any.
802 ASTMutationListener *getASTMutationListener() const { return Listener; }
804 void PrintStats() const;
805 const SmallVectorImpl<Type *>& getTypes() const { return Types; }
807 /// \brief Retrieve the declaration for the 128-bit signed integer type.
808 TypedefDecl *getInt128Decl() const;
810 /// \brief Retrieve the declaration for the 128-bit unsigned integer type.
811 TypedefDecl *getUInt128Decl() const;
813 //===--------------------------------------------------------------------===//
815 //===--------------------------------------------------------------------===//
818 /// \brief Return a type with extended qualifiers.
819 QualType getExtQualType(const Type *Base, Qualifiers Quals) const;
821 QualType getTypeDeclTypeSlow(const TypeDecl *Decl) const;
824 /// \brief Return the uniqued reference to the type for an address space
825 /// qualified type with the specified type and address space.
827 /// The resulting type has a union of the qualifiers from T and the address
828 /// space. If T already has an address space specifier, it is silently
830 QualType getAddrSpaceQualType(QualType T, unsigned AddressSpace) const;
832 /// \brief Return the uniqued reference to the type for an Objective-C
833 /// gc-qualified type.
835 /// The retulting type has a union of the qualifiers from T and the gc
837 QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const;
839 /// \brief Return the uniqued reference to the type for a \c restrict
842 /// The resulting type has a union of the qualifiers from \p T and
844 QualType getRestrictType(QualType T) const {
845 return T.withFastQualifiers(Qualifiers::Restrict);
848 /// \brief Return the uniqued reference to the type for a \c volatile
851 /// The resulting type has a union of the qualifiers from \p T and
853 QualType getVolatileType(QualType T) const {
854 return T.withFastQualifiers(Qualifiers::Volatile);
857 /// \brief Return the uniqued reference to the type for a \c const
860 /// The resulting type has a union of the qualifiers from \p T and \c const.
862 /// It can be reasonably expected that this will always be equivalent to
863 /// calling T.withConst().
864 QualType getConstType(QualType T) const { return T.withConst(); }
866 /// \brief Change the ExtInfo on a function type.
867 const FunctionType *adjustFunctionType(const FunctionType *Fn,
868 FunctionType::ExtInfo EInfo);
870 /// \brief Change the result type of a function type once it is deduced.
871 void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType);
873 /// \brief Return the uniqued reference to the type for a complex
874 /// number with the specified element type.
875 QualType getComplexType(QualType T) const;
876 CanQualType getComplexType(CanQualType T) const {
877 return CanQualType::CreateUnsafe(getComplexType((QualType) T));
880 /// \brief Return the uniqued reference to the type for a pointer to
881 /// the specified type.
882 QualType getPointerType(QualType T) const;
883 CanQualType getPointerType(CanQualType T) const {
884 return CanQualType::CreateUnsafe(getPointerType((QualType) T));
887 /// \brief Return the uniqued reference to the atomic type for the specified
889 QualType getAtomicType(QualType T) const;
891 /// \brief Return the uniqued reference to the type for a block of the
893 QualType getBlockPointerType(QualType T) const;
895 /// Gets the struct used to keep track of the descriptor for pointer to
897 QualType getBlockDescriptorType() const;
899 /// Gets the struct used to keep track of the extended descriptor for
900 /// pointer to blocks.
901 QualType getBlockDescriptorExtendedType() const;
903 void setcudaConfigureCallDecl(FunctionDecl *FD) {
904 cudaConfigureCallDecl = FD;
906 FunctionDecl *getcudaConfigureCallDecl() {
907 return cudaConfigureCallDecl;
910 /// Returns true iff we need copy/dispose helpers for the given type.
911 bool BlockRequiresCopying(QualType Ty, const VarDecl *D);
914 /// Returns true, if given type has a known lifetime. HasByrefExtendedLayout is set
915 /// to false in this case. If HasByrefExtendedLayout returns true, byref variable
916 /// has extended lifetime.
917 bool getByrefLifetime(QualType Ty,
918 Qualifiers::ObjCLifetime &Lifetime,
919 bool &HasByrefExtendedLayout) const;
921 /// \brief Return the uniqued reference to the type for an lvalue reference
922 /// to the specified type.
923 QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true)
926 /// \brief Return the uniqued reference to the type for an rvalue reference
927 /// to the specified type.
928 QualType getRValueReferenceType(QualType T) const;
930 /// \brief Return the uniqued reference to the type for a member pointer to
931 /// the specified type in the specified class.
933 /// The class \p Cls is a \c Type because it could be a dependent name.
934 QualType getMemberPointerType(QualType T, const Type *Cls) const;
936 /// \brief Return a non-unique reference to the type for a variable array of
937 /// the specified element type.
938 QualType getVariableArrayType(QualType EltTy, Expr *NumElts,
939 ArrayType::ArraySizeModifier ASM,
940 unsigned IndexTypeQuals,
941 SourceRange Brackets) const;
943 /// \brief Return a non-unique reference to the type for a dependently-sized
944 /// array of the specified element type.
946 /// FIXME: We will need these to be uniqued, or at least comparable, at some
948 QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
949 ArrayType::ArraySizeModifier ASM,
950 unsigned IndexTypeQuals,
951 SourceRange Brackets) const;
953 /// \brief Return a unique reference to the type for an incomplete array of
954 /// the specified element type.
955 QualType getIncompleteArrayType(QualType EltTy,
956 ArrayType::ArraySizeModifier ASM,
957 unsigned IndexTypeQuals) const;
959 /// \brief Return the unique reference to the type for a constant array of
960 /// the specified element type.
961 QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize,
962 ArrayType::ArraySizeModifier ASM,
963 unsigned IndexTypeQuals) const;
965 /// \brief Returns a vla type where known sizes are replaced with [*].
966 QualType getVariableArrayDecayedType(QualType Ty) const;
968 /// \brief Return the unique reference to a vector type of the specified
969 /// element type and size.
971 /// \pre \p VectorType must be a built-in type.
972 QualType getVectorType(QualType VectorType, unsigned NumElts,
973 VectorType::VectorKind VecKind) const;
975 /// \brief Return the unique reference to an extended vector type
976 /// of the specified element type and size.
978 /// \pre \p VectorType must be a built-in type.
979 QualType getExtVectorType(QualType VectorType, unsigned NumElts) const;
981 /// \pre Return a non-unique reference to the type for a dependently-sized
982 /// vector of the specified element type.
984 /// FIXME: We will need these to be uniqued, or at least comparable, at some
986 QualType getDependentSizedExtVectorType(QualType VectorType,
988 SourceLocation AttrLoc) const;
990 /// \brief Return a K&R style C function type like 'int()'.
991 QualType getFunctionNoProtoType(QualType ResultTy,
992 const FunctionType::ExtInfo &Info) const;
994 QualType getFunctionNoProtoType(QualType ResultTy) const {
995 return getFunctionNoProtoType(ResultTy, FunctionType::ExtInfo());
998 /// \brief Return a normal function type with a typed argument list.
999 QualType getFunctionType(QualType ResultTy, ArrayRef<QualType> Args,
1000 const FunctionProtoType::ExtProtoInfo &EPI) const;
1002 /// \brief Return the unique reference to the type for the specified type
1004 QualType getTypeDeclType(const TypeDecl *Decl,
1005 const TypeDecl *PrevDecl = 0) const {
1006 assert(Decl && "Passed null for Decl param");
1007 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1010 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
1011 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1012 return QualType(PrevDecl->TypeForDecl, 0);
1015 return getTypeDeclTypeSlow(Decl);
1018 /// \brief Return the unique reference to the type for the specified
1019 /// typedef-name decl.
1020 QualType getTypedefType(const TypedefNameDecl *Decl,
1021 QualType Canon = QualType()) const;
1023 QualType getRecordType(const RecordDecl *Decl) const;
1025 QualType getEnumType(const EnumDecl *Decl) const;
1027 QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const;
1029 QualType getAttributedType(AttributedType::Kind attrKind,
1030 QualType modifiedType,
1031 QualType equivalentType);
1033 QualType getSubstTemplateTypeParmType(const TemplateTypeParmType *Replaced,
1034 QualType Replacement) const;
1035 QualType getSubstTemplateTypeParmPackType(
1036 const TemplateTypeParmType *Replaced,
1037 const TemplateArgument &ArgPack);
1039 QualType getTemplateTypeParmType(unsigned Depth, unsigned Index,
1041 TemplateTypeParmDecl *ParmDecl = 0) const;
1043 QualType getTemplateSpecializationType(TemplateName T,
1044 const TemplateArgument *Args,
1046 QualType Canon = QualType()) const;
1048 QualType getCanonicalTemplateSpecializationType(TemplateName T,
1049 const TemplateArgument *Args,
1050 unsigned NumArgs) const;
1052 QualType getTemplateSpecializationType(TemplateName T,
1053 const TemplateArgumentListInfo &Args,
1054 QualType Canon = QualType()) const;
1057 getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc,
1058 const TemplateArgumentListInfo &Args,
1059 QualType Canon = QualType()) const;
1061 QualType getParenType(QualType NamedType) const;
1063 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1064 NestedNameSpecifier *NNS,
1065 QualType NamedType) const;
1066 QualType getDependentNameType(ElaboratedTypeKeyword Keyword,
1067 NestedNameSpecifier *NNS,
1068 const IdentifierInfo *Name,
1069 QualType Canon = QualType()) const;
1071 QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
1072 NestedNameSpecifier *NNS,
1073 const IdentifierInfo *Name,
1074 const TemplateArgumentListInfo &Args) const;
1075 QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
1076 NestedNameSpecifier *NNS,
1077 const IdentifierInfo *Name,
1079 const TemplateArgument *Args) const;
1081 QualType getPackExpansionType(QualType Pattern,
1082 Optional<unsigned> NumExpansions);
1084 QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
1085 ObjCInterfaceDecl *PrevDecl = 0) const;
1087 QualType getObjCObjectType(QualType Base,
1088 ObjCProtocolDecl * const *Protocols,
1089 unsigned NumProtocols) const;
1091 /// \brief Return a ObjCObjectPointerType type for the given ObjCObjectType.
1092 QualType getObjCObjectPointerType(QualType OIT) const;
1094 /// \brief GCC extension.
1095 QualType getTypeOfExprType(Expr *e) const;
1096 QualType getTypeOfType(QualType t) const;
1098 /// \brief C++11 decltype.
1099 QualType getDecltypeType(Expr *e, QualType UnderlyingType) const;
1101 /// \brief Unary type transforms
1102 QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
1103 UnaryTransformType::UTTKind UKind) const;
1105 /// \brief C++11 deduced auto type.
1106 QualType getAutoType(QualType DeducedType, bool IsDecltypeAuto,
1107 bool IsDependent = false) const;
1109 /// \brief C++11 deduction pattern for 'auto' type.
1110 QualType getAutoDeductType() const;
1112 /// \brief C++11 deduction pattern for 'auto &&' type.
1113 QualType getAutoRRefDeductType() const;
1115 /// \brief Return the unique reference to the type for the specified TagDecl
1116 /// (struct/union/class/enum) decl.
1117 QualType getTagDeclType(const TagDecl *Decl) const;
1119 /// \brief Return the unique type for "size_t" (C99 7.17), defined in
1122 /// The sizeof operator requires this (C99 6.5.3.4p4).
1123 CanQualType getSizeType() const;
1125 /// \brief Return the unique type for "intmax_t" (C99 7.18.1.5), defined in
1127 CanQualType getIntMaxType() const;
1129 /// \brief Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in
1131 CanQualType getUIntMaxType() const;
1133 /// \brief In C++, this returns the unique wchar_t type. In C99, this
1134 /// returns a type compatible with the type defined in <stddef.h> as defined
1136 QualType getWCharType() const { return WCharTy; }
1138 /// \brief Return the type of "signed wchar_t".
1140 /// Used when in C++, as a GCC extension.
1141 QualType getSignedWCharType() const;
1143 /// \brief Return the type of "unsigned wchar_t".
1145 /// Used when in C++, as a GCC extension.
1146 QualType getUnsignedWCharType() const;
1148 /// \brief In C99, this returns a type compatible with the type
1149 /// defined in <stddef.h> as defined by the target.
1150 QualType getWIntType() const { return WIntTy; }
1152 /// \brief Return a type compatible with "intptr_t" (C99 7.18.1.4),
1153 /// as defined by the target.
1154 QualType getIntPtrType() const;
1156 /// \brief Return a type compatible with "uintptr_t" (C99 7.18.1.4),
1157 /// as defined by the target.
1158 QualType getUIntPtrType() const;
1160 /// \brief Return the unique type for "ptrdiff_t" (C99 7.17) defined in
1161 /// <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1162 QualType getPointerDiffType() const;
1164 /// \brief Return the unique type for "pid_t" defined in
1165 /// <sys/types.h>. We need this to compute the correct type for vfork().
1166 QualType getProcessIDType() const;
1168 /// \brief Return the C structure type used to represent constant CFStrings.
1169 QualType getCFConstantStringType() const;
1171 /// \brief Returns the C struct type for objc_super
1172 QualType getObjCSuperType() const;
1173 void setObjCSuperType(QualType ST) { ObjCSuperType = ST; }
1175 /// Get the structure type used to representation CFStrings, or NULL
1176 /// if it hasn't yet been built.
1177 QualType getRawCFConstantStringType() const {
1178 if (CFConstantStringTypeDecl)
1179 return getTagDeclType(CFConstantStringTypeDecl);
1182 void setCFConstantStringType(QualType T);
1184 // This setter/getter represents the ObjC type for an NSConstantString.
1185 void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl);
1186 QualType getObjCConstantStringInterface() const {
1187 return ObjCConstantStringType;
1190 QualType getObjCNSStringType() const {
1191 return ObjCNSStringType;
1194 void setObjCNSStringType(QualType T) {
1195 ObjCNSStringType = T;
1198 /// \brief Retrieve the type that \c id has been defined to, which may be
1199 /// different from the built-in \c id if \c id has been typedef'd.
1200 QualType getObjCIdRedefinitionType() const {
1201 if (ObjCIdRedefinitionType.isNull())
1202 return getObjCIdType();
1203 return ObjCIdRedefinitionType;
1206 /// \brief Set the user-written type that redefines \c id.
1207 void setObjCIdRedefinitionType(QualType RedefType) {
1208 ObjCIdRedefinitionType = RedefType;
1211 /// \brief Retrieve the type that \c Class has been defined to, which may be
1212 /// different from the built-in \c Class if \c Class has been typedef'd.
1213 QualType getObjCClassRedefinitionType() const {
1214 if (ObjCClassRedefinitionType.isNull())
1215 return getObjCClassType();
1216 return ObjCClassRedefinitionType;
1219 /// \brief Set the user-written type that redefines 'SEL'.
1220 void setObjCClassRedefinitionType(QualType RedefType) {
1221 ObjCClassRedefinitionType = RedefType;
1224 /// \brief Retrieve the type that 'SEL' has been defined to, which may be
1225 /// different from the built-in 'SEL' if 'SEL' has been typedef'd.
1226 QualType getObjCSelRedefinitionType() const {
1227 if (ObjCSelRedefinitionType.isNull())
1228 return getObjCSelType();
1229 return ObjCSelRedefinitionType;
1233 /// \brief Set the user-written type that redefines 'SEL'.
1234 void setObjCSelRedefinitionType(QualType RedefType) {
1235 ObjCSelRedefinitionType = RedefType;
1238 /// \brief Retrieve the Objective-C "instancetype" type, if already known;
1239 /// otherwise, returns a NULL type;
1240 QualType getObjCInstanceType() {
1241 return getTypeDeclType(getObjCInstanceTypeDecl());
1244 /// \brief Retrieve the typedef declaration corresponding to the Objective-C
1245 /// "instancetype" type.
1246 TypedefDecl *getObjCInstanceTypeDecl();
1248 /// \brief Set the type for the C FILE type.
1249 void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; }
1251 /// \brief Retrieve the C FILE type.
1252 QualType getFILEType() const {
1254 return getTypeDeclType(FILEDecl);
1258 /// \brief Set the type for the C jmp_buf type.
1259 void setjmp_bufDecl(TypeDecl *jmp_bufDecl) {
1260 this->jmp_bufDecl = jmp_bufDecl;
1263 /// \brief Retrieve the C jmp_buf type.
1264 QualType getjmp_bufType() const {
1266 return getTypeDeclType(jmp_bufDecl);
1270 /// \brief Set the type for the C sigjmp_buf type.
1271 void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) {
1272 this->sigjmp_bufDecl = sigjmp_bufDecl;
1275 /// \brief Retrieve the C sigjmp_buf type.
1276 QualType getsigjmp_bufType() const {
1278 return getTypeDeclType(sigjmp_bufDecl);
1282 /// \brief Set the type for the C ucontext_t type.
1283 void setucontext_tDecl(TypeDecl *ucontext_tDecl) {
1284 this->ucontext_tDecl = ucontext_tDecl;
1287 /// \brief Retrieve the C ucontext_t type.
1288 QualType getucontext_tType() const {
1290 return getTypeDeclType(ucontext_tDecl);
1294 /// \brief The result type of logical operations, '<', '>', '!=', etc.
1295 QualType getLogicalOperationType() const {
1296 return getLangOpts().CPlusPlus ? BoolTy : IntTy;
1299 /// \brief Emit the Objective-CC type encoding for the given type \p T into
1302 /// If \p Field is specified then record field names are also encoded.
1303 void getObjCEncodingForType(QualType T, std::string &S,
1304 const FieldDecl *Field=0) const;
1306 void getLegacyIntegralTypeEncoding(QualType &t) const;
1308 /// \brief Put the string version of the type qualifiers \p QT into \p S.
1309 void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
1310 std::string &S) const;
1312 /// \brief Emit the encoded type for the function \p Decl into \p S.
1314 /// This is in the same format as Objective-C method encodings.
1316 /// \returns true if an error occurred (e.g., because one of the parameter
1317 /// types is incomplete), false otherwise.
1318 bool getObjCEncodingForFunctionDecl(const FunctionDecl *Decl, std::string& S);
1320 /// \brief Emit the encoded type for the method declaration \p Decl into
1323 /// \returns true if an error occurred (e.g., because one of the parameter
1324 /// types is incomplete), false otherwise.
1325 bool getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, std::string &S,
1326 bool Extended = false)
1329 /// \brief Return the encoded type for this block declaration.
1330 std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const;
1332 /// getObjCEncodingForPropertyDecl - Return the encoded type for
1333 /// this method declaration. If non-NULL, Container must be either
1334 /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
1335 /// only be NULL when getting encodings for protocol properties.
1336 void getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
1337 const Decl *Container,
1338 std::string &S) const;
1340 bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
1341 ObjCProtocolDecl *rProto) const;
1343 /// \brief Return the size of type \p T for Objective-C encoding purpose,
1345 CharUnits getObjCEncodingTypeSize(QualType T) const;
1347 /// \brief Retrieve the typedef corresponding to the predefined \c id type
1349 TypedefDecl *getObjCIdDecl() const;
1351 /// \brief Represents the Objective-CC \c id type.
1353 /// This is set up lazily, by Sema. \c id is always a (typedef for a)
1354 /// pointer type, a pointer to a struct.
1355 QualType getObjCIdType() const {
1356 return getTypeDeclType(getObjCIdDecl());
1359 /// \brief Retrieve the typedef corresponding to the predefined 'SEL' type
1361 TypedefDecl *getObjCSelDecl() const;
1363 /// \brief Retrieve the type that corresponds to the predefined Objective-C
1365 QualType getObjCSelType() const {
1366 return getTypeDeclType(getObjCSelDecl());
1369 /// \brief Retrieve the typedef declaration corresponding to the predefined
1370 /// Objective-C 'Class' type.
1371 TypedefDecl *getObjCClassDecl() const;
1373 /// \brief Represents the Objective-C \c Class type.
1375 /// This is set up lazily, by Sema. \c Class is always a (typedef for a)
1376 /// pointer type, a pointer to a struct.
1377 QualType getObjCClassType() const {
1378 return getTypeDeclType(getObjCClassDecl());
1381 /// \brief Retrieve the Objective-C class declaration corresponding to
1382 /// the predefined \c Protocol class.
1383 ObjCInterfaceDecl *getObjCProtocolDecl() const;
1385 /// \brief Retrieve declaration of 'BOOL' typedef
1386 TypedefDecl *getBOOLDecl() const {
1390 /// \brief Save declaration of 'BOOL' typedef
1391 void setBOOLDecl(TypedefDecl *TD) {
1395 /// \brief type of 'BOOL' type.
1396 QualType getBOOLType() const {
1397 return getTypeDeclType(getBOOLDecl());
1400 /// \brief Retrieve the type of the Objective-C \c Protocol class.
1401 QualType getObjCProtoType() const {
1402 return getObjCInterfaceType(getObjCProtocolDecl());
1405 /// \brief Retrieve the C type declaration corresponding to the predefined
1406 /// \c __builtin_va_list type.
1407 TypedefDecl *getBuiltinVaListDecl() const;
1409 /// \brief Retrieve the type of the \c __builtin_va_list type.
1410 QualType getBuiltinVaListType() const {
1411 return getTypeDeclType(getBuiltinVaListDecl());
1414 /// \brief Retrieve the C type declaration corresponding to the predefined
1415 /// \c __va_list_tag type used to help define the \c __builtin_va_list type
1416 /// for some targets.
1417 QualType getVaListTagType() const;
1419 /// \brief Return a type with additional \c const, \c volatile, or
1420 /// \c restrict qualifiers.
1421 QualType getCVRQualifiedType(QualType T, unsigned CVR) const {
1422 return getQualifiedType(T, Qualifiers::fromCVRMask(CVR));
1425 /// \brief Un-split a SplitQualType.
1426 QualType getQualifiedType(SplitQualType split) const {
1427 return getQualifiedType(split.Ty, split.Quals);
1430 /// \brief Return a type with additional qualifiers.
1431 QualType getQualifiedType(QualType T, Qualifiers Qs) const {
1432 if (!Qs.hasNonFastQualifiers())
1433 return T.withFastQualifiers(Qs.getFastQualifiers());
1434 QualifierCollector Qc(Qs);
1435 const Type *Ptr = Qc.strip(T);
1436 return getExtQualType(Ptr, Qc);
1439 /// \brief Return a type with additional qualifiers.
1440 QualType getQualifiedType(const Type *T, Qualifiers Qs) const {
1441 if (!Qs.hasNonFastQualifiers())
1442 return QualType(T, Qs.getFastQualifiers());
1443 return getExtQualType(T, Qs);
1446 /// \brief Return a type with the given lifetime qualifier.
1448 /// \pre Neither type.ObjCLifetime() nor \p lifetime may be \c OCL_None.
1449 QualType getLifetimeQualifiedType(QualType type,
1450 Qualifiers::ObjCLifetime lifetime) {
1451 assert(type.getObjCLifetime() == Qualifiers::OCL_None);
1452 assert(lifetime != Qualifiers::OCL_None);
1455 qs.addObjCLifetime(lifetime);
1456 return getQualifiedType(type, qs);
1459 /// getUnqualifiedObjCPointerType - Returns version of
1460 /// Objective-C pointer type with lifetime qualifier removed.
1461 QualType getUnqualifiedObjCPointerType(QualType type) const {
1462 if (!type.getTypePtr()->isObjCObjectPointerType() ||
1463 !type.getQualifiers().hasObjCLifetime())
1465 Qualifiers Qs = type.getQualifiers();
1466 Qs.removeObjCLifetime();
1467 return getQualifiedType(type.getUnqualifiedType(), Qs);
1470 DeclarationNameInfo getNameForTemplate(TemplateName Name,
1471 SourceLocation NameLoc) const;
1473 TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin,
1474 UnresolvedSetIterator End) const;
1476 TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
1477 bool TemplateKeyword,
1478 TemplateDecl *Template) const;
1480 TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1481 const IdentifierInfo *Name) const;
1482 TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1483 OverloadedOperatorKind Operator) const;
1484 TemplateName getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
1485 TemplateName replacement) const;
1486 TemplateName getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
1487 const TemplateArgument &ArgPack) const;
1489 enum GetBuiltinTypeError {
1490 GE_None, ///< No error
1491 GE_Missing_stdio, ///< Missing a type from <stdio.h>
1492 GE_Missing_setjmp, ///< Missing a type from <setjmp.h>
1493 GE_Missing_ucontext ///< Missing a type from <ucontext.h>
1496 /// \brief Return the type for the specified builtin.
1498 /// If \p IntegerConstantArgs is non-null, it is filled in with a bitmask of
1499 /// arguments to the builtin that are required to be integer constant
1501 QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error,
1502 unsigned *IntegerConstantArgs = 0) const;
1505 CanQualType getFromTargetType(unsigned Type) const;
1506 std::pair<uint64_t, unsigned> getTypeInfoImpl(const Type *T) const;
1508 //===--------------------------------------------------------------------===//
1510 //===--------------------------------------------------------------------===//
1513 /// \brief Return one of the GCNone, Weak or Strong Objective-C garbage
1514 /// collection attributes.
1515 Qualifiers::GC getObjCGCAttrKind(QualType Ty) const;
1517 /// \brief Return true if the given vector types are of the same unqualified
1518 /// type or if they are equivalent to the same GCC vector type.
1520 /// \note This ignores whether they are target-specific (AltiVec or Neon)
1522 bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec);
1524 /// \brief Return true if this is an \c NSObject object with its \c NSObject
1526 static bool isObjCNSObjectType(QualType Ty) {
1527 return Ty->isObjCNSObjectType();
1530 //===--------------------------------------------------------------------===//
1531 // Type Sizing and Analysis
1532 //===--------------------------------------------------------------------===//
1534 /// \brief Return the APFloat 'semantics' for the specified scalar floating
1536 const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
1538 /// \brief Get the size and alignment of the specified complete type in bits.
1539 std::pair<uint64_t, unsigned> getTypeInfo(const Type *T) const;
1540 std::pair<uint64_t, unsigned> getTypeInfo(QualType T) const {
1541 return getTypeInfo(T.getTypePtr());
1544 /// \brief Return the size of the specified (complete) type \p T, in bits.
1545 uint64_t getTypeSize(QualType T) const {
1546 return getTypeInfo(T).first;
1548 uint64_t getTypeSize(const Type *T) const {
1549 return getTypeInfo(T).first;
1552 /// \brief Return the size of the character type, in bits.
1553 uint64_t getCharWidth() const {
1554 return getTypeSize(CharTy);
1557 /// \brief Convert a size in bits to a size in characters.
1558 CharUnits toCharUnitsFromBits(int64_t BitSize) const;
1560 /// \brief Convert a size in characters to a size in bits.
1561 int64_t toBits(CharUnits CharSize) const;
1563 /// \brief Return the size of the specified (complete) type \p T, in
1565 CharUnits getTypeSizeInChars(QualType T) const;
1566 CharUnits getTypeSizeInChars(const Type *T) const;
1568 /// \brief Return the ABI-specified alignment of a (complete) type \p T, in
1570 unsigned getTypeAlign(QualType T) const {
1571 return getTypeInfo(T).second;
1573 unsigned getTypeAlign(const Type *T) const {
1574 return getTypeInfo(T).second;
1577 /// \brief Return the ABI-specified alignment of a (complete) type \p T, in
1579 CharUnits getTypeAlignInChars(QualType T) const;
1580 CharUnits getTypeAlignInChars(const Type *T) const;
1582 // getTypeInfoDataSizeInChars - Return the size of a type, in chars. If the
1583 // type is a record, its data size is returned.
1584 std::pair<CharUnits, CharUnits> getTypeInfoDataSizeInChars(QualType T) const;
1586 std::pair<CharUnits, CharUnits> getTypeInfoInChars(const Type *T) const;
1587 std::pair<CharUnits, CharUnits> getTypeInfoInChars(QualType T) const;
1589 /// \brief Return the "preferred" alignment of the specified type \p T for
1590 /// the current target, in bits.
1592 /// This can be different than the ABI alignment in cases where it is
1593 /// beneficial for performance to overalign a data type.
1594 unsigned getPreferredTypeAlign(const Type *T) const;
1596 /// \brief Return the alignment in bits that should be given to a
1597 /// global variable with type \p T.
1598 unsigned getAlignOfGlobalVar(QualType T) const;
1600 /// \brief Return the alignment in characters that should be given to a
1601 /// global variable with type \p T.
1602 CharUnits getAlignOfGlobalVarInChars(QualType T) const;
1604 /// \brief Return a conservative estimate of the alignment of the specified
1607 /// \pre \p D must not be a bitfield type, as bitfields do not have a valid
1610 /// If \p RefAsPointee, references are treated like their underlying type
1611 /// (for alignof), else they're treated like pointers (for CodeGen).
1612 CharUnits getDeclAlign(const Decl *D, bool RefAsPointee = false) const;
1614 /// \brief Get or compute information about the layout of the specified
1615 /// record (struct/union/class) \p D, which indicates its size and field
1616 /// position information.
1617 const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D) const;
1619 /// \brief Get or compute information about the layout of the specified
1620 /// Objective-C interface.
1621 const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D)
1624 void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS,
1625 bool Simple = false) const;
1627 /// \brief Get or compute information about the layout of the specified
1628 /// Objective-C implementation.
1630 /// This may differ from the interface if synthesized ivars are present.
1631 const ASTRecordLayout &
1632 getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const;
1634 /// \brief Get our current best idea for the key function of the
1635 /// given record decl, or NULL if there isn't one.
1637 /// The key function is, according to the Itanium C++ ABI section 5.2.3:
1638 /// ...the first non-pure virtual function that is not inline at the
1639 /// point of class definition.
1641 /// Other ABIs use the same idea. However, the ARM C++ ABI ignores
1642 /// virtual functions that are defined 'inline', which means that
1643 /// the result of this computation can change.
1644 const CXXMethodDecl *getCurrentKeyFunction(const CXXRecordDecl *RD);
1646 /// \brief Observe that the given method cannot be a key function.
1647 /// Checks the key-function cache for the method's class and clears it
1648 /// if matches the given declaration.
1650 /// This is used in ABIs where out-of-line definitions marked
1651 /// inline are not considered to be key functions.
1653 /// \param method should be the declaration from the class definition
1654 void setNonKeyFunction(const CXXMethodDecl *method);
1656 /// Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
1657 uint64_t getFieldOffset(const ValueDecl *FD) const;
1659 bool isNearlyEmpty(const CXXRecordDecl *RD) const;
1661 MangleContext *createMangleContext();
1663 void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass,
1664 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const;
1666 unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const;
1667 void CollectInheritedProtocols(const Decl *CDecl,
1668 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols);
1670 //===--------------------------------------------------------------------===//
1672 //===--------------------------------------------------------------------===//
1674 /// \brief Return the canonical (structural) type corresponding to the
1675 /// specified potentially non-canonical type \p T.
1677 /// The non-canonical version of a type may have many "decorated" versions of
1678 /// types. Decorators can include typedefs, 'typeof' operators, etc. The
1679 /// returned type is guaranteed to be free of any of these, allowing two
1680 /// canonical types to be compared for exact equality with a simple pointer
1682 CanQualType getCanonicalType(QualType T) const {
1683 return CanQualType::CreateUnsafe(T.getCanonicalType());
1686 const Type *getCanonicalType(const Type *T) const {
1687 return T->getCanonicalTypeInternal().getTypePtr();
1690 /// \brief Return the canonical parameter type corresponding to the specific
1691 /// potentially non-canonical one.
1693 /// Qualifiers are stripped off, functions are turned into function
1694 /// pointers, and arrays decay one level into pointers.
1695 CanQualType getCanonicalParamType(QualType T) const;
1697 /// \brief Determine whether the given types \p T1 and \p T2 are equivalent.
1698 bool hasSameType(QualType T1, QualType T2) const {
1699 return getCanonicalType(T1) == getCanonicalType(T2);
1702 /// \brief Return this type as a completely-unqualified array type,
1703 /// capturing the qualifiers in \p Quals.
1705 /// This will remove the minimal amount of sugaring from the types, similar
1706 /// to the behavior of QualType::getUnqualifiedType().
1708 /// \param T is the qualified type, which may be an ArrayType
1710 /// \param Quals will receive the full set of qualifiers that were
1711 /// applied to the array.
1713 /// \returns if this is an array type, the completely unqualified array type
1714 /// that corresponds to it. Otherwise, returns T.getUnqualifiedType().
1715 QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals);
1717 /// \brief Determine whether the given types are equivalent after
1718 /// cvr-qualifiers have been removed.
1719 bool hasSameUnqualifiedType(QualType T1, QualType T2) const {
1720 return getCanonicalType(T1).getTypePtr() ==
1721 getCanonicalType(T2).getTypePtr();
1724 bool UnwrapSimilarPointerTypes(QualType &T1, QualType &T2);
1726 /// \brief Retrieves the "canonical" nested name specifier for a
1727 /// given nested name specifier.
1729 /// The canonical nested name specifier is a nested name specifier
1730 /// that uniquely identifies a type or namespace within the type
1731 /// system. For example, given:
1736 /// template<typename T> struct X { typename T* type; };
1740 /// template<typename T> struct Y {
1741 /// typename N::S::X<T>::type member;
1745 /// Here, the nested-name-specifier for N::S::X<T>:: will be
1746 /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined
1747 /// by declarations in the type system and the canonical type for
1748 /// the template type parameter 'T' is template-param-0-0.
1749 NestedNameSpecifier *
1750 getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const;
1752 /// \brief Retrieves the default calling convention to use for
1753 /// C++ instance methods.
1754 CallingConv getDefaultCXXMethodCallConv(bool isVariadic);
1756 /// \brief Retrieves the canonical representation of the given
1757 /// calling convention.
1758 CallingConv getCanonicalCallConv(CallingConv CC) const;
1760 /// \brief Determines whether two calling conventions name the same
1761 /// calling convention.
1762 bool isSameCallConv(CallingConv lcc, CallingConv rcc) {
1763 return (getCanonicalCallConv(lcc) == getCanonicalCallConv(rcc));
1766 /// \brief Retrieves the "canonical" template name that refers to a
1769 /// The canonical template name is the simplest expression that can
1770 /// be used to refer to a given template. For most templates, this
1771 /// expression is just the template declaration itself. For example,
1772 /// the template std::vector can be referred to via a variety of
1773 /// names---std::vector, \::std::vector, vector (if vector is in
1774 /// scope), etc.---but all of these names map down to the same
1775 /// TemplateDecl, which is used to form the canonical template name.
1777 /// Dependent template names are more interesting. Here, the
1778 /// template name could be something like T::template apply or
1779 /// std::allocator<T>::template rebind, where the nested name
1780 /// specifier itself is dependent. In this case, the canonical
1781 /// template name uses the shortest form of the dependent
1782 /// nested-name-specifier, which itself contains all canonical
1783 /// types, values, and templates.
1784 TemplateName getCanonicalTemplateName(TemplateName Name) const;
1786 /// \brief Determine whether the given template names refer to the same
1788 bool hasSameTemplateName(TemplateName X, TemplateName Y);
1790 /// \brief Retrieve the "canonical" template argument.
1792 /// The canonical template argument is the simplest template argument
1793 /// (which may be a type, value, expression, or declaration) that
1794 /// expresses the value of the argument.
1795 TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg)
1798 /// Type Query functions. If the type is an instance of the specified class,
1799 /// return the Type pointer for the underlying maximally pretty type. This
1800 /// is a member of ASTContext because this may need to do some amount of
1801 /// canonicalization, e.g. to move type qualifiers into the element type.
1802 const ArrayType *getAsArrayType(QualType T) const;
1803 const ConstantArrayType *getAsConstantArrayType(QualType T) const {
1804 return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T));
1806 const VariableArrayType *getAsVariableArrayType(QualType T) const {
1807 return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T));
1809 const IncompleteArrayType *getAsIncompleteArrayType(QualType T) const {
1810 return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
1812 const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T)
1814 return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T));
1817 /// \brief Return the innermost element type of an array type.
1819 /// For example, will return "int" for int[m][n]
1820 QualType getBaseElementType(const ArrayType *VAT) const;
1822 /// \brief Return the innermost element type of a type (which needn't
1823 /// actually be an array type).
1824 QualType getBaseElementType(QualType QT) const;
1826 /// \brief Return number of constant array elements.
1827 uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const;
1829 /// \brief Perform adjustment on the parameter type of a function.
1831 /// This routine adjusts the given parameter type @p T to the actual
1832 /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
1833 /// C++ [dcl.fct]p3). The adjusted parameter type is returned.
1834 QualType getAdjustedParameterType(QualType T) const;
1836 /// \brief Retrieve the parameter type as adjusted for use in the signature
1837 /// of a function, decaying array and function types and removing top-level
1839 QualType getSignatureParameterType(QualType T) const;
1841 /// \brief Return the properly qualified result of decaying the specified
1842 /// array type to a pointer.
1844 /// This operation is non-trivial when handling typedefs etc. The canonical
1845 /// type of \p T must be an array type, this returns a pointer to a properly
1846 /// qualified element of the array.
1848 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
1849 QualType getArrayDecayedType(QualType T) const;
1851 /// \brief Return the type that \p PromotableType will promote to: C99
1852 /// 6.3.1.1p2, assuming that \p PromotableType is a promotable integer type.
1853 QualType getPromotedIntegerType(QualType PromotableType) const;
1855 /// \brief Recurses in pointer/array types until it finds an Objective-C
1856 /// retainable type and returns its ownership.
1857 Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const;
1859 /// \brief Whether this is a promotable bitfield reference according
1860 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
1862 /// \returns the type this bit-field will promote to, or NULL if no
1863 /// promotion occurs.
1864 QualType isPromotableBitField(Expr *E) const;
1866 /// \brief Return the highest ranked integer type, see C99 6.3.1.8p1.
1868 /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
1869 /// \p LHS < \p RHS, return -1.
1870 int getIntegerTypeOrder(QualType LHS, QualType RHS) const;
1872 /// \brief Compare the rank of the two specified floating point types,
1873 /// ignoring the domain of the type (i.e. 'double' == '_Complex double').
1875 /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
1876 /// \p LHS < \p RHS, return -1.
1877 int getFloatingTypeOrder(QualType LHS, QualType RHS) const;
1879 /// \brief Return a real floating point or a complex type (based on
1880 /// \p typeDomain/\p typeSize).
1882 /// \param typeDomain a real floating point or complex type.
1883 /// \param typeSize a real floating point or complex type.
1884 QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
1885 QualType typeDomain) const;
1887 unsigned getTargetAddressSpace(QualType T) const {
1888 return getTargetAddressSpace(T.getQualifiers());
1891 unsigned getTargetAddressSpace(Qualifiers Q) const {
1892 return getTargetAddressSpace(Q.getAddressSpace());
1895 unsigned getTargetAddressSpace(unsigned AS) const {
1896 if (AS < LangAS::Offset || AS >= LangAS::Offset + LangAS::Count)
1899 return (*AddrSpaceMap)[AS - LangAS::Offset];
1903 // Helper for integer ordering
1904 unsigned getIntegerRank(const Type *T) const;
1908 //===--------------------------------------------------------------------===//
1909 // Type Compatibility Predicates
1910 //===--------------------------------------------------------------------===//
1912 /// Compatibility predicates used to check assignment expressions.
1913 bool typesAreCompatible(QualType T1, QualType T2,
1914 bool CompareUnqualified = false); // C99 6.2.7p1
1916 bool propertyTypesAreCompatible(QualType, QualType);
1917 bool typesAreBlockPointerCompatible(QualType, QualType);
1919 bool isObjCIdType(QualType T) const {
1920 return T == getObjCIdType();
1922 bool isObjCClassType(QualType T) const {
1923 return T == getObjCClassType();
1925 bool isObjCSelType(QualType T) const {
1926 return T == getObjCSelType();
1928 bool QualifiedIdConformsQualifiedId(QualType LHS, QualType RHS);
1929 bool ObjCQualifiedIdTypesAreCompatible(QualType LHS, QualType RHS,
1932 bool ObjCQualifiedClassTypesAreCompatible(QualType LHS, QualType RHS);
1934 // Check the safety of assignment from LHS to RHS
1935 bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
1936 const ObjCObjectPointerType *RHSOPT);
1937 bool canAssignObjCInterfaces(const ObjCObjectType *LHS,
1938 const ObjCObjectType *RHS);
1939 bool canAssignObjCInterfacesInBlockPointer(
1940 const ObjCObjectPointerType *LHSOPT,
1941 const ObjCObjectPointerType *RHSOPT,
1942 bool BlockReturnType);
1943 bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
1944 QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT,
1945 const ObjCObjectPointerType *RHSOPT);
1946 bool canBindObjCObjectType(QualType To, QualType From);
1948 // Functions for calculating composite types
1949 QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false,
1950 bool Unqualified = false, bool BlockReturnType = false);
1951 QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false,
1952 bool Unqualified = false);
1953 QualType mergeFunctionArgumentTypes(QualType, QualType,
1954 bool OfBlockPointer=false,
1955 bool Unqualified = false);
1956 QualType mergeTransparentUnionType(QualType, QualType,
1957 bool OfBlockPointer=false,
1958 bool Unqualified = false);
1960 QualType mergeObjCGCQualifiers(QualType, QualType);
1962 bool FunctionTypesMatchOnNSConsumedAttrs(
1963 const FunctionProtoType *FromFunctionType,
1964 const FunctionProtoType *ToFunctionType);
1966 void ResetObjCLayout(const ObjCContainerDecl *CD) {
1967 ObjCLayouts[CD] = 0;
1970 //===--------------------------------------------------------------------===//
1971 // Integer Predicates
1972 //===--------------------------------------------------------------------===//
1974 // The width of an integer, as defined in C99 6.2.6.2. This is the number
1975 // of bits in an integer type excluding any padding bits.
1976 unsigned getIntWidth(QualType T) const;
1978 // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
1979 // unsigned integer type. This method takes a signed type, and returns the
1980 // corresponding unsigned integer type.
1981 QualType getCorrespondingUnsignedType(QualType T) const;
1983 //===--------------------------------------------------------------------===//
1985 //===--------------------------------------------------------------------===//
1987 typedef SmallVectorImpl<Type *>::iterator type_iterator;
1988 typedef SmallVectorImpl<Type *>::const_iterator const_type_iterator;
1990 type_iterator types_begin() { return Types.begin(); }
1991 type_iterator types_end() { return Types.end(); }
1992 const_type_iterator types_begin() const { return Types.begin(); }
1993 const_type_iterator types_end() const { return Types.end(); }
1995 //===--------------------------------------------------------------------===//
1997 //===--------------------------------------------------------------------===//
1999 /// \brief Make an APSInt of the appropriate width and signedness for the
2000 /// given \p Value and integer \p Type.
2001 llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const {
2002 llvm::APSInt Res(getIntWidth(Type),
2003 !Type->isSignedIntegerOrEnumerationType());
2008 bool isSentinelNullExpr(const Expr *E);
2010 /// \brief Get the implementation of the ObjCInterfaceDecl \p D, or NULL if
2012 ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D);
2013 /// \brief Get the implementation of the ObjCCategoryDecl \p D, or NULL if
2015 ObjCCategoryImplDecl *getObjCImplementation(ObjCCategoryDecl *D);
2017 /// \brief Return true if there is at least one \@implementation in the TU.
2018 bool AnyObjCImplementation() {
2019 return !ObjCImpls.empty();
2022 /// \brief Set the implementation of ObjCInterfaceDecl.
2023 void setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2024 ObjCImplementationDecl *ImplD);
2025 /// \brief Set the implementation of ObjCCategoryDecl.
2026 void setObjCImplementation(ObjCCategoryDecl *CatD,
2027 ObjCCategoryImplDecl *ImplD);
2029 /// \brief Get the duplicate declaration of a ObjCMethod in the same
2030 /// interface, or null if none exists.
2031 const ObjCMethodDecl *getObjCMethodRedeclaration(
2032 const ObjCMethodDecl *MD) const {
2033 return ObjCMethodRedecls.lookup(MD);
2036 void setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2037 const ObjCMethodDecl *Redecl) {
2038 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2039 ObjCMethodRedecls[MD] = Redecl;
2042 /// \brief Returns the Objective-C interface that \p ND belongs to if it is
2043 /// an Objective-C method/property/ivar etc. that is part of an interface,
2044 /// otherwise returns null.
2045 const ObjCInterfaceDecl *getObjContainingInterface(const NamedDecl *ND) const;
2047 /// \brief Set the copy inialization expression of a block var decl.
2048 void setBlockVarCopyInits(VarDecl*VD, Expr* Init);
2049 /// \brief Get the copy initialization expression of the VarDecl \p VD, or
2050 /// NULL if none exists.
2051 Expr *getBlockVarCopyInits(const VarDecl* VD);
2053 /// \brief Allocate an uninitialized TypeSourceInfo.
2055 /// The caller should initialize the memory held by TypeSourceInfo using
2056 /// the TypeLoc wrappers.
2058 /// \param T the type that will be the basis for type source info. This type
2059 /// should refer to how the declarator was written in source code, not to
2060 /// what type semantic analysis resolved the declarator to.
2062 /// \param Size the size of the type info to create, or 0 if the size
2063 /// should be calculated based on the type.
2064 TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0) const;
2066 /// \brief Allocate a TypeSourceInfo where all locations have been
2067 /// initialized to a given location, which defaults to the empty
2070 getTrivialTypeSourceInfo(QualType T,
2071 SourceLocation Loc = SourceLocation()) const;
2073 TypeSourceInfo *getNullTypeSourceInfo() { return &NullTypeSourceInfo; }
2075 /// \brief Add a deallocation callback that will be invoked when the
2076 /// ASTContext is destroyed.
2078 /// \param Callback A callback function that will be invoked on destruction.
2080 /// \param Data Pointer data that will be provided to the callback function
2081 /// when it is called.
2082 void AddDeallocation(void (*Callback)(void*), void *Data);
2084 GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD);
2085 GVALinkage GetGVALinkageForVariable(const VarDecl *VD);
2087 /// \brief Determines if the decl can be CodeGen'ed or deserialized from PCH
2088 /// lazily, only when used; this is only relevant for function or file scoped
2089 /// var definitions.
2091 /// \returns true if the function/var must be CodeGen'ed/deserialized even if
2093 bool DeclMustBeEmitted(const Decl *D);
2095 void addUnnamedTag(const TagDecl *Tag);
2096 int getUnnamedTagManglingNumber(const TagDecl *Tag) const;
2098 /// \brief Retrieve the lambda mangling number for a lambda expression.
2099 unsigned getLambdaManglingNumber(CXXMethodDecl *CallOperator);
2101 /// \brief Used by ParmVarDecl to store on the side the
2102 /// index of the parameter when it exceeds the size of the normal bitfield.
2103 void setParameterIndex(const ParmVarDecl *D, unsigned index);
2105 /// \brief Used by ParmVarDecl to retrieve on the side the
2106 /// index of the parameter when it exceeds the size of the normal bitfield.
2107 unsigned getParameterIndex(const ParmVarDecl *D) const;
2109 //===--------------------------------------------------------------------===//
2111 //===--------------------------------------------------------------------===//
2113 /// \brief The number of implicitly-declared default constructors.
2114 static unsigned NumImplicitDefaultConstructors;
2116 /// \brief The number of implicitly-declared default constructors for
2117 /// which declarations were built.
2118 static unsigned NumImplicitDefaultConstructorsDeclared;
2120 /// \brief The number of implicitly-declared copy constructors.
2121 static unsigned NumImplicitCopyConstructors;
2123 /// \brief The number of implicitly-declared copy constructors for
2124 /// which declarations were built.
2125 static unsigned NumImplicitCopyConstructorsDeclared;
2127 /// \brief The number of implicitly-declared move constructors.
2128 static unsigned NumImplicitMoveConstructors;
2130 /// \brief The number of implicitly-declared move constructors for
2131 /// which declarations were built.
2132 static unsigned NumImplicitMoveConstructorsDeclared;
2134 /// \brief The number of implicitly-declared copy assignment operators.
2135 static unsigned NumImplicitCopyAssignmentOperators;
2137 /// \brief The number of implicitly-declared copy assignment operators for
2138 /// which declarations were built.
2139 static unsigned NumImplicitCopyAssignmentOperatorsDeclared;
2141 /// \brief The number of implicitly-declared move assignment operators.
2142 static unsigned NumImplicitMoveAssignmentOperators;
2144 /// \brief The number of implicitly-declared move assignment operators for
2145 /// which declarations were built.
2146 static unsigned NumImplicitMoveAssignmentOperatorsDeclared;
2148 /// \brief The number of implicitly-declared destructors.
2149 static unsigned NumImplicitDestructors;
2151 /// \brief The number of implicitly-declared destructors for which
2152 /// declarations were built.
2153 static unsigned NumImplicitDestructorsDeclared;
2156 ASTContext(const ASTContext &) LLVM_DELETED_FUNCTION;
2157 void operator=(const ASTContext &) LLVM_DELETED_FUNCTION;
2160 /// \brief Initialize built-in types.
2162 /// This routine may only be invoked once for a given ASTContext object.
2163 /// It is normally invoked by the ASTContext constructor. However, the
2164 /// constructor can be asked to delay initialization, which places the burden
2165 /// of calling this function on the user of that object.
2167 /// \param Target The target
2168 void InitBuiltinTypes(const TargetInfo &Target);
2171 void InitBuiltinType(CanQualType &R, BuiltinType::Kind K);
2173 // Return the Objective-C type encoding for a given type.
2174 void getObjCEncodingForTypeImpl(QualType t, std::string &S,
2175 bool ExpandPointedToStructures,
2176 bool ExpandStructures,
2177 const FieldDecl *Field,
2178 bool OutermostType = false,
2179 bool EncodingProperty = false,
2180 bool StructField = false,
2181 bool EncodeBlockParameters = false,
2182 bool EncodeClassNames = false,
2183 bool EncodePointerToObjCTypedef = false) const;
2185 // Adds the encoding of the structure's members.
2186 void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S,
2187 const FieldDecl *Field,
2188 bool includeVBases = true) const;
2190 // Adds the encoding of a method parameter or return type.
2191 void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
2192 QualType T, std::string& S,
2193 bool Extended) const;
2195 const ASTRecordLayout &
2196 getObjCLayout(const ObjCInterfaceDecl *D,
2197 const ObjCImplementationDecl *Impl) const;
2200 /// \brief A set of deallocations that should be performed when the
2201 /// ASTContext is destroyed.
2202 SmallVector<std::pair<void (*)(void*), void *>, 16> Deallocations;
2204 // FIXME: This currently contains the set of StoredDeclMaps used
2205 // by DeclContext objects. This probably should not be in ASTContext,
2206 // but we include it here so that ASTContext can quickly deallocate them.
2207 llvm::PointerIntPair<StoredDeclsMap*,1> LastSDM;
2209 /// \brief A counter used to uniquely identify "blocks".
2210 mutable unsigned int UniqueBlockByRefTypeID;
2212 friend class DeclContext;
2213 friend class DeclarationNameTable;
2214 void ReleaseDeclContextMaps();
2216 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
2217 /// parents as defined by the \c RecursiveASTVisitor.
2219 /// Note that the relationship described here is purely in terms of AST
2220 /// traversal - there are other relationships (for example declaration context)
2221 /// in the AST that are better modeled by special matchers.
2223 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
2224 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
2226 /// \brief Builds and returns the translation unit's parent map.
2228 /// The caller takes ownership of the returned \c ParentMap.
2229 static ParentMap *buildMap(TranslationUnitDecl &TU) {
2230 ParentMapASTVisitor Visitor(new ParentMap);
2231 Visitor.TraverseDecl(&TU);
2232 return Visitor.Parents;
2236 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
2238 ParentMapASTVisitor(ParentMap *Parents) : Parents(Parents) {
2241 bool shouldVisitTemplateInstantiations() const {
2244 bool shouldVisitImplicitCode() const {
2247 // Disables data recursion. We intercept Traverse* methods in the RAV, which
2248 // are not triggered during data recursion.
2249 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
2253 template <typename T>
2254 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
2257 if (ParentStack.size() > 0)
2258 // FIXME: Currently we add the same parent multiple times, for example
2259 // when we visit all subexpressions of template instantiations; this is
2260 // suboptimal, bug benign: the only way to visit those is with
2261 // hasAncestor / hasParent, and those do not create new matches.
2262 // The plan is to enable DynTypedNode to be storable in a map or hash
2263 // map. The main problem there is to implement hash functions /
2264 // comparison operators for all types that DynTypedNode supports that
2265 // do not have pointer identity.
2266 (*Parents)[Node].push_back(ParentStack.back());
2267 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
2268 bool Result = (this ->* traverse) (Node);
2269 ParentStack.pop_back();
2273 bool TraverseDecl(Decl *DeclNode) {
2274 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
2277 bool TraverseStmt(Stmt *StmtNode) {
2278 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
2282 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
2284 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
2287 llvm::OwningPtr<ParentMap> AllParents;
2290 /// \brief Utility function for constructing a nullary selector.
2291 static inline Selector GetNullarySelector(StringRef name, ASTContext& Ctx) {
2292 IdentifierInfo* II = &Ctx.Idents.get(name);
2293 return Ctx.Selectors.getSelector(0, &II);
2296 /// \brief Utility function for constructing an unary selector.
2297 static inline Selector GetUnarySelector(StringRef name, ASTContext& Ctx) {
2298 IdentifierInfo* II = &Ctx.Idents.get(name);
2299 return Ctx.Selectors.getSelector(1, &II);
2302 } // end namespace clang
2304 // operator new and delete aren't allowed inside namespaces.
2306 /// @brief Placement new for using the ASTContext's allocator.
2308 /// This placement form of operator new uses the ASTContext's allocator for
2309 /// obtaining memory.
2311 /// IMPORTANT: These are also declared in clang/AST/AttrIterator.h! Any changes
2312 /// here need to also be made there.
2314 /// We intentionally avoid using a nothrow specification here so that the calls
2315 /// to this operator will not perform a null check on the result -- the
2316 /// underlying allocator never returns null pointers.
2318 /// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
2320 /// // Default alignment (8)
2321 /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
2322 /// // Specific alignment
2323 /// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
2325 /// Please note that you cannot use delete on the pointer; it must be
2326 /// deallocated using an explicit destructor call followed by
2327 /// @c Context.Deallocate(Ptr).
2329 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
2330 /// @param C The ASTContext that provides the allocator.
2331 /// @param Alignment The alignment of the allocated memory (if the underlying
2332 /// allocator supports it).
2333 /// @return The allocated memory. Could be NULL.
2334 inline void *operator new(size_t Bytes, const clang::ASTContext &C,
2336 return C.Allocate(Bytes, Alignment);
2338 /// @brief Placement delete companion to the new above.
2340 /// This operator is just a companion to the new above. There is no way of
2341 /// invoking it directly; see the new operator for more details. This operator
2342 /// is called implicitly by the compiler if a placement new expression using
2343 /// the ASTContext throws in the object constructor.
2344 inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t) {
2348 /// This placement form of operator new[] uses the ASTContext's allocator for
2349 /// obtaining memory.
2351 /// We intentionally avoid using a nothrow specification here so that the calls
2352 /// to this operator will not perform a null check on the result -- the
2353 /// underlying allocator never returns null pointers.
2355 /// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
2357 /// // Default alignment (8)
2358 /// char *data = new (Context) char[10];
2359 /// // Specific alignment
2360 /// char *data = new (Context, 4) char[10];
2362 /// Please note that you cannot use delete on the pointer; it must be
2363 /// deallocated using an explicit destructor call followed by
2364 /// @c Context.Deallocate(Ptr).
2366 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
2367 /// @param C The ASTContext that provides the allocator.
2368 /// @param Alignment The alignment of the allocated memory (if the underlying
2369 /// allocator supports it).
2370 /// @return The allocated memory. Could be NULL.
2371 inline void *operator new[](size_t Bytes, const clang::ASTContext& C,
2372 size_t Alignment = 8) {
2373 return C.Allocate(Bytes, Alignment);
2376 /// @brief Placement delete[] companion to the new[] above.
2378 /// This operator is just a companion to the new[] above. There is no way of
2379 /// invoking it directly; see the new[] operator for more details. This operator
2380 /// is called implicitly by the compiler if a placement new[] expression using
2381 /// the ASTContext throws in the object constructor.
2382 inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_t) {