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/ExternalASTSource.h"
23 #include "clang/AST/NestedNameSpecifier.h"
24 #include "clang/AST/PrettyPrinter.h"
25 #include "clang/AST/RawCommentList.h"
26 #include "clang/AST/TemplateName.h"
27 #include "clang/AST/Type.h"
28 #include "clang/Basic/AddressSpaces.h"
29 #include "clang/Basic/IdentifierTable.h"
30 #include "clang/Basic/LangOptions.h"
31 #include "clang/Basic/OperatorKinds.h"
32 #include "clang/Basic/PartialDiagnostic.h"
33 #include "clang/Basic/VersionTuple.h"
34 #include "llvm/ADT/DenseMap.h"
35 #include "llvm/ADT/FoldingSet.h"
36 #include "llvm/ADT/IntrusiveRefCntPtr.h"
37 #include "llvm/ADT/SmallPtrSet.h"
38 #include "llvm/ADT/TinyPtrVector.h"
39 #include "llvm/Support/Allocator.h"
50 class ASTRecordLayout;
53 class DiagnosticsEngine;
55 class ASTMutationListener;
56 class IdentifierTable;
57 class MaterializeTemporaryExpr;
61 class MangleNumberingContext;
65 class ObjCPropertyDecl;
66 class UnresolvedSetIterator;
68 class UsingShadowDecl;
69 class VTableContextBase;
71 namespace Builtin { class Context; }
77 /// \brief Holds long-lived AST nodes (such as types and decls) that can be
78 /// referred to throughout the semantic analysis of a file.
79 class ASTContext : public RefCountedBase<ASTContext> {
80 ASTContext &this_() { return *this; }
82 mutable SmallVector<Type *, 0> Types;
83 mutable llvm::FoldingSet<ExtQuals> ExtQualNodes;
84 mutable llvm::FoldingSet<ComplexType> ComplexTypes;
85 mutable llvm::FoldingSet<PointerType> PointerTypes;
86 mutable llvm::FoldingSet<AdjustedType> AdjustedTypes;
87 mutable llvm::FoldingSet<BlockPointerType> BlockPointerTypes;
88 mutable llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes;
89 mutable llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes;
90 mutable llvm::FoldingSet<MemberPointerType> MemberPointerTypes;
91 mutable llvm::FoldingSet<ConstantArrayType> ConstantArrayTypes;
92 mutable llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
93 mutable std::vector<VariableArrayType*> VariableArrayTypes;
94 mutable llvm::FoldingSet<DependentSizedArrayType> DependentSizedArrayTypes;
95 mutable llvm::FoldingSet<DependentSizedExtVectorType>
96 DependentSizedExtVectorTypes;
97 mutable llvm::FoldingSet<VectorType> VectorTypes;
98 mutable llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes;
99 mutable llvm::ContextualFoldingSet<FunctionProtoType, ASTContext&>
101 mutable llvm::FoldingSet<DependentTypeOfExprType> DependentTypeOfExprTypes;
102 mutable llvm::FoldingSet<DependentDecltypeType> DependentDecltypeTypes;
103 mutable llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes;
104 mutable llvm::FoldingSet<SubstTemplateTypeParmType>
105 SubstTemplateTypeParmTypes;
106 mutable llvm::FoldingSet<SubstTemplateTypeParmPackType>
107 SubstTemplateTypeParmPackTypes;
108 mutable llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&>
109 TemplateSpecializationTypes;
110 mutable llvm::FoldingSet<ParenType> ParenTypes;
111 mutable llvm::FoldingSet<ElaboratedType> ElaboratedTypes;
112 mutable llvm::FoldingSet<DependentNameType> DependentNameTypes;
113 mutable llvm::ContextualFoldingSet<DependentTemplateSpecializationType,
115 DependentTemplateSpecializationTypes;
116 llvm::FoldingSet<PackExpansionType> PackExpansionTypes;
117 mutable llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes;
118 mutable llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes;
119 mutable llvm::FoldingSet<AutoType> AutoTypes;
120 mutable llvm::FoldingSet<AtomicType> AtomicTypes;
121 llvm::FoldingSet<AttributedType> AttributedTypes;
123 mutable llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames;
124 mutable llvm::FoldingSet<DependentTemplateName> DependentTemplateNames;
125 mutable llvm::FoldingSet<SubstTemplateTemplateParmStorage>
126 SubstTemplateTemplateParms;
127 mutable llvm::ContextualFoldingSet<SubstTemplateTemplateParmPackStorage,
129 SubstTemplateTemplateParmPacks;
131 /// \brief The set of nested name specifiers.
133 /// This set is managed by the NestedNameSpecifier class.
134 mutable llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers;
135 mutable NestedNameSpecifier *GlobalNestedNameSpecifier;
136 friend class NestedNameSpecifier;
138 /// \brief A cache mapping from RecordDecls to ASTRecordLayouts.
140 /// This is lazily created. This is intentionally not serialized.
141 mutable llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>
143 mutable llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>
146 /// \brief A cache from types to size and alignment information.
147 typedef llvm::DenseMap<const Type*,
148 std::pair<uint64_t, unsigned> > TypeInfoMap;
149 mutable TypeInfoMap MemoizedTypeInfo;
151 /// \brief A cache mapping from CXXRecordDecls to key functions.
152 llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr> KeyFunctions;
154 /// \brief Mapping from ObjCContainers to their ObjCImplementations.
155 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls;
157 /// \brief Mapping from ObjCMethod to its duplicate declaration in the same
159 llvm::DenseMap<const ObjCMethodDecl*,const ObjCMethodDecl*> ObjCMethodRedecls;
161 /// \brief Mapping from __block VarDecls to their copy initialization expr.
162 llvm::DenseMap<const VarDecl*, Expr*> BlockVarCopyInits;
164 /// \brief Mapping from class scope functions specialization to their
165 /// template patterns.
166 llvm::DenseMap<const FunctionDecl*, FunctionDecl*>
167 ClassScopeSpecializationPattern;
169 /// \brief Mapping from materialized temporaries with static storage duration
170 /// that appear in constant initializers to their evaluated values.
171 llvm::DenseMap<const MaterializeTemporaryExpr*, APValue>
172 MaterializedTemporaryValues;
174 /// \brief Representation of a "canonical" template template parameter that
175 /// is used in canonical template names.
176 class CanonicalTemplateTemplateParm : public llvm::FoldingSetNode {
177 TemplateTemplateParmDecl *Parm;
180 CanonicalTemplateTemplateParm(TemplateTemplateParmDecl *Parm)
183 TemplateTemplateParmDecl *getParam() const { return Parm; }
185 void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, Parm); }
187 static void Profile(llvm::FoldingSetNodeID &ID,
188 TemplateTemplateParmDecl *Parm);
190 mutable llvm::FoldingSet<CanonicalTemplateTemplateParm>
191 CanonTemplateTemplateParms;
193 TemplateTemplateParmDecl *
194 getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const;
196 /// \brief The typedef for the __int128_t type.
197 mutable TypedefDecl *Int128Decl;
199 /// \brief The typedef for the __uint128_t type.
200 mutable TypedefDecl *UInt128Decl;
202 /// \brief The typedef for the __float128 stub type.
203 mutable TypeDecl *Float128StubDecl;
205 /// \brief The typedef for the target specific predefined
206 /// __builtin_va_list type.
207 mutable TypedefDecl *BuiltinVaListDecl;
209 /// \brief The typedef for the predefined \c id type.
210 mutable TypedefDecl *ObjCIdDecl;
212 /// \brief The typedef for the predefined \c SEL type.
213 mutable TypedefDecl *ObjCSelDecl;
215 /// \brief The typedef for the predefined \c Class type.
216 mutable TypedefDecl *ObjCClassDecl;
218 /// \brief The typedef for the predefined \c Protocol class in Objective-C.
219 mutable ObjCInterfaceDecl *ObjCProtocolClassDecl;
221 /// \brief The typedef for the predefined 'BOOL' type.
222 mutable TypedefDecl *BOOLDecl;
224 // Typedefs which may be provided defining the structure of Objective-C
226 QualType ObjCIdRedefinitionType;
227 QualType ObjCClassRedefinitionType;
228 QualType ObjCSelRedefinitionType;
230 QualType ObjCConstantStringType;
231 mutable RecordDecl *CFConstantStringTypeDecl;
233 mutable QualType ObjCSuperType;
235 QualType ObjCNSStringType;
237 /// \brief The typedef declaration for the Objective-C "instancetype" type.
238 TypedefDecl *ObjCInstanceTypeDecl;
240 /// \brief The type for the C FILE type.
243 /// \brief The type for the C jmp_buf type.
244 TypeDecl *jmp_bufDecl;
246 /// \brief The type for the C sigjmp_buf type.
247 TypeDecl *sigjmp_bufDecl;
249 /// \brief The type for the C ucontext_t type.
250 TypeDecl *ucontext_tDecl;
252 /// \brief Type for the Block descriptor for Blocks CodeGen.
254 /// Since this is only used for generation of debug info, it is not
256 mutable RecordDecl *BlockDescriptorType;
258 /// \brief Type for the Block descriptor for Blocks CodeGen.
260 /// Since this is only used for generation of debug info, it is not
262 mutable RecordDecl *BlockDescriptorExtendedType;
264 /// \brief Declaration for the CUDA cudaConfigureCall function.
265 FunctionDecl *cudaConfigureCallDecl;
267 TypeSourceInfo NullTypeSourceInfo;
269 /// \brief Keeps track of all declaration attributes.
271 /// Since so few decls have attrs, we keep them in a hash map instead of
272 /// wasting space in the Decl class.
273 llvm::DenseMap<const Decl*, AttrVec*> DeclAttrs;
275 /// \brief A mapping from non-redeclarable declarations in modules that were
276 /// merged with other declarations to the canonical declaration that they were
278 llvm::DenseMap<Decl*, Decl*> MergedDecls;
281 /// \brief A type synonym for the TemplateOrInstantiation mapping.
282 typedef llvm::PointerUnion<VarTemplateDecl *, MemberSpecializationInfo *>
283 TemplateOrSpecializationInfo;
287 /// \brief A mapping to contain the template or declaration that
288 /// a variable declaration describes or was instantiated from,
291 /// For non-templates, this value will be NULL. For variable
292 /// declarations that describe a variable template, this will be a
293 /// pointer to a VarTemplateDecl. For static data members
294 /// of class template specializations, this will be the
295 /// MemberSpecializationInfo referring to the member variable that was
296 /// instantiated or specialized. Thus, the mapping will keep track of
297 /// the static data member templates from which static data members of
298 /// class template specializations were instantiated.
300 /// Given the following example:
303 /// template<typename T>
308 /// template<typename T>
309 /// T X<T>::value = T(17);
311 /// int *x = &X<int>::value;
314 /// This mapping will contain an entry that maps from the VarDecl for
315 /// X<int>::value to the corresponding VarDecl for X<T>::value (within the
316 /// class template X) and will be marked TSK_ImplicitInstantiation.
317 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>
318 TemplateOrInstantiation;
320 /// \brief Keeps track of the declaration from which a UsingDecl was
321 /// created during instantiation.
323 /// The source declaration is always a UsingDecl, an UnresolvedUsingValueDecl,
324 /// or an UnresolvedUsingTypenameDecl.
328 /// template<typename T>
333 /// template<typename T>
334 /// struct B : A<T> {
338 /// template struct B<int>;
341 /// This mapping will contain an entry that maps from the UsingDecl in
342 /// B<int> to the UnresolvedUsingDecl in B<T>.
343 llvm::DenseMap<UsingDecl *, NamedDecl *> InstantiatedFromUsingDecl;
345 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>
346 InstantiatedFromUsingShadowDecl;
348 llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl;
350 /// \brief Mapping that stores the methods overridden by a given C++
353 /// Since most C++ member functions aren't virtual and therefore
354 /// don't override anything, we store the overridden functions in
355 /// this map on the side rather than within the CXXMethodDecl structure.
356 typedef llvm::TinyPtrVector<const CXXMethodDecl*> CXXMethodVector;
357 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector> OverriddenMethods;
359 /// \brief Mapping from each declaration context to its corresponding
360 /// mangling numbering context (used for constructs like lambdas which
361 /// need to be consistently numbered for the mangler).
362 llvm::DenseMap<const DeclContext *, MangleNumberingContext *>
363 MangleNumberingContexts;
365 /// \brief Side-table of mangling numbers for declarations which rarely
366 /// need them (like static local vars).
367 llvm::DenseMap<const NamedDecl *, unsigned> MangleNumbers;
368 llvm::DenseMap<const VarDecl *, unsigned> StaticLocalNumbers;
370 /// \brief Mapping that stores parameterIndex values for ParmVarDecls when
371 /// that value exceeds the bitfield size of ParmVarDeclBits.ParameterIndex.
372 typedef llvm::DenseMap<const VarDecl *, unsigned> ParameterIndexTable;
373 ParameterIndexTable ParamIndices;
375 ImportDecl *FirstLocalImport;
376 ImportDecl *LastLocalImport;
378 TranslationUnitDecl *TUDecl;
380 /// \brief The associated SourceManager object.a
381 SourceManager &SourceMgr;
383 /// \brief The language options used to create the AST associated with
384 /// this ASTContext object.
385 LangOptions &LangOpts;
387 /// \brief The allocator used to create AST objects.
389 /// AST objects are never destructed; rather, all memory associated with the
390 /// AST objects will be released when the ASTContext itself is destroyed.
391 mutable llvm::BumpPtrAllocator BumpAlloc;
393 /// \brief Allocator for partial diagnostics.
394 PartialDiagnostic::StorageAllocator DiagAllocator;
396 /// \brief The current C++ ABI.
397 std::unique_ptr<CXXABI> ABI;
398 CXXABI *createCXXABI(const TargetInfo &T);
400 /// \brief The logical -> physical address space map.
401 const LangAS::Map *AddrSpaceMap;
403 /// \brief Address space map mangling must be used with language specific
404 /// address spaces (e.g. OpenCL/CUDA)
405 bool AddrSpaceMapMangling;
407 friend class ASTDeclReader;
408 friend class ASTReader;
409 friend class ASTWriter;
410 friend class CXXRecordDecl;
412 const TargetInfo *Target;
413 clang::PrintingPolicy PrintingPolicy;
416 IdentifierTable &Idents;
417 SelectorTable &Selectors;
418 Builtin::Context &BuiltinInfo;
419 mutable DeclarationNameTable DeclarationNames;
420 IntrusiveRefCntPtr<ExternalASTSource> ExternalSource;
421 ASTMutationListener *Listener;
423 /// \brief Contains parents of a node.
424 typedef llvm::SmallVector<ast_type_traits::DynTypedNode, 2> ParentVector;
426 /// \brief Maps from a node to its parents.
427 typedef llvm::DenseMap<const void *,
428 llvm::PointerUnion<ast_type_traits::DynTypedNode *,
429 ParentVector *>> ParentMap;
431 /// \brief Returns the parents of the given node.
433 /// Note that this will lazily compute the parents of all nodes
434 /// and store them for later retrieval. Thus, the first call is O(n)
435 /// in the number of AST nodes.
437 /// Caveats and FIXMEs:
438 /// Calculating the parent map over all AST nodes will need to load the
439 /// full AST. This can be undesirable in the case where the full AST is
440 /// expensive to create (for example, when using precompiled header
441 /// preambles). Thus, there are good opportunities for optimization here.
442 /// One idea is to walk the given node downwards, looking for references
443 /// to declaration contexts - once a declaration context is found, compute
444 /// the parent map for the declaration context; if that can satisfy the
445 /// request, loading the whole AST can be avoided. Note that this is made
446 /// more complex by statements in templates having multiple parents - those
447 /// problems can be solved by building closure over the templated parts of
448 /// the AST, which also avoids touching large parts of the AST.
449 /// Additionally, we will want to add an interface to already give a hint
450 /// where to search for the parents, for example when looking at a statement
451 /// inside a certain function.
453 /// 'NodeT' can be one of Decl, Stmt, Type, TypeLoc,
454 /// NestedNameSpecifier or NestedNameSpecifierLoc.
455 template <typename NodeT>
456 ParentVector getParents(const NodeT &Node) {
457 return getParents(ast_type_traits::DynTypedNode::create(Node));
460 ParentVector getParents(const ast_type_traits::DynTypedNode &Node);
462 const clang::PrintingPolicy &getPrintingPolicy() const {
463 return PrintingPolicy;
466 void setPrintingPolicy(const clang::PrintingPolicy &Policy) {
467 PrintingPolicy = Policy;
470 SourceManager& getSourceManager() { return SourceMgr; }
471 const SourceManager& getSourceManager() const { return SourceMgr; }
473 llvm::BumpPtrAllocator &getAllocator() const {
477 void *Allocate(size_t Size, unsigned Align = 8) const {
478 return BumpAlloc.Allocate(Size, Align);
480 void Deallocate(void *Ptr) const { }
482 /// Return the total amount of physical memory allocated for representing
483 /// AST nodes and type information.
484 size_t getASTAllocatedMemory() const {
485 return BumpAlloc.getTotalMemory();
487 /// Return the total memory used for various side tables.
488 size_t getSideTableAllocatedMemory() const;
490 PartialDiagnostic::StorageAllocator &getDiagAllocator() {
491 return DiagAllocator;
494 const TargetInfo &getTargetInfo() const { return *Target; }
496 /// getIntTypeForBitwidth -
497 /// sets integer QualTy according to specified details:
498 /// bitwidth, signed/unsigned.
499 /// Returns empty type if there is no appropriate target types.
500 QualType getIntTypeForBitwidth(unsigned DestWidth,
501 unsigned Signed) const;
502 /// getRealTypeForBitwidth -
503 /// sets floating point QualTy according to specified bitwidth.
504 /// Returns empty type if there is no appropriate target types.
505 QualType getRealTypeForBitwidth(unsigned DestWidth) const;
507 bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const;
509 const LangOptions& getLangOpts() const { return LangOpts; }
511 DiagnosticsEngine &getDiagnostics() const;
513 FullSourceLoc getFullLoc(SourceLocation Loc) const {
514 return FullSourceLoc(Loc,SourceMgr);
517 /// \brief All comments in this translation unit.
518 RawCommentList Comments;
520 /// \brief True if comments are already loaded from ExternalASTSource.
521 mutable bool CommentsLoaded;
523 class RawCommentAndCacheFlags {
526 /// We searched for a comment attached to the particular declaration, but
532 /// We have found a comment attached to this particular declaration.
537 /// This declaration does not have an attached comment, and we have
538 /// searched the redeclaration chain.
540 /// If getRaw() == 0, the whole redeclaration chain does not have any
543 /// If getRaw() != 0, it is a comment propagated from other
548 Kind getKind() const LLVM_READONLY {
549 return Data.getInt();
552 void setKind(Kind K) {
556 const RawComment *getRaw() const LLVM_READONLY {
557 return Data.getPointer();
560 void setRaw(const RawComment *RC) {
564 const Decl *getOriginalDecl() const LLVM_READONLY {
568 void setOriginalDecl(const Decl *Orig) {
573 llvm::PointerIntPair<const RawComment *, 2, Kind> Data;
574 const Decl *OriginalDecl;
577 /// \brief Mapping from declarations to comments attached to any
580 /// Raw comments are owned by Comments list. This mapping is populated
582 mutable llvm::DenseMap<const Decl *, RawCommentAndCacheFlags> RedeclComments;
584 /// \brief Mapping from declarations to parsed comments attached to any
586 mutable llvm::DenseMap<const Decl *, comments::FullComment *> ParsedComments;
588 /// \brief Return the documentation comment attached to a given declaration,
589 /// without looking into cache.
590 RawComment *getRawCommentForDeclNoCache(const Decl *D) const;
593 RawCommentList &getRawCommentList() {
597 void addComment(const RawComment &RC) {
598 assert(LangOpts.RetainCommentsFromSystemHeaders ||
599 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
600 Comments.addComment(RC, BumpAlloc);
603 /// \brief Return the documentation comment attached to a given declaration.
604 /// Returns NULL if no comment is attached.
606 /// \param OriginalDecl if not NULL, is set to declaration AST node that had
607 /// the comment, if the comment we found comes from a redeclaration.
609 getRawCommentForAnyRedecl(const Decl *D,
610 const Decl **OriginalDecl = nullptr) const;
612 /// Return parsed documentation comment attached to a given declaration.
613 /// Returns NULL if no comment is attached.
615 /// \param PP the Preprocessor used with this TU. Could be NULL if
616 /// preprocessor is not available.
617 comments::FullComment *getCommentForDecl(const Decl *D,
618 const Preprocessor *PP) const;
620 /// Return parsed documentation comment attached to a given declaration.
621 /// Returns NULL if no comment is attached. Does not look at any
622 /// redeclarations of the declaration.
623 comments::FullComment *getLocalCommentForDeclUncached(const Decl *D) const;
625 comments::FullComment *cloneFullComment(comments::FullComment *FC,
626 const Decl *D) const;
629 mutable comments::CommandTraits CommentCommandTraits;
631 /// \brief Iterator that visits import declarations.
632 class import_iterator {
636 typedef ImportDecl *value_type;
637 typedef ImportDecl *reference;
638 typedef ImportDecl *pointer;
639 typedef int difference_type;
640 typedef std::forward_iterator_tag iterator_category;
642 import_iterator() : Import() {}
643 explicit import_iterator(ImportDecl *Import) : Import(Import) {}
645 reference operator*() const { return Import; }
646 pointer operator->() const { return Import; }
648 import_iterator &operator++() {
649 Import = ASTContext::getNextLocalImport(Import);
653 import_iterator operator++(int) {
654 import_iterator Other(*this);
659 friend bool operator==(import_iterator X, import_iterator Y) {
660 return X.Import == Y.Import;
663 friend bool operator!=(import_iterator X, import_iterator Y) {
664 return X.Import != Y.Import;
669 comments::CommandTraits &getCommentCommandTraits() const {
670 return CommentCommandTraits;
673 /// \brief Retrieve the attributes for the given declaration.
674 AttrVec& getDeclAttrs(const Decl *D);
676 /// \brief Erase the attributes corresponding to the given declaration.
677 void eraseDeclAttrs(const Decl *D);
679 /// \brief If this variable is an instantiated static data member of a
680 /// class template specialization, returns the templated static data member
681 /// from which it was instantiated.
683 MemberSpecializationInfo *getInstantiatedFromStaticDataMember(
686 TemplateOrSpecializationInfo
687 getTemplateOrSpecializationInfo(const VarDecl *Var);
689 FunctionDecl *getClassScopeSpecializationPattern(const FunctionDecl *FD);
691 void setClassScopeSpecializationPattern(FunctionDecl *FD,
692 FunctionDecl *Pattern);
694 /// \brief Note that the static data member \p Inst is an instantiation of
695 /// the static data member template \p Tmpl of a class template.
696 void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
697 TemplateSpecializationKind TSK,
698 SourceLocation PointOfInstantiation = SourceLocation());
700 void setTemplateOrSpecializationInfo(VarDecl *Inst,
701 TemplateOrSpecializationInfo TSI);
703 /// \brief If the given using decl \p Inst is an instantiation of a
704 /// (possibly unresolved) using decl from a template instantiation,
706 NamedDecl *getInstantiatedFromUsingDecl(UsingDecl *Inst);
708 /// \brief Remember that the using decl \p Inst is an instantiation
709 /// of the using decl \p Pattern of a class template.
710 void setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern);
712 void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
713 UsingShadowDecl *Pattern);
714 UsingShadowDecl *getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst);
716 FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field);
718 void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl);
720 // Access to the set of methods overridden by the given C++ method.
721 typedef CXXMethodVector::const_iterator overridden_cxx_method_iterator;
722 overridden_cxx_method_iterator
723 overridden_methods_begin(const CXXMethodDecl *Method) const;
725 overridden_cxx_method_iterator
726 overridden_methods_end(const CXXMethodDecl *Method) const;
728 unsigned overridden_methods_size(const CXXMethodDecl *Method) const;
730 /// \brief Note that the given C++ \p Method overrides the given \p
731 /// Overridden method.
732 void addOverriddenMethod(const CXXMethodDecl *Method,
733 const CXXMethodDecl *Overridden);
735 /// \brief Return C++ or ObjC overridden methods for the given \p Method.
737 /// An ObjC method is considered to override any method in the class's
738 /// base classes, its protocols, or its categories' protocols, that has
739 /// the same selector and is of the same kind (class or instance).
740 /// A method in an implementation is not considered as overriding the same
741 /// method in the interface or its categories.
742 void getOverriddenMethods(
743 const NamedDecl *Method,
744 SmallVectorImpl<const NamedDecl *> &Overridden) const;
746 /// \brief Notify the AST context that a new import declaration has been
747 /// parsed or implicitly created within this translation unit.
748 void addedLocalImportDecl(ImportDecl *Import);
750 static ImportDecl *getNextLocalImport(ImportDecl *Import) {
751 return Import->NextLocalImport;
754 typedef llvm::iterator_range<import_iterator> import_range;
755 import_range local_imports() const {
756 return import_range(import_iterator(FirstLocalImport), import_iterator());
759 Decl *getPrimaryMergedDecl(Decl *D) {
760 Decl *Result = MergedDecls.lookup(D);
761 return Result ? Result : D;
763 void setPrimaryMergedDecl(Decl *D, Decl *Primary) {
764 MergedDecls[D] = Primary;
767 TranslationUnitDecl *getTranslationUnitDecl() const { return TUDecl; }
774 CanQualType WCharTy; // [C++ 3.9.1p5].
775 CanQualType WideCharTy; // Same as WCharTy in C++, integer type in C99.
776 CanQualType WIntTy; // [C99 7.24.1], integer type unchanged by default promotions.
777 CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99.
778 CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99.
779 CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty;
780 CanQualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy;
781 CanQualType UnsignedLongLongTy, UnsignedInt128Ty;
782 CanQualType FloatTy, DoubleTy, LongDoubleTy;
783 CanQualType HalfTy; // [OpenCL 6.1.1.1], ARM NEON
784 CanQualType FloatComplexTy, DoubleComplexTy, LongDoubleComplexTy;
785 CanQualType VoidPtrTy, NullPtrTy;
786 CanQualType DependentTy, OverloadTy, BoundMemberTy, UnknownAnyTy;
787 CanQualType BuiltinFnTy;
788 CanQualType PseudoObjectTy, ARCUnbridgedCastTy;
789 CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy;
790 CanQualType ObjCBuiltinBoolTy;
791 CanQualType OCLImage1dTy, OCLImage1dArrayTy, OCLImage1dBufferTy;
792 CanQualType OCLImage2dTy, OCLImage2dArrayTy;
793 CanQualType OCLImage3dTy;
794 CanQualType OCLSamplerTy, OCLEventTy;
796 // Types for deductions in C++0x [stmt.ranged]'s desugaring. Built on demand.
797 mutable QualType AutoDeductTy; // Deduction against 'auto'.
798 mutable QualType AutoRRefDeductTy; // Deduction against 'auto &&'.
800 // Type used to help define __builtin_va_list for some targets.
801 // The type is built when constructing 'BuiltinVaListDecl'.
802 mutable QualType VaListTagTy;
804 ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents,
805 SelectorTable &sels, Builtin::Context &builtins);
809 /// \brief Attach an external AST source to the AST context.
811 /// The external AST source provides the ability to load parts of
812 /// the abstract syntax tree as needed from some external storage,
813 /// e.g., a precompiled header.
814 void setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source);
816 /// \brief Retrieve a pointer to the external AST source associated
817 /// with this AST context, if any.
818 ExternalASTSource *getExternalSource() const {
819 return ExternalSource.get();
822 /// \brief Attach an AST mutation listener to the AST context.
824 /// The AST mutation listener provides the ability to track modifications to
825 /// the abstract syntax tree entities committed after they were initially
827 void setASTMutationListener(ASTMutationListener *Listener) {
828 this->Listener = Listener;
831 /// \brief Retrieve a pointer to the AST mutation listener associated
832 /// with this AST context, if any.
833 ASTMutationListener *getASTMutationListener() const { return Listener; }
835 void PrintStats() const;
836 const SmallVectorImpl<Type *>& getTypes() const { return Types; }
838 /// \brief Create a new implicit TU-level CXXRecordDecl or RecordDecl
840 RecordDecl *buildImplicitRecord(StringRef Name,
841 RecordDecl::TagKind TK = TTK_Struct) const;
843 /// \brief Create a new implicit TU-level typedef declaration.
844 TypedefDecl *buildImplicitTypedef(QualType T, StringRef Name) const;
846 /// \brief Retrieve the declaration for the 128-bit signed integer type.
847 TypedefDecl *getInt128Decl() const;
849 /// \brief Retrieve the declaration for the 128-bit unsigned integer type.
850 TypedefDecl *getUInt128Decl() const;
852 /// \brief Retrieve the declaration for a 128-bit float stub type.
853 TypeDecl *getFloat128StubType() const;
855 //===--------------------------------------------------------------------===//
857 //===--------------------------------------------------------------------===//
860 /// \brief Return a type with extended qualifiers.
861 QualType getExtQualType(const Type *Base, Qualifiers Quals) const;
863 QualType getTypeDeclTypeSlow(const TypeDecl *Decl) const;
866 /// \brief Return the uniqued reference to the type for an address space
867 /// qualified type with the specified type and address space.
869 /// The resulting type has a union of the qualifiers from T and the address
870 /// space. If T already has an address space specifier, it is silently
872 QualType getAddrSpaceQualType(QualType T, unsigned AddressSpace) const;
874 /// \brief Return the uniqued reference to the type for an Objective-C
875 /// gc-qualified type.
877 /// The retulting type has a union of the qualifiers from T and the gc
879 QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const;
881 /// \brief Return the uniqued reference to the type for a \c restrict
884 /// The resulting type has a union of the qualifiers from \p T and
886 QualType getRestrictType(QualType T) const {
887 return T.withFastQualifiers(Qualifiers::Restrict);
890 /// \brief Return the uniqued reference to the type for a \c volatile
893 /// The resulting type has a union of the qualifiers from \p T and
895 QualType getVolatileType(QualType T) const {
896 return T.withFastQualifiers(Qualifiers::Volatile);
899 /// \brief Return the uniqued reference to the type for a \c const
902 /// The resulting type has a union of the qualifiers from \p T and \c const.
904 /// It can be reasonably expected that this will always be equivalent to
905 /// calling T.withConst().
906 QualType getConstType(QualType T) const { return T.withConst(); }
908 /// \brief Change the ExtInfo on a function type.
909 const FunctionType *adjustFunctionType(const FunctionType *Fn,
910 FunctionType::ExtInfo EInfo);
912 /// \brief Change the result type of a function type once it is deduced.
913 void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType);
915 /// \brief Return the uniqued reference to the type for a complex
916 /// number with the specified element type.
917 QualType getComplexType(QualType T) const;
918 CanQualType getComplexType(CanQualType T) const {
919 return CanQualType::CreateUnsafe(getComplexType((QualType) T));
922 /// \brief Return the uniqued reference to the type for a pointer to
923 /// the specified type.
924 QualType getPointerType(QualType T) const;
925 CanQualType getPointerType(CanQualType T) const {
926 return CanQualType::CreateUnsafe(getPointerType((QualType) T));
929 /// \brief Return the uniqued reference to a type adjusted from the original
930 /// type to a new type.
931 QualType getAdjustedType(QualType Orig, QualType New) const;
932 CanQualType getAdjustedType(CanQualType Orig, CanQualType New) const {
933 return CanQualType::CreateUnsafe(
934 getAdjustedType((QualType)Orig, (QualType)New));
937 /// \brief Return the uniqued reference to the decayed version of the given
938 /// type. Can only be called on array and function types which decay to
940 QualType getDecayedType(QualType T) const;
941 CanQualType getDecayedType(CanQualType T) const {
942 return CanQualType::CreateUnsafe(getDecayedType((QualType) T));
945 /// \brief Return the uniqued reference to the atomic type for the specified
947 QualType getAtomicType(QualType T) const;
949 /// \brief Return the uniqued reference to the type for a block of the
951 QualType getBlockPointerType(QualType T) const;
953 /// Gets the struct used to keep track of the descriptor for pointer to
955 QualType getBlockDescriptorType() const;
957 /// Gets the struct used to keep track of the extended descriptor for
958 /// pointer to blocks.
959 QualType getBlockDescriptorExtendedType() const;
961 void setcudaConfigureCallDecl(FunctionDecl *FD) {
962 cudaConfigureCallDecl = FD;
964 FunctionDecl *getcudaConfigureCallDecl() {
965 return cudaConfigureCallDecl;
968 /// Returns true iff we need copy/dispose helpers for the given type.
969 bool BlockRequiresCopying(QualType Ty, const VarDecl *D);
972 /// Returns true, if given type has a known lifetime. HasByrefExtendedLayout is set
973 /// to false in this case. If HasByrefExtendedLayout returns true, byref variable
974 /// has extended lifetime.
975 bool getByrefLifetime(QualType Ty,
976 Qualifiers::ObjCLifetime &Lifetime,
977 bool &HasByrefExtendedLayout) const;
979 /// \brief Return the uniqued reference to the type for an lvalue reference
980 /// to the specified type.
981 QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true)
984 /// \brief Return the uniqued reference to the type for an rvalue reference
985 /// to the specified type.
986 QualType getRValueReferenceType(QualType T) const;
988 /// \brief Return the uniqued reference to the type for a member pointer to
989 /// the specified type in the specified class.
991 /// The class \p Cls is a \c Type because it could be a dependent name.
992 QualType getMemberPointerType(QualType T, const Type *Cls) const;
994 /// \brief Return a non-unique reference to the type for a variable array of
995 /// the specified element type.
996 QualType getVariableArrayType(QualType EltTy, Expr *NumElts,
997 ArrayType::ArraySizeModifier ASM,
998 unsigned IndexTypeQuals,
999 SourceRange Brackets) const;
1001 /// \brief Return a non-unique reference to the type for a dependently-sized
1002 /// array of the specified element type.
1004 /// FIXME: We will need these to be uniqued, or at least comparable, at some
1006 QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
1007 ArrayType::ArraySizeModifier ASM,
1008 unsigned IndexTypeQuals,
1009 SourceRange Brackets) const;
1011 /// \brief Return a unique reference to the type for an incomplete array of
1012 /// the specified element type.
1013 QualType getIncompleteArrayType(QualType EltTy,
1014 ArrayType::ArraySizeModifier ASM,
1015 unsigned IndexTypeQuals) const;
1017 /// \brief Return the unique reference to the type for a constant array of
1018 /// the specified element type.
1019 QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize,
1020 ArrayType::ArraySizeModifier ASM,
1021 unsigned IndexTypeQuals) const;
1023 /// \brief Returns a vla type where known sizes are replaced with [*].
1024 QualType getVariableArrayDecayedType(QualType Ty) const;
1026 /// \brief Return the unique reference to a vector type of the specified
1027 /// element type and size.
1029 /// \pre \p VectorType must be a built-in type.
1030 QualType getVectorType(QualType VectorType, unsigned NumElts,
1031 VectorType::VectorKind VecKind) const;
1033 /// \brief Return the unique reference to an extended vector type
1034 /// of the specified element type and size.
1036 /// \pre \p VectorType must be a built-in type.
1037 QualType getExtVectorType(QualType VectorType, unsigned NumElts) const;
1039 /// \pre Return a non-unique reference to the type for a dependently-sized
1040 /// vector of the specified element type.
1042 /// FIXME: We will need these to be uniqued, or at least comparable, at some
1044 QualType getDependentSizedExtVectorType(QualType VectorType,
1046 SourceLocation AttrLoc) const;
1048 /// \brief Return a K&R style C function type like 'int()'.
1049 QualType getFunctionNoProtoType(QualType ResultTy,
1050 const FunctionType::ExtInfo &Info) const;
1052 QualType getFunctionNoProtoType(QualType ResultTy) const {
1053 return getFunctionNoProtoType(ResultTy, FunctionType::ExtInfo());
1056 /// \brief Return a normal function type with a typed argument list.
1057 QualType getFunctionType(QualType ResultTy, ArrayRef<QualType> Args,
1058 const FunctionProtoType::ExtProtoInfo &EPI) const;
1060 /// \brief Return the unique reference to the type for the specified type
1062 QualType getTypeDeclType(const TypeDecl *Decl,
1063 const TypeDecl *PrevDecl = nullptr) const {
1064 assert(Decl && "Passed null for Decl param");
1065 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1068 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
1069 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1070 return QualType(PrevDecl->TypeForDecl, 0);
1073 return getTypeDeclTypeSlow(Decl);
1076 /// \brief Return the unique reference to the type for the specified
1077 /// typedef-name decl.
1078 QualType getTypedefType(const TypedefNameDecl *Decl,
1079 QualType Canon = QualType()) const;
1081 QualType getRecordType(const RecordDecl *Decl) const;
1083 QualType getEnumType(const EnumDecl *Decl) const;
1085 QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const;
1087 QualType getAttributedType(AttributedType::Kind attrKind,
1088 QualType modifiedType,
1089 QualType equivalentType);
1091 QualType getSubstTemplateTypeParmType(const TemplateTypeParmType *Replaced,
1092 QualType Replacement) const;
1093 QualType getSubstTemplateTypeParmPackType(
1094 const TemplateTypeParmType *Replaced,
1095 const TemplateArgument &ArgPack);
1098 getTemplateTypeParmType(unsigned Depth, unsigned Index,
1100 TemplateTypeParmDecl *ParmDecl = nullptr) const;
1102 QualType getTemplateSpecializationType(TemplateName T,
1103 const TemplateArgument *Args,
1105 QualType Canon = QualType()) const;
1107 QualType getCanonicalTemplateSpecializationType(TemplateName T,
1108 const TemplateArgument *Args,
1109 unsigned NumArgs) const;
1111 QualType getTemplateSpecializationType(TemplateName T,
1112 const TemplateArgumentListInfo &Args,
1113 QualType Canon = QualType()) const;
1116 getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc,
1117 const TemplateArgumentListInfo &Args,
1118 QualType Canon = QualType()) const;
1120 QualType getParenType(QualType NamedType) const;
1122 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1123 NestedNameSpecifier *NNS,
1124 QualType NamedType) const;
1125 QualType getDependentNameType(ElaboratedTypeKeyword Keyword,
1126 NestedNameSpecifier *NNS,
1127 const IdentifierInfo *Name,
1128 QualType Canon = QualType()) const;
1130 QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
1131 NestedNameSpecifier *NNS,
1132 const IdentifierInfo *Name,
1133 const TemplateArgumentListInfo &Args) const;
1134 QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
1135 NestedNameSpecifier *NNS,
1136 const IdentifierInfo *Name,
1138 const TemplateArgument *Args) const;
1140 QualType getPackExpansionType(QualType Pattern,
1141 Optional<unsigned> NumExpansions);
1143 QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
1144 ObjCInterfaceDecl *PrevDecl = nullptr) const;
1146 QualType getObjCObjectType(QualType Base,
1147 ObjCProtocolDecl * const *Protocols,
1148 unsigned NumProtocols) const;
1150 bool ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *Decl);
1151 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
1152 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
1154 bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
1155 ObjCInterfaceDecl *IDecl);
1157 /// \brief Return a ObjCObjectPointerType type for the given ObjCObjectType.
1158 QualType getObjCObjectPointerType(QualType OIT) const;
1160 /// \brief GCC extension.
1161 QualType getTypeOfExprType(Expr *e) const;
1162 QualType getTypeOfType(QualType t) const;
1164 /// \brief C++11 decltype.
1165 QualType getDecltypeType(Expr *e, QualType UnderlyingType) const;
1167 /// \brief Unary type transforms
1168 QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
1169 UnaryTransformType::UTTKind UKind) const;
1171 /// \brief C++11 deduced auto type.
1172 QualType getAutoType(QualType DeducedType, bool IsDecltypeAuto,
1173 bool IsDependent) const;
1175 /// \brief C++11 deduction pattern for 'auto' type.
1176 QualType getAutoDeductType() const;
1178 /// \brief C++11 deduction pattern for 'auto &&' type.
1179 QualType getAutoRRefDeductType() const;
1181 /// \brief Return the unique reference to the type for the specified TagDecl
1182 /// (struct/union/class/enum) decl.
1183 QualType getTagDeclType(const TagDecl *Decl) const;
1185 /// \brief Return the unique type for "size_t" (C99 7.17), defined in
1188 /// The sizeof operator requires this (C99 6.5.3.4p4).
1189 CanQualType getSizeType() const;
1191 /// \brief Return the unique type for "intmax_t" (C99 7.18.1.5), defined in
1193 CanQualType getIntMaxType() const;
1195 /// \brief Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in
1197 CanQualType getUIntMaxType() const;
1199 /// \brief Return the unique wchar_t type available in C++ (and available as
1200 /// __wchar_t as a Microsoft extension).
1201 QualType getWCharType() const { return WCharTy; }
1203 /// \brief Return the type of wide characters. In C++, this returns the
1204 /// unique wchar_t type. In C99, this returns a type compatible with the type
1205 /// defined in <stddef.h> as defined by the target.
1206 QualType getWideCharType() const { return WideCharTy; }
1208 /// \brief Return the type of "signed wchar_t".
1210 /// Used when in C++, as a GCC extension.
1211 QualType getSignedWCharType() const;
1213 /// \brief Return the type of "unsigned wchar_t".
1215 /// Used when in C++, as a GCC extension.
1216 QualType getUnsignedWCharType() const;
1218 /// \brief In C99, this returns a type compatible with the type
1219 /// defined in <stddef.h> as defined by the target.
1220 QualType getWIntType() const { return WIntTy; }
1222 /// \brief Return a type compatible with "intptr_t" (C99 7.18.1.4),
1223 /// as defined by the target.
1224 QualType getIntPtrType() const;
1226 /// \brief Return a type compatible with "uintptr_t" (C99 7.18.1.4),
1227 /// as defined by the target.
1228 QualType getUIntPtrType() const;
1230 /// \brief Return the unique type for "ptrdiff_t" (C99 7.17) defined in
1231 /// <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1232 QualType getPointerDiffType() const;
1234 /// \brief Return the unique type for "pid_t" defined in
1235 /// <sys/types.h>. We need this to compute the correct type for vfork().
1236 QualType getProcessIDType() const;
1238 /// \brief Return the C structure type used to represent constant CFStrings.
1239 QualType getCFConstantStringType() const;
1241 /// \brief Returns the C struct type for objc_super
1242 QualType getObjCSuperType() const;
1243 void setObjCSuperType(QualType ST) { ObjCSuperType = ST; }
1245 /// Get the structure type used to representation CFStrings, or NULL
1246 /// if it hasn't yet been built.
1247 QualType getRawCFConstantStringType() const {
1248 if (CFConstantStringTypeDecl)
1249 return getTagDeclType(CFConstantStringTypeDecl);
1252 void setCFConstantStringType(QualType T);
1254 // This setter/getter represents the ObjC type for an NSConstantString.
1255 void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl);
1256 QualType getObjCConstantStringInterface() const {
1257 return ObjCConstantStringType;
1260 QualType getObjCNSStringType() const {
1261 return ObjCNSStringType;
1264 void setObjCNSStringType(QualType T) {
1265 ObjCNSStringType = T;
1268 /// \brief Retrieve the type that \c id has been defined to, which may be
1269 /// different from the built-in \c id if \c id has been typedef'd.
1270 QualType getObjCIdRedefinitionType() const {
1271 if (ObjCIdRedefinitionType.isNull())
1272 return getObjCIdType();
1273 return ObjCIdRedefinitionType;
1276 /// \brief Set the user-written type that redefines \c id.
1277 void setObjCIdRedefinitionType(QualType RedefType) {
1278 ObjCIdRedefinitionType = RedefType;
1281 /// \brief Retrieve the type that \c Class has been defined to, which may be
1282 /// different from the built-in \c Class if \c Class has been typedef'd.
1283 QualType getObjCClassRedefinitionType() const {
1284 if (ObjCClassRedefinitionType.isNull())
1285 return getObjCClassType();
1286 return ObjCClassRedefinitionType;
1289 /// \brief Set the user-written type that redefines 'SEL'.
1290 void setObjCClassRedefinitionType(QualType RedefType) {
1291 ObjCClassRedefinitionType = RedefType;
1294 /// \brief Retrieve the type that 'SEL' has been defined to, which may be
1295 /// different from the built-in 'SEL' if 'SEL' has been typedef'd.
1296 QualType getObjCSelRedefinitionType() const {
1297 if (ObjCSelRedefinitionType.isNull())
1298 return getObjCSelType();
1299 return ObjCSelRedefinitionType;
1303 /// \brief Set the user-written type that redefines 'SEL'.
1304 void setObjCSelRedefinitionType(QualType RedefType) {
1305 ObjCSelRedefinitionType = RedefType;
1308 /// \brief Retrieve the Objective-C "instancetype" type, if already known;
1309 /// otherwise, returns a NULL type;
1310 QualType getObjCInstanceType() {
1311 return getTypeDeclType(getObjCInstanceTypeDecl());
1314 /// \brief Retrieve the typedef declaration corresponding to the Objective-C
1315 /// "instancetype" type.
1316 TypedefDecl *getObjCInstanceTypeDecl();
1318 /// \brief Set the type for the C FILE type.
1319 void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; }
1321 /// \brief Retrieve the C FILE type.
1322 QualType getFILEType() const {
1324 return getTypeDeclType(FILEDecl);
1328 /// \brief Set the type for the C jmp_buf type.
1329 void setjmp_bufDecl(TypeDecl *jmp_bufDecl) {
1330 this->jmp_bufDecl = jmp_bufDecl;
1333 /// \brief Retrieve the C jmp_buf type.
1334 QualType getjmp_bufType() const {
1336 return getTypeDeclType(jmp_bufDecl);
1340 /// \brief Set the type for the C sigjmp_buf type.
1341 void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) {
1342 this->sigjmp_bufDecl = sigjmp_bufDecl;
1345 /// \brief Retrieve the C sigjmp_buf type.
1346 QualType getsigjmp_bufType() const {
1348 return getTypeDeclType(sigjmp_bufDecl);
1352 /// \brief Set the type for the C ucontext_t type.
1353 void setucontext_tDecl(TypeDecl *ucontext_tDecl) {
1354 this->ucontext_tDecl = ucontext_tDecl;
1357 /// \brief Retrieve the C ucontext_t type.
1358 QualType getucontext_tType() const {
1360 return getTypeDeclType(ucontext_tDecl);
1364 /// \brief The result type of logical operations, '<', '>', '!=', etc.
1365 QualType getLogicalOperationType() const {
1366 return getLangOpts().CPlusPlus ? BoolTy : IntTy;
1369 /// \brief Emit the Objective-CC type encoding for the given type \p T into
1372 /// If \p Field is specified then record field names are also encoded.
1373 void getObjCEncodingForType(QualType T, std::string &S,
1374 const FieldDecl *Field=nullptr) const;
1376 /// \brief Emit the Objective-C property type encoding for the given
1377 /// type \p T into \p S.
1378 void getObjCEncodingForPropertyType(QualType T, std::string &S) const;
1380 void getLegacyIntegralTypeEncoding(QualType &t) const;
1382 /// \brief Put the string version of the type qualifiers \p QT into \p S.
1383 void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
1384 std::string &S) const;
1386 /// \brief Emit the encoded type for the function \p Decl into \p S.
1388 /// This is in the same format as Objective-C method encodings.
1390 /// \returns true if an error occurred (e.g., because one of the parameter
1391 /// types is incomplete), false otherwise.
1392 bool getObjCEncodingForFunctionDecl(const FunctionDecl *Decl, std::string& S);
1394 /// \brief Emit the encoded type for the method declaration \p Decl into
1397 /// \returns true if an error occurred (e.g., because one of the parameter
1398 /// types is incomplete), false otherwise.
1399 bool getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, std::string &S,
1400 bool Extended = false)
1403 /// \brief Return the encoded type for this block declaration.
1404 std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const;
1406 /// getObjCEncodingForPropertyDecl - Return the encoded type for
1407 /// this method declaration. If non-NULL, Container must be either
1408 /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
1409 /// only be NULL when getting encodings for protocol properties.
1410 void getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
1411 const Decl *Container,
1412 std::string &S) const;
1414 bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
1415 ObjCProtocolDecl *rProto) const;
1417 ObjCPropertyImplDecl *getObjCPropertyImplDeclForPropertyDecl(
1418 const ObjCPropertyDecl *PD,
1419 const Decl *Container) const;
1421 /// \brief Return the size of type \p T for Objective-C encoding purpose,
1423 CharUnits getObjCEncodingTypeSize(QualType T) const;
1425 /// \brief Retrieve the typedef corresponding to the predefined \c id type
1427 TypedefDecl *getObjCIdDecl() const;
1429 /// \brief Represents the Objective-CC \c id type.
1431 /// This is set up lazily, by Sema. \c id is always a (typedef for a)
1432 /// pointer type, a pointer to a struct.
1433 QualType getObjCIdType() const {
1434 return getTypeDeclType(getObjCIdDecl());
1437 /// \brief Retrieve the typedef corresponding to the predefined 'SEL' type
1439 TypedefDecl *getObjCSelDecl() const;
1441 /// \brief Retrieve the type that corresponds to the predefined Objective-C
1443 QualType getObjCSelType() const {
1444 return getTypeDeclType(getObjCSelDecl());
1447 /// \brief Retrieve the typedef declaration corresponding to the predefined
1448 /// Objective-C 'Class' type.
1449 TypedefDecl *getObjCClassDecl() const;
1451 /// \brief Represents the Objective-C \c Class type.
1453 /// This is set up lazily, by Sema. \c Class is always a (typedef for a)
1454 /// pointer type, a pointer to a struct.
1455 QualType getObjCClassType() const {
1456 return getTypeDeclType(getObjCClassDecl());
1459 /// \brief Retrieve the Objective-C class declaration corresponding to
1460 /// the predefined \c Protocol class.
1461 ObjCInterfaceDecl *getObjCProtocolDecl() const;
1463 /// \brief Retrieve declaration of 'BOOL' typedef
1464 TypedefDecl *getBOOLDecl() const {
1468 /// \brief Save declaration of 'BOOL' typedef
1469 void setBOOLDecl(TypedefDecl *TD) {
1473 /// \brief type of 'BOOL' type.
1474 QualType getBOOLType() const {
1475 return getTypeDeclType(getBOOLDecl());
1478 /// \brief Retrieve the type of the Objective-C \c Protocol class.
1479 QualType getObjCProtoType() const {
1480 return getObjCInterfaceType(getObjCProtocolDecl());
1483 /// \brief Retrieve the C type declaration corresponding to the predefined
1484 /// \c __builtin_va_list type.
1485 TypedefDecl *getBuiltinVaListDecl() const;
1487 /// \brief Retrieve the type of the \c __builtin_va_list type.
1488 QualType getBuiltinVaListType() const {
1489 return getTypeDeclType(getBuiltinVaListDecl());
1492 /// \brief Retrieve the C type declaration corresponding to the predefined
1493 /// \c __va_list_tag type used to help define the \c __builtin_va_list type
1494 /// for some targets.
1495 QualType getVaListTagType() const;
1497 /// \brief Return a type with additional \c const, \c volatile, or
1498 /// \c restrict qualifiers.
1499 QualType getCVRQualifiedType(QualType T, unsigned CVR) const {
1500 return getQualifiedType(T, Qualifiers::fromCVRMask(CVR));
1503 /// \brief Un-split a SplitQualType.
1504 QualType getQualifiedType(SplitQualType split) const {
1505 return getQualifiedType(split.Ty, split.Quals);
1508 /// \brief Return a type with additional qualifiers.
1509 QualType getQualifiedType(QualType T, Qualifiers Qs) const {
1510 if (!Qs.hasNonFastQualifiers())
1511 return T.withFastQualifiers(Qs.getFastQualifiers());
1512 QualifierCollector Qc(Qs);
1513 const Type *Ptr = Qc.strip(T);
1514 return getExtQualType(Ptr, Qc);
1517 /// \brief Return a type with additional qualifiers.
1518 QualType getQualifiedType(const Type *T, Qualifiers Qs) const {
1519 if (!Qs.hasNonFastQualifiers())
1520 return QualType(T, Qs.getFastQualifiers());
1521 return getExtQualType(T, Qs);
1524 /// \brief Return a type with the given lifetime qualifier.
1526 /// \pre Neither type.ObjCLifetime() nor \p lifetime may be \c OCL_None.
1527 QualType getLifetimeQualifiedType(QualType type,
1528 Qualifiers::ObjCLifetime lifetime) {
1529 assert(type.getObjCLifetime() == Qualifiers::OCL_None);
1530 assert(lifetime != Qualifiers::OCL_None);
1533 qs.addObjCLifetime(lifetime);
1534 return getQualifiedType(type, qs);
1537 /// getUnqualifiedObjCPointerType - Returns version of
1538 /// Objective-C pointer type with lifetime qualifier removed.
1539 QualType getUnqualifiedObjCPointerType(QualType type) const {
1540 if (!type.getTypePtr()->isObjCObjectPointerType() ||
1541 !type.getQualifiers().hasObjCLifetime())
1543 Qualifiers Qs = type.getQualifiers();
1544 Qs.removeObjCLifetime();
1545 return getQualifiedType(type.getUnqualifiedType(), Qs);
1548 DeclarationNameInfo getNameForTemplate(TemplateName Name,
1549 SourceLocation NameLoc) const;
1551 TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin,
1552 UnresolvedSetIterator End) const;
1554 TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
1555 bool TemplateKeyword,
1556 TemplateDecl *Template) const;
1558 TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1559 const IdentifierInfo *Name) const;
1560 TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1561 OverloadedOperatorKind Operator) const;
1562 TemplateName getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
1563 TemplateName replacement) const;
1564 TemplateName getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
1565 const TemplateArgument &ArgPack) const;
1567 enum GetBuiltinTypeError {
1568 GE_None, ///< No error
1569 GE_Missing_stdio, ///< Missing a type from <stdio.h>
1570 GE_Missing_setjmp, ///< Missing a type from <setjmp.h>
1571 GE_Missing_ucontext ///< Missing a type from <ucontext.h>
1574 /// \brief Return the type for the specified builtin.
1576 /// If \p IntegerConstantArgs is non-null, it is filled in with a bitmask of
1577 /// arguments to the builtin that are required to be integer constant
1579 QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error,
1580 unsigned *IntegerConstantArgs = nullptr) const;
1583 CanQualType getFromTargetType(unsigned Type) const;
1584 std::pair<uint64_t, unsigned> getTypeInfoImpl(const Type *T) const;
1586 //===--------------------------------------------------------------------===//
1588 //===--------------------------------------------------------------------===//
1591 /// \brief Return one of the GCNone, Weak or Strong Objective-C garbage
1592 /// collection attributes.
1593 Qualifiers::GC getObjCGCAttrKind(QualType Ty) const;
1595 /// \brief Return true if the given vector types are of the same unqualified
1596 /// type or if they are equivalent to the same GCC vector type.
1598 /// \note This ignores whether they are target-specific (AltiVec or Neon)
1600 bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec);
1602 /// \brief Return true if this is an \c NSObject object with its \c NSObject
1604 static bool isObjCNSObjectType(QualType Ty) {
1605 return Ty->isObjCNSObjectType();
1608 //===--------------------------------------------------------------------===//
1609 // Type Sizing and Analysis
1610 //===--------------------------------------------------------------------===//
1612 /// \brief Return the APFloat 'semantics' for the specified scalar floating
1614 const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
1616 /// \brief Get the size and alignment of the specified complete type in bits.
1617 std::pair<uint64_t, unsigned> getTypeInfo(const Type *T) const;
1618 std::pair<uint64_t, unsigned> getTypeInfo(QualType T) const {
1619 return getTypeInfo(T.getTypePtr());
1622 /// \brief Return the size of the specified (complete) type \p T, in bits.
1623 uint64_t getTypeSize(QualType T) const {
1624 return getTypeInfo(T).first;
1626 uint64_t getTypeSize(const Type *T) const {
1627 return getTypeInfo(T).first;
1630 /// \brief Return the size of the character type, in bits.
1631 uint64_t getCharWidth() const {
1632 return getTypeSize(CharTy);
1635 /// \brief Convert a size in bits to a size in characters.
1636 CharUnits toCharUnitsFromBits(int64_t BitSize) const;
1638 /// \brief Convert a size in characters to a size in bits.
1639 int64_t toBits(CharUnits CharSize) const;
1641 /// \brief Return the size of the specified (complete) type \p T, in
1643 CharUnits getTypeSizeInChars(QualType T) const;
1644 CharUnits getTypeSizeInChars(const Type *T) const;
1646 /// \brief Return the ABI-specified alignment of a (complete) type \p T, in
1648 unsigned getTypeAlign(QualType T) const {
1649 return getTypeInfo(T).second;
1651 unsigned getTypeAlign(const Type *T) const {
1652 return getTypeInfo(T).second;
1655 /// \brief Return the ABI-specified alignment of a (complete) type \p T, in
1657 CharUnits getTypeAlignInChars(QualType T) const;
1658 CharUnits getTypeAlignInChars(const Type *T) const;
1660 // getTypeInfoDataSizeInChars - Return the size of a type, in chars. If the
1661 // type is a record, its data size is returned.
1662 std::pair<CharUnits, CharUnits> getTypeInfoDataSizeInChars(QualType T) const;
1664 std::pair<CharUnits, CharUnits> getTypeInfoInChars(const Type *T) const;
1665 std::pair<CharUnits, CharUnits> getTypeInfoInChars(QualType T) const;
1667 /// \brief Return the "preferred" alignment of the specified type \p T for
1668 /// the current target, in bits.
1670 /// This can be different than the ABI alignment in cases where it is
1671 /// beneficial for performance to overalign a data type.
1672 unsigned getPreferredTypeAlign(const Type *T) const;
1674 /// \brief Return the alignment in bits that should be given to a
1675 /// global variable with type \p T.
1676 unsigned getAlignOfGlobalVar(QualType T) const;
1678 /// \brief Return the alignment in characters that should be given to a
1679 /// global variable with type \p T.
1680 CharUnits getAlignOfGlobalVarInChars(QualType T) const;
1682 /// \brief Return a conservative estimate of the alignment of the specified
1685 /// \pre \p D must not be a bitfield type, as bitfields do not have a valid
1688 /// If \p ForAlignof, references are treated like their underlying type
1689 /// and large arrays don't get any special treatment. If not \p ForAlignof
1690 /// it computes the value expected by CodeGen: references are treated like
1691 /// pointers and large arrays get extra alignment.
1692 CharUnits getDeclAlign(const Decl *D, bool ForAlignof = false) const;
1694 /// \brief Get or compute information about the layout of the specified
1695 /// record (struct/union/class) \p D, which indicates its size and field
1696 /// position information.
1697 const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D) const;
1698 const ASTRecordLayout *BuildMicrosoftASTRecordLayout(const RecordDecl *D) const;
1700 /// \brief Get or compute information about the layout of the specified
1701 /// Objective-C interface.
1702 const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D)
1705 void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS,
1706 bool Simple = false) const;
1708 /// \brief Get or compute information about the layout of the specified
1709 /// Objective-C implementation.
1711 /// This may differ from the interface if synthesized ivars are present.
1712 const ASTRecordLayout &
1713 getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const;
1715 /// \brief Get our current best idea for the key function of the
1716 /// given record decl, or NULL if there isn't one.
1718 /// The key function is, according to the Itanium C++ ABI section 5.2.3:
1719 /// ...the first non-pure virtual function that is not inline at the
1720 /// point of class definition.
1722 /// Other ABIs use the same idea. However, the ARM C++ ABI ignores
1723 /// virtual functions that are defined 'inline', which means that
1724 /// the result of this computation can change.
1725 const CXXMethodDecl *getCurrentKeyFunction(const CXXRecordDecl *RD);
1727 /// \brief Observe that the given method cannot be a key function.
1728 /// Checks the key-function cache for the method's class and clears it
1729 /// if matches the given declaration.
1731 /// This is used in ABIs where out-of-line definitions marked
1732 /// inline are not considered to be key functions.
1734 /// \param method should be the declaration from the class definition
1735 void setNonKeyFunction(const CXXMethodDecl *method);
1737 /// Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
1738 uint64_t getFieldOffset(const ValueDecl *FD) const;
1740 bool isNearlyEmpty(const CXXRecordDecl *RD) const;
1742 VTableContextBase *getVTableContext();
1744 MangleContext *createMangleContext();
1746 void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass,
1747 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const;
1749 unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const;
1750 void CollectInheritedProtocols(const Decl *CDecl,
1751 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols);
1753 //===--------------------------------------------------------------------===//
1755 //===--------------------------------------------------------------------===//
1757 /// \brief Return the canonical (structural) type corresponding to the
1758 /// specified potentially non-canonical type \p T.
1760 /// The non-canonical version of a type may have many "decorated" versions of
1761 /// types. Decorators can include typedefs, 'typeof' operators, etc. The
1762 /// returned type is guaranteed to be free of any of these, allowing two
1763 /// canonical types to be compared for exact equality with a simple pointer
1765 CanQualType getCanonicalType(QualType T) const {
1766 return CanQualType::CreateUnsafe(T.getCanonicalType());
1769 const Type *getCanonicalType(const Type *T) const {
1770 return T->getCanonicalTypeInternal().getTypePtr();
1773 /// \brief Return the canonical parameter type corresponding to the specific
1774 /// potentially non-canonical one.
1776 /// Qualifiers are stripped off, functions are turned into function
1777 /// pointers, and arrays decay one level into pointers.
1778 CanQualType getCanonicalParamType(QualType T) const;
1780 /// \brief Determine whether the given types \p T1 and \p T2 are equivalent.
1781 bool hasSameType(QualType T1, QualType T2) const {
1782 return getCanonicalType(T1) == getCanonicalType(T2);
1785 bool hasSameType(const Type *T1, const Type *T2) const {
1786 return getCanonicalType(T1) == getCanonicalType(T2);
1789 /// \brief Return this type as a completely-unqualified array type,
1790 /// capturing the qualifiers in \p Quals.
1792 /// This will remove the minimal amount of sugaring from the types, similar
1793 /// to the behavior of QualType::getUnqualifiedType().
1795 /// \param T is the qualified type, which may be an ArrayType
1797 /// \param Quals will receive the full set of qualifiers that were
1798 /// applied to the array.
1800 /// \returns if this is an array type, the completely unqualified array type
1801 /// that corresponds to it. Otherwise, returns T.getUnqualifiedType().
1802 QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals);
1804 /// \brief Determine whether the given types are equivalent after
1805 /// cvr-qualifiers have been removed.
1806 bool hasSameUnqualifiedType(QualType T1, QualType T2) const {
1807 return getCanonicalType(T1).getTypePtr() ==
1808 getCanonicalType(T2).getTypePtr();
1811 bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
1812 const ObjCMethodDecl *MethodImp);
1814 bool UnwrapSimilarPointerTypes(QualType &T1, QualType &T2);
1816 /// \brief Retrieves the "canonical" nested name specifier for a
1817 /// given nested name specifier.
1819 /// The canonical nested name specifier is a nested name specifier
1820 /// that uniquely identifies a type or namespace within the type
1821 /// system. For example, given:
1826 /// template<typename T> struct X { typename T* type; };
1830 /// template<typename T> struct Y {
1831 /// typename N::S::X<T>::type member;
1835 /// Here, the nested-name-specifier for N::S::X<T>:: will be
1836 /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined
1837 /// by declarations in the type system and the canonical type for
1838 /// the template type parameter 'T' is template-param-0-0.
1839 NestedNameSpecifier *
1840 getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const;
1842 /// \brief Retrieves the default calling convention for the current target.
1843 CallingConv getDefaultCallingConvention(bool isVariadic,
1844 bool IsCXXMethod) const;
1846 /// \brief Retrieves the "canonical" template name that refers to a
1849 /// The canonical template name is the simplest expression that can
1850 /// be used to refer to a given template. For most templates, this
1851 /// expression is just the template declaration itself. For example,
1852 /// the template std::vector can be referred to via a variety of
1853 /// names---std::vector, \::std::vector, vector (if vector is in
1854 /// scope), etc.---but all of these names map down to the same
1855 /// TemplateDecl, which is used to form the canonical template name.
1857 /// Dependent template names are more interesting. Here, the
1858 /// template name could be something like T::template apply or
1859 /// std::allocator<T>::template rebind, where the nested name
1860 /// specifier itself is dependent. In this case, the canonical
1861 /// template name uses the shortest form of the dependent
1862 /// nested-name-specifier, which itself contains all canonical
1863 /// types, values, and templates.
1864 TemplateName getCanonicalTemplateName(TemplateName Name) const;
1866 /// \brief Determine whether the given template names refer to the same
1868 bool hasSameTemplateName(TemplateName X, TemplateName Y);
1870 /// \brief Retrieve the "canonical" template argument.
1872 /// The canonical template argument is the simplest template argument
1873 /// (which may be a type, value, expression, or declaration) that
1874 /// expresses the value of the argument.
1875 TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg)
1878 /// Type Query functions. If the type is an instance of the specified class,
1879 /// return the Type pointer for the underlying maximally pretty type. This
1880 /// is a member of ASTContext because this may need to do some amount of
1881 /// canonicalization, e.g. to move type qualifiers into the element type.
1882 const ArrayType *getAsArrayType(QualType T) const;
1883 const ConstantArrayType *getAsConstantArrayType(QualType T) const {
1884 return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T));
1886 const VariableArrayType *getAsVariableArrayType(QualType T) const {
1887 return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T));
1889 const IncompleteArrayType *getAsIncompleteArrayType(QualType T) const {
1890 return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
1892 const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T)
1894 return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T));
1897 /// \brief Return the innermost element type of an array type.
1899 /// For example, will return "int" for int[m][n]
1900 QualType getBaseElementType(const ArrayType *VAT) const;
1902 /// \brief Return the innermost element type of a type (which needn't
1903 /// actually be an array type).
1904 QualType getBaseElementType(QualType QT) const;
1906 /// \brief Return number of constant array elements.
1907 uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const;
1909 /// \brief Perform adjustment on the parameter type of a function.
1911 /// This routine adjusts the given parameter type @p T to the actual
1912 /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
1913 /// C++ [dcl.fct]p3). The adjusted parameter type is returned.
1914 QualType getAdjustedParameterType(QualType T) const;
1916 /// \brief Retrieve the parameter type as adjusted for use in the signature
1917 /// of a function, decaying array and function types and removing top-level
1919 QualType getSignatureParameterType(QualType T) const;
1921 /// \brief Return the properly qualified result of decaying the specified
1922 /// array type to a pointer.
1924 /// This operation is non-trivial when handling typedefs etc. The canonical
1925 /// type of \p T must be an array type, this returns a pointer to a properly
1926 /// qualified element of the array.
1928 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
1929 QualType getArrayDecayedType(QualType T) const;
1931 /// \brief Return the type that \p PromotableType will promote to: C99
1932 /// 6.3.1.1p2, assuming that \p PromotableType is a promotable integer type.
1933 QualType getPromotedIntegerType(QualType PromotableType) const;
1935 /// \brief Recurses in pointer/array types until it finds an Objective-C
1936 /// retainable type and returns its ownership.
1937 Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const;
1939 /// \brief Whether this is a promotable bitfield reference according
1940 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
1942 /// \returns the type this bit-field will promote to, or NULL if no
1943 /// promotion occurs.
1944 QualType isPromotableBitField(Expr *E) const;
1946 /// \brief Return the highest ranked integer type, see C99 6.3.1.8p1.
1948 /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
1949 /// \p LHS < \p RHS, return -1.
1950 int getIntegerTypeOrder(QualType LHS, QualType RHS) const;
1952 /// \brief Compare the rank of the two specified floating point types,
1953 /// ignoring the domain of the type (i.e. 'double' == '_Complex double').
1955 /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
1956 /// \p LHS < \p RHS, return -1.
1957 int getFloatingTypeOrder(QualType LHS, QualType RHS) const;
1959 /// \brief Return a real floating point or a complex type (based on
1960 /// \p typeDomain/\p typeSize).
1962 /// \param typeDomain a real floating point or complex type.
1963 /// \param typeSize a real floating point or complex type.
1964 QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
1965 QualType typeDomain) const;
1967 unsigned getTargetAddressSpace(QualType T) const {
1968 return getTargetAddressSpace(T.getQualifiers());
1971 unsigned getTargetAddressSpace(Qualifiers Q) const {
1972 return getTargetAddressSpace(Q.getAddressSpace());
1975 unsigned getTargetAddressSpace(unsigned AS) const {
1976 if (AS < LangAS::Offset || AS >= LangAS::Offset + LangAS::Count)
1979 return (*AddrSpaceMap)[AS - LangAS::Offset];
1982 bool addressSpaceMapManglingFor(unsigned AS) const {
1983 return AddrSpaceMapMangling ||
1984 AS < LangAS::Offset ||
1985 AS >= LangAS::Offset + LangAS::Count;
1989 // Helper for integer ordering
1990 unsigned getIntegerRank(const Type *T) const;
1994 //===--------------------------------------------------------------------===//
1995 // Type Compatibility Predicates
1996 //===--------------------------------------------------------------------===//
1998 /// Compatibility predicates used to check assignment expressions.
1999 bool typesAreCompatible(QualType T1, QualType T2,
2000 bool CompareUnqualified = false); // C99 6.2.7p1
2002 bool propertyTypesAreCompatible(QualType, QualType);
2003 bool typesAreBlockPointerCompatible(QualType, QualType);
2005 bool isObjCIdType(QualType T) const {
2006 return T == getObjCIdType();
2008 bool isObjCClassType(QualType T) const {
2009 return T == getObjCClassType();
2011 bool isObjCSelType(QualType T) const {
2012 return T == getObjCSelType();
2014 bool ObjCQualifiedIdTypesAreCompatible(QualType LHS, QualType RHS,
2017 bool ObjCQualifiedClassTypesAreCompatible(QualType LHS, QualType RHS);
2019 // Check the safety of assignment from LHS to RHS
2020 bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
2021 const ObjCObjectPointerType *RHSOPT);
2022 bool canAssignObjCInterfaces(const ObjCObjectType *LHS,
2023 const ObjCObjectType *RHS);
2024 bool canAssignObjCInterfacesInBlockPointer(
2025 const ObjCObjectPointerType *LHSOPT,
2026 const ObjCObjectPointerType *RHSOPT,
2027 bool BlockReturnType);
2028 bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
2029 QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT,
2030 const ObjCObjectPointerType *RHSOPT);
2031 bool canBindObjCObjectType(QualType To, QualType From);
2033 // Functions for calculating composite types
2034 QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false,
2035 bool Unqualified = false, bool BlockReturnType = false);
2036 QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false,
2037 bool Unqualified = false);
2038 QualType mergeFunctionParameterTypes(QualType, QualType,
2039 bool OfBlockPointer = false,
2040 bool Unqualified = false);
2041 QualType mergeTransparentUnionType(QualType, QualType,
2042 bool OfBlockPointer=false,
2043 bool Unqualified = false);
2045 QualType mergeObjCGCQualifiers(QualType, QualType);
2047 bool FunctionTypesMatchOnNSConsumedAttrs(
2048 const FunctionProtoType *FromFunctionType,
2049 const FunctionProtoType *ToFunctionType);
2051 void ResetObjCLayout(const ObjCContainerDecl *CD) {
2052 ObjCLayouts[CD] = nullptr;
2055 //===--------------------------------------------------------------------===//
2056 // Integer Predicates
2057 //===--------------------------------------------------------------------===//
2059 // The width of an integer, as defined in C99 6.2.6.2. This is the number
2060 // of bits in an integer type excluding any padding bits.
2061 unsigned getIntWidth(QualType T) const;
2063 // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
2064 // unsigned integer type. This method takes a signed type, and returns the
2065 // corresponding unsigned integer type.
2066 QualType getCorrespondingUnsignedType(QualType T) const;
2068 //===--------------------------------------------------------------------===//
2070 //===--------------------------------------------------------------------===//
2071 typedef llvm::iterator_range<SmallVectorImpl<Type *>::const_iterator>
2074 type_const_range types() const {
2075 return type_const_range(Types.begin(), Types.end());
2078 //===--------------------------------------------------------------------===//
2080 //===--------------------------------------------------------------------===//
2082 /// \brief Make an APSInt of the appropriate width and signedness for the
2083 /// given \p Value and integer \p Type.
2084 llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const {
2085 llvm::APSInt Res(getIntWidth(Type),
2086 !Type->isSignedIntegerOrEnumerationType());
2091 bool isSentinelNullExpr(const Expr *E);
2093 /// \brief Get the implementation of the ObjCInterfaceDecl \p D, or NULL if
2095 ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D);
2096 /// \brief Get the implementation of the ObjCCategoryDecl \p D, or NULL if
2098 ObjCCategoryImplDecl *getObjCImplementation(ObjCCategoryDecl *D);
2100 /// \brief Return true if there is at least one \@implementation in the TU.
2101 bool AnyObjCImplementation() {
2102 return !ObjCImpls.empty();
2105 /// \brief Set the implementation of ObjCInterfaceDecl.
2106 void setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2107 ObjCImplementationDecl *ImplD);
2108 /// \brief Set the implementation of ObjCCategoryDecl.
2109 void setObjCImplementation(ObjCCategoryDecl *CatD,
2110 ObjCCategoryImplDecl *ImplD);
2112 /// \brief Get the duplicate declaration of a ObjCMethod in the same
2113 /// interface, or null if none exists.
2114 const ObjCMethodDecl *getObjCMethodRedeclaration(
2115 const ObjCMethodDecl *MD) const {
2116 return ObjCMethodRedecls.lookup(MD);
2119 void setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2120 const ObjCMethodDecl *Redecl) {
2121 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2122 ObjCMethodRedecls[MD] = Redecl;
2125 /// \brief Returns the Objective-C interface that \p ND belongs to if it is
2126 /// an Objective-C method/property/ivar etc. that is part of an interface,
2127 /// otherwise returns null.
2128 const ObjCInterfaceDecl *getObjContainingInterface(const NamedDecl *ND) const;
2130 /// \brief Set the copy inialization expression of a block var decl.
2131 void setBlockVarCopyInits(VarDecl*VD, Expr* Init);
2132 /// \brief Get the copy initialization expression of the VarDecl \p VD, or
2133 /// NULL if none exists.
2134 Expr *getBlockVarCopyInits(const VarDecl* VD);
2136 /// \brief Allocate an uninitialized TypeSourceInfo.
2138 /// The caller should initialize the memory held by TypeSourceInfo using
2139 /// the TypeLoc wrappers.
2141 /// \param T the type that will be the basis for type source info. This type
2142 /// should refer to how the declarator was written in source code, not to
2143 /// what type semantic analysis resolved the declarator to.
2145 /// \param Size the size of the type info to create, or 0 if the size
2146 /// should be calculated based on the type.
2147 TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0) const;
2149 /// \brief Allocate a TypeSourceInfo where all locations have been
2150 /// initialized to a given location, which defaults to the empty
2153 getTrivialTypeSourceInfo(QualType T,
2154 SourceLocation Loc = SourceLocation()) const;
2156 TypeSourceInfo *getNullTypeSourceInfo() { return &NullTypeSourceInfo; }
2158 /// \brief Add a deallocation callback that will be invoked when the
2159 /// ASTContext is destroyed.
2161 /// \param Callback A callback function that will be invoked on destruction.
2163 /// \param Data Pointer data that will be provided to the callback function
2164 /// when it is called.
2165 void AddDeallocation(void (*Callback)(void*), void *Data);
2167 GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const;
2168 GVALinkage GetGVALinkageForVariable(const VarDecl *VD);
2170 /// \brief Determines if the decl can be CodeGen'ed or deserialized from PCH
2171 /// lazily, only when used; this is only relevant for function or file scoped
2172 /// var definitions.
2174 /// \returns true if the function/var must be CodeGen'ed/deserialized even if
2176 bool DeclMustBeEmitted(const Decl *D);
2178 void setManglingNumber(const NamedDecl *ND, unsigned Number);
2179 unsigned getManglingNumber(const NamedDecl *ND) const;
2181 void setStaticLocalNumber(const VarDecl *VD, unsigned Number);
2182 unsigned getStaticLocalNumber(const VarDecl *VD) const;
2184 /// \brief Retrieve the context for computing mangling numbers in the given
2186 MangleNumberingContext &getManglingNumberContext(const DeclContext *DC);
2188 MangleNumberingContext *createMangleNumberingContext() const;
2190 /// \brief Used by ParmVarDecl to store on the side the
2191 /// index of the parameter when it exceeds the size of the normal bitfield.
2192 void setParameterIndex(const ParmVarDecl *D, unsigned index);
2194 /// \brief Used by ParmVarDecl to retrieve on the side the
2195 /// index of the parameter when it exceeds the size of the normal bitfield.
2196 unsigned getParameterIndex(const ParmVarDecl *D) const;
2198 /// \brief Get the storage for the constant value of a materialized temporary
2199 /// of static storage duration.
2200 APValue *getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
2203 //===--------------------------------------------------------------------===//
2205 //===--------------------------------------------------------------------===//
2207 /// \brief The number of implicitly-declared default constructors.
2208 static unsigned NumImplicitDefaultConstructors;
2210 /// \brief The number of implicitly-declared default constructors for
2211 /// which declarations were built.
2212 static unsigned NumImplicitDefaultConstructorsDeclared;
2214 /// \brief The number of implicitly-declared copy constructors.
2215 static unsigned NumImplicitCopyConstructors;
2217 /// \brief The number of implicitly-declared copy constructors for
2218 /// which declarations were built.
2219 static unsigned NumImplicitCopyConstructorsDeclared;
2221 /// \brief The number of implicitly-declared move constructors.
2222 static unsigned NumImplicitMoveConstructors;
2224 /// \brief The number of implicitly-declared move constructors for
2225 /// which declarations were built.
2226 static unsigned NumImplicitMoveConstructorsDeclared;
2228 /// \brief The number of implicitly-declared copy assignment operators.
2229 static unsigned NumImplicitCopyAssignmentOperators;
2231 /// \brief The number of implicitly-declared copy assignment operators for
2232 /// which declarations were built.
2233 static unsigned NumImplicitCopyAssignmentOperatorsDeclared;
2235 /// \brief The number of implicitly-declared move assignment operators.
2236 static unsigned NumImplicitMoveAssignmentOperators;
2238 /// \brief The number of implicitly-declared move assignment operators for
2239 /// which declarations were built.
2240 static unsigned NumImplicitMoveAssignmentOperatorsDeclared;
2242 /// \brief The number of implicitly-declared destructors.
2243 static unsigned NumImplicitDestructors;
2245 /// \brief The number of implicitly-declared destructors for which
2246 /// declarations were built.
2247 static unsigned NumImplicitDestructorsDeclared;
2250 ASTContext(const ASTContext &) LLVM_DELETED_FUNCTION;
2251 void operator=(const ASTContext &) LLVM_DELETED_FUNCTION;
2254 /// \brief Initialize built-in types.
2256 /// This routine may only be invoked once for a given ASTContext object.
2257 /// It is normally invoked after ASTContext construction.
2259 /// \param Target The target
2260 void InitBuiltinTypes(const TargetInfo &Target);
2263 void InitBuiltinType(CanQualType &R, BuiltinType::Kind K);
2265 // Return the Objective-C type encoding for a given type.
2266 void getObjCEncodingForTypeImpl(QualType t, std::string &S,
2267 bool ExpandPointedToStructures,
2268 bool ExpandStructures,
2269 const FieldDecl *Field,
2270 bool OutermostType = false,
2271 bool EncodingProperty = false,
2272 bool StructField = false,
2273 bool EncodeBlockParameters = false,
2274 bool EncodeClassNames = false,
2275 bool EncodePointerToObjCTypedef = false) const;
2277 // Adds the encoding of the structure's members.
2278 void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S,
2279 const FieldDecl *Field,
2280 bool includeVBases = true) const;
2282 // Adds the encoding of a method parameter or return type.
2283 void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
2284 QualType T, std::string& S,
2285 bool Extended) const;
2287 /// \brief Returns true if this is an inline-initialized static data member
2288 /// which is treated as a definition for MSVC compatibility.
2289 bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const;
2292 const ASTRecordLayout &
2293 getObjCLayout(const ObjCInterfaceDecl *D,
2294 const ObjCImplementationDecl *Impl) const;
2296 /// \brief A set of deallocations that should be performed when the
2297 /// ASTContext is destroyed.
2298 typedef llvm::SmallDenseMap<void(*)(void*), llvm::SmallVector<void*, 16> >
2300 DeallocationMap Deallocations;
2302 // FIXME: This currently contains the set of StoredDeclMaps used
2303 // by DeclContext objects. This probably should not be in ASTContext,
2304 // but we include it here so that ASTContext can quickly deallocate them.
2305 llvm::PointerIntPair<StoredDeclsMap*,1> LastSDM;
2307 friend class DeclContext;
2308 friend class DeclarationNameTable;
2309 void ReleaseDeclContextMaps();
2310 void ReleaseParentMapEntries();
2312 std::unique_ptr<ParentMap> AllParents;
2314 std::unique_ptr<VTableContextBase> VTContext;
2317 /// \brief Utility function for constructing a nullary selector.
2318 static inline Selector GetNullarySelector(StringRef name, ASTContext& Ctx) {
2319 IdentifierInfo* II = &Ctx.Idents.get(name);
2320 return Ctx.Selectors.getSelector(0, &II);
2323 /// \brief Utility function for constructing an unary selector.
2324 static inline Selector GetUnarySelector(StringRef name, ASTContext& Ctx) {
2325 IdentifierInfo* II = &Ctx.Idents.get(name);
2326 return Ctx.Selectors.getSelector(1, &II);
2329 } // end namespace clang
2331 // operator new and delete aren't allowed inside namespaces.
2333 /// @brief Placement new for using the ASTContext's allocator.
2335 /// This placement form of operator new uses the ASTContext's allocator for
2336 /// obtaining memory.
2338 /// IMPORTANT: These are also declared in clang/AST/AttrIterator.h! Any changes
2339 /// here need to also be made there.
2341 /// We intentionally avoid using a nothrow specification here so that the calls
2342 /// to this operator will not perform a null check on the result -- the
2343 /// underlying allocator never returns null pointers.
2345 /// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
2347 /// // Default alignment (8)
2348 /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
2349 /// // Specific alignment
2350 /// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
2352 /// Please note that you cannot use delete on the pointer; it must be
2353 /// deallocated using an explicit destructor call followed by
2354 /// @c Context.Deallocate(Ptr).
2356 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
2357 /// @param C The ASTContext that provides the allocator.
2358 /// @param Alignment The alignment of the allocated memory (if the underlying
2359 /// allocator supports it).
2360 /// @return The allocated memory. Could be NULL.
2361 inline void *operator new(size_t Bytes, const clang::ASTContext &C,
2363 return C.Allocate(Bytes, Alignment);
2365 /// @brief Placement delete companion to the new above.
2367 /// This operator is just a companion to the new above. There is no way of
2368 /// invoking it directly; see the new operator for more details. This operator
2369 /// is called implicitly by the compiler if a placement new expression using
2370 /// the ASTContext throws in the object constructor.
2371 inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t) {
2375 /// This placement form of operator new[] uses the ASTContext's allocator for
2376 /// obtaining memory.
2378 /// We intentionally avoid using a nothrow specification here so that the calls
2379 /// to this operator will not perform a null check on the result -- the
2380 /// underlying allocator never returns null pointers.
2382 /// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
2384 /// // Default alignment (8)
2385 /// char *data = new (Context) char[10];
2386 /// // Specific alignment
2387 /// char *data = new (Context, 4) char[10];
2389 /// Please note that you cannot use delete on the pointer; it must be
2390 /// deallocated using an explicit destructor call followed by
2391 /// @c Context.Deallocate(Ptr).
2393 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
2394 /// @param C The ASTContext that provides the allocator.
2395 /// @param Alignment The alignment of the allocated memory (if the underlying
2396 /// allocator supports it).
2397 /// @return The allocated memory. Could be NULL.
2398 inline void *operator new[](size_t Bytes, const clang::ASTContext& C,
2399 size_t Alignment = 8) {
2400 return C.Allocate(Bytes, Alignment);
2403 /// @brief Placement delete[] companion to the new[] above.
2405 /// This operator is just a companion to the new[] above. There is no way of
2406 /// invoking it directly; see the new[] operator for more details. This operator
2407 /// is called implicitly by the compiler if a placement new[] expression using
2408 /// the ASTContext throws in the object constructor.
2409 inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_t) {
2413 /// \brief Create the representation of a LazyGenerationalUpdatePtr.
2414 template <typename Owner, typename T,
2415 void (clang::ExternalASTSource::*Update)(Owner)>
2416 typename clang::LazyGenerationalUpdatePtr<Owner, T, Update>::ValueType
2417 clang::LazyGenerationalUpdatePtr<Owner, T, Update>::makeValue(
2418 const clang::ASTContext &Ctx, T Value) {
2419 // Note, this is implemented here so that ExternalASTSource.h doesn't need to
2420 // include ASTContext.h. We explicitly instantiate it for all relevant types
2421 // in ASTContext.cpp.
2422 if (auto *Source = Ctx.getExternalSource())
2423 return new (Ctx) LazyData(Source, Value);