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/NestedNameSpecifier.h"
23 #include "clang/AST/PrettyPrinter.h"
24 #include "clang/AST/RawCommentList.h"
25 #include "clang/AST/TemplateName.h"
26 #include "clang/AST/Type.h"
27 #include "clang/Basic/AddressSpaces.h"
28 #include "clang/Basic/IdentifierTable.h"
29 #include "clang/Basic/LangOptions.h"
30 #include "clang/Basic/OperatorKinds.h"
31 #include "clang/Basic/PartialDiagnostic.h"
32 #include "clang/Basic/VersionTuple.h"
33 #include "llvm/ADT/DenseMap.h"
34 #include "llvm/ADT/FoldingSet.h"
35 #include "llvm/ADT/IntrusiveRefCntPtr.h"
36 #include "llvm/ADT/OwningPtr.h"
37 #include "llvm/ADT/SmallPtrSet.h"
38 #include "llvm/ADT/TinyPtrVector.h"
39 #include "llvm/Support/Allocator.h"
49 class ASTRecordLayout;
52 class DiagnosticsEngine;
54 class ExternalASTSource;
55 class ASTMutationListener;
56 class IdentifierTable;
57 class MaterializeTemporaryExpr;
61 class MangleNumberingContext;
65 class ObjCPropertyDecl;
66 class UnresolvedSetIterator;
68 class UsingShadowDecl;
70 namespace Builtin { class Context; }
76 /// \brief Holds long-lived AST nodes (such as types and decls) that can be
77 /// referred to throughout the semantic analysis of a file.
78 class ASTContext : public RefCountedBase<ASTContext> {
79 ASTContext &this_() { return *this; }
81 mutable SmallVector<Type *, 0> Types;
82 mutable llvm::FoldingSet<ExtQuals> ExtQualNodes;
83 mutable llvm::FoldingSet<ComplexType> ComplexTypes;
84 mutable llvm::FoldingSet<PointerType> PointerTypes;
85 mutable llvm::FoldingSet<DecayedType> DecayedTypes;
86 mutable llvm::FoldingSet<BlockPointerType> BlockPointerTypes;
87 mutable llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes;
88 mutable llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes;
89 mutable llvm::FoldingSet<MemberPointerType> MemberPointerTypes;
90 mutable llvm::FoldingSet<ConstantArrayType> ConstantArrayTypes;
91 mutable llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
92 mutable std::vector<VariableArrayType*> VariableArrayTypes;
93 mutable llvm::FoldingSet<DependentSizedArrayType> DependentSizedArrayTypes;
94 mutable llvm::FoldingSet<DependentSizedExtVectorType>
95 DependentSizedExtVectorTypes;
96 mutable llvm::FoldingSet<VectorType> VectorTypes;
97 mutable llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes;
98 mutable llvm::ContextualFoldingSet<FunctionProtoType, ASTContext&>
100 mutable llvm::FoldingSet<DependentTypeOfExprType> DependentTypeOfExprTypes;
101 mutable llvm::FoldingSet<DependentDecltypeType> DependentDecltypeTypes;
102 mutable llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes;
103 mutable llvm::FoldingSet<SubstTemplateTypeParmType>
104 SubstTemplateTypeParmTypes;
105 mutable llvm::FoldingSet<SubstTemplateTypeParmPackType>
106 SubstTemplateTypeParmPackTypes;
107 mutable llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&>
108 TemplateSpecializationTypes;
109 mutable llvm::FoldingSet<ParenType> ParenTypes;
110 mutable llvm::FoldingSet<ElaboratedType> ElaboratedTypes;
111 mutable llvm::FoldingSet<DependentNameType> DependentNameTypes;
112 mutable llvm::ContextualFoldingSet<DependentTemplateSpecializationType,
114 DependentTemplateSpecializationTypes;
115 llvm::FoldingSet<PackExpansionType> PackExpansionTypes;
116 mutable llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes;
117 mutable llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes;
118 mutable llvm::FoldingSet<AutoType> AutoTypes;
119 mutable llvm::FoldingSet<AtomicType> AtomicTypes;
120 llvm::FoldingSet<AttributedType> AttributedTypes;
122 mutable llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames;
123 mutable llvm::FoldingSet<DependentTemplateName> DependentTemplateNames;
124 mutable llvm::FoldingSet<SubstTemplateTemplateParmStorage>
125 SubstTemplateTemplateParms;
126 mutable llvm::ContextualFoldingSet<SubstTemplateTemplateParmPackStorage,
128 SubstTemplateTemplateParmPacks;
130 /// \brief The set of nested name specifiers.
132 /// This set is managed by the NestedNameSpecifier class.
133 mutable llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers;
134 mutable NestedNameSpecifier *GlobalNestedNameSpecifier;
135 friend class NestedNameSpecifier;
137 /// \brief A cache mapping from RecordDecls to ASTRecordLayouts.
139 /// This is lazily created. This is intentionally not serialized.
140 mutable llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>
142 mutable llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>
145 /// \brief A cache from types to size and alignment information.
146 typedef llvm::DenseMap<const Type*,
147 std::pair<uint64_t, unsigned> > TypeInfoMap;
148 mutable TypeInfoMap MemoizedTypeInfo;
150 /// \brief A cache mapping from CXXRecordDecls to key functions.
151 llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr> KeyFunctions;
153 /// \brief Mapping from ObjCContainers to their ObjCImplementations.
154 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls;
156 /// \brief Mapping from ObjCMethod to its duplicate declaration in the same
158 llvm::DenseMap<const ObjCMethodDecl*,const ObjCMethodDecl*> ObjCMethodRedecls;
160 /// \brief Mapping from __block VarDecls to their copy initialization expr.
161 llvm::DenseMap<const VarDecl*, Expr*> BlockVarCopyInits;
163 /// \brief Mapping from class scope functions specialization to their
164 /// template patterns.
165 llvm::DenseMap<const FunctionDecl*, FunctionDecl*>
166 ClassScopeSpecializationPattern;
168 /// \brief Mapping from materialized temporaries with static storage duration
169 /// that appear in constant initializers to their evaluated values.
170 llvm::DenseMap<const MaterializeTemporaryExpr*, APValue>
171 MaterializedTemporaryValues;
173 /// \brief Representation of a "canonical" template template parameter that
174 /// is used in canonical template names.
175 class CanonicalTemplateTemplateParm : public llvm::FoldingSetNode {
176 TemplateTemplateParmDecl *Parm;
179 CanonicalTemplateTemplateParm(TemplateTemplateParmDecl *Parm)
182 TemplateTemplateParmDecl *getParam() const { return Parm; }
184 void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, Parm); }
186 static void Profile(llvm::FoldingSetNodeID &ID,
187 TemplateTemplateParmDecl *Parm);
189 mutable llvm::FoldingSet<CanonicalTemplateTemplateParm>
190 CanonTemplateTemplateParms;
192 TemplateTemplateParmDecl *
193 getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const;
195 /// \brief The typedef for the __int128_t type.
196 mutable TypedefDecl *Int128Decl;
198 /// \brief The typedef for the __uint128_t type.
199 mutable TypedefDecl *UInt128Decl;
201 /// \brief The typedef for the __float128 stub type.
202 mutable TypeDecl *Float128StubDecl;
204 /// \brief The typedef for the target specific predefined
205 /// __builtin_va_list type.
206 mutable TypedefDecl *BuiltinVaListDecl;
208 /// \brief The typedef for the predefined \c id type.
209 mutable TypedefDecl *ObjCIdDecl;
211 /// \brief The typedef for the predefined \c SEL type.
212 mutable TypedefDecl *ObjCSelDecl;
214 /// \brief The typedef for the predefined \c Class type.
215 mutable TypedefDecl *ObjCClassDecl;
217 /// \brief The typedef for the predefined \c Protocol class in Objective-C.
218 mutable ObjCInterfaceDecl *ObjCProtocolClassDecl;
220 /// \brief The typedef for the predefined 'BOOL' type.
221 mutable TypedefDecl *BOOLDecl;
223 // Typedefs which may be provided defining the structure of Objective-C
225 QualType ObjCIdRedefinitionType;
226 QualType ObjCClassRedefinitionType;
227 QualType ObjCSelRedefinitionType;
229 QualType ObjCConstantStringType;
230 mutable RecordDecl *CFConstantStringTypeDecl;
232 mutable QualType ObjCSuperType;
234 QualType ObjCNSStringType;
236 /// \brief The typedef declaration for the Objective-C "instancetype" type.
237 TypedefDecl *ObjCInstanceTypeDecl;
239 /// \brief The type for the C FILE type.
242 /// \brief The type for the C jmp_buf type.
243 TypeDecl *jmp_bufDecl;
245 /// \brief The type for the C sigjmp_buf type.
246 TypeDecl *sigjmp_bufDecl;
248 /// \brief The type for the C ucontext_t type.
249 TypeDecl *ucontext_tDecl;
251 /// \brief Type for the Block descriptor for Blocks CodeGen.
253 /// Since this is only used for generation of debug info, it is not
255 mutable RecordDecl *BlockDescriptorType;
257 /// \brief Type for the Block descriptor for Blocks CodeGen.
259 /// Since this is only used for generation of debug info, it is not
261 mutable RecordDecl *BlockDescriptorExtendedType;
263 /// \brief Declaration for the CUDA cudaConfigureCall function.
264 FunctionDecl *cudaConfigureCallDecl;
266 TypeSourceInfo NullTypeSourceInfo;
268 /// \brief Keeps track of all declaration attributes.
270 /// Since so few decls have attrs, we keep them in a hash map instead of
271 /// wasting space in the Decl class.
272 llvm::DenseMap<const Decl*, AttrVec*> DeclAttrs;
274 /// \brief A mapping from non-redeclarable declarations in modules that were
275 /// merged with other declarations to the canonical declaration that they were
277 llvm::DenseMap<Decl*, Decl*> MergedDecls;
280 /// \brief A type synonym for the TemplateOrInstantiation mapping.
281 typedef llvm::PointerUnion<VarTemplateDecl *, MemberSpecializationInfo *>
282 TemplateOrSpecializationInfo;
286 /// \brief A mapping to contain the template or declaration that
287 /// a variable declaration describes or was instantiated from,
290 /// For non-templates, this value will be NULL. For variable
291 /// declarations that describe a variable template, this will be a
292 /// pointer to a VarTemplateDecl. For static data members
293 /// of class template specializations, this will be the
294 /// MemberSpecializationInfo referring to the member variable that was
295 /// instantiated or specialized. Thus, the mapping will keep track of
296 /// the static data member templates from which static data members of
297 /// class template specializations were instantiated.
299 /// Given the following example:
302 /// template<typename T>
307 /// template<typename T>
308 /// T X<T>::value = T(17);
310 /// int *x = &X<int>::value;
313 /// This mapping will contain an entry that maps from the VarDecl for
314 /// X<int>::value to the corresponding VarDecl for X<T>::value (within the
315 /// class template X) and will be marked TSK_ImplicitInstantiation.
316 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>
317 TemplateOrInstantiation;
319 /// \brief Keeps track of the declaration from which a UsingDecl was
320 /// created during instantiation.
322 /// The source declaration is always a UsingDecl, an UnresolvedUsingValueDecl,
323 /// or an UnresolvedUsingTypenameDecl.
327 /// template<typename T>
332 /// template<typename T>
333 /// struct B : A<T> {
337 /// template struct B<int>;
340 /// This mapping will contain an entry that maps from the UsingDecl in
341 /// B<int> to the UnresolvedUsingDecl in B<T>.
342 llvm::DenseMap<UsingDecl *, NamedDecl *> InstantiatedFromUsingDecl;
344 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>
345 InstantiatedFromUsingShadowDecl;
347 llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl;
349 /// \brief Mapping that stores the methods overridden by a given C++
352 /// Since most C++ member functions aren't virtual and therefore
353 /// don't override anything, we store the overridden functions in
354 /// this map on the side rather than within the CXXMethodDecl structure.
355 typedef llvm::TinyPtrVector<const CXXMethodDecl*> CXXMethodVector;
356 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector> OverriddenMethods;
358 /// \brief Mapping from each declaration context to its corresponding
359 /// mangling numbering context (used for constructs like lambdas which
360 /// need to be consistently numbered for the mangler).
361 llvm::DenseMap<const DeclContext *, MangleNumberingContext *>
362 MangleNumberingContexts;
364 /// \brief Side-table of mangling numbers for declarations which rarely
365 /// need them (like static local vars).
366 llvm::DenseMap<const NamedDecl *, unsigned> MangleNumbers;
368 /// \brief Mapping that stores parameterIndex values for ParmVarDecls when
369 /// that value exceeds the bitfield size of ParmVarDeclBits.ParameterIndex.
370 typedef llvm::DenseMap<const VarDecl *, unsigned> ParameterIndexTable;
371 ParameterIndexTable ParamIndices;
373 ImportDecl *FirstLocalImport;
374 ImportDecl *LastLocalImport;
376 TranslationUnitDecl *TUDecl;
378 /// \brief The associated SourceManager object.a
379 SourceManager &SourceMgr;
381 /// \brief The language options used to create the AST associated with
382 /// this ASTContext object.
383 LangOptions &LangOpts;
385 /// \brief The allocator used to create AST objects.
387 /// AST objects are never destructed; rather, all memory associated with the
388 /// AST objects will be released when the ASTContext itself is destroyed.
389 mutable llvm::BumpPtrAllocator BumpAlloc;
391 /// \brief Allocator for partial diagnostics.
392 PartialDiagnostic::StorageAllocator DiagAllocator;
394 /// \brief The current C++ ABI.
395 OwningPtr<CXXABI> ABI;
396 CXXABI *createCXXABI(const TargetInfo &T);
398 /// \brief The logical -> physical address space map.
399 const LangAS::Map *AddrSpaceMap;
401 /// \brief Address space map mangling must be used with language specific
402 /// address spaces (e.g. OpenCL/CUDA)
403 bool AddrSpaceMapMangling;
405 friend class ASTDeclReader;
406 friend class ASTReader;
407 friend class ASTWriter;
408 friend class CXXRecordDecl;
410 const TargetInfo *Target;
411 clang::PrintingPolicy PrintingPolicy;
414 IdentifierTable &Idents;
415 SelectorTable &Selectors;
416 Builtin::Context &BuiltinInfo;
417 mutable DeclarationNameTable DeclarationNames;
418 OwningPtr<ExternalASTSource> ExternalSource;
419 ASTMutationListener *Listener;
421 /// \brief Contains parents of a node.
422 typedef llvm::SmallVector<ast_type_traits::DynTypedNode, 1> ParentVector;
424 /// \brief Maps from a node to its parents.
425 typedef llvm::DenseMap<const void *, ParentVector> ParentMap;
427 /// \brief Returns the parents of the given node.
429 /// Note that this will lazily compute the parents of all nodes
430 /// and store them for later retrieval. Thus, the first call is O(n)
431 /// in the number of AST nodes.
433 /// Caveats and FIXMEs:
434 /// Calculating the parent map over all AST nodes will need to load the
435 /// full AST. This can be undesirable in the case where the full AST is
436 /// expensive to create (for example, when using precompiled header
437 /// preambles). Thus, there are good opportunities for optimization here.
438 /// One idea is to walk the given node downwards, looking for references
439 /// to declaration contexts - once a declaration context is found, compute
440 /// the parent map for the declaration context; if that can satisfy the
441 /// request, loading the whole AST can be avoided. Note that this is made
442 /// more complex by statements in templates having multiple parents - those
443 /// problems can be solved by building closure over the templated parts of
444 /// the AST, which also avoids touching large parts of the AST.
445 /// Additionally, we will want to add an interface to already give a hint
446 /// where to search for the parents, for example when looking at a statement
447 /// inside a certain function.
449 /// 'NodeT' can be one of Decl, Stmt, Type, TypeLoc,
450 /// NestedNameSpecifier or NestedNameSpecifierLoc.
451 template <typename NodeT>
452 ParentVector getParents(const NodeT &Node) {
453 return getParents(ast_type_traits::DynTypedNode::create(Node));
456 ParentVector getParents(const ast_type_traits::DynTypedNode &Node);
458 const clang::PrintingPolicy &getPrintingPolicy() const {
459 return PrintingPolicy;
462 void setPrintingPolicy(const clang::PrintingPolicy &Policy) {
463 PrintingPolicy = Policy;
466 SourceManager& getSourceManager() { return SourceMgr; }
467 const SourceManager& getSourceManager() const { return SourceMgr; }
469 llvm::BumpPtrAllocator &getAllocator() const {
473 void *Allocate(size_t Size, unsigned Align = 8) const {
474 return BumpAlloc.Allocate(Size, Align);
476 void Deallocate(void *Ptr) const { }
478 /// Return the total amount of physical memory allocated for representing
479 /// AST nodes and type information.
480 size_t getASTAllocatedMemory() const {
481 return BumpAlloc.getTotalMemory();
483 /// Return the total memory used for various side tables.
484 size_t getSideTableAllocatedMemory() const;
486 PartialDiagnostic::StorageAllocator &getDiagAllocator() {
487 return DiagAllocator;
490 const TargetInfo &getTargetInfo() const { return *Target; }
492 /// getIntTypeForBitwidth -
493 /// sets integer QualTy according to specified details:
494 /// bitwidth, signed/unsigned.
495 /// Returns empty type if there is no appropriate target types.
496 QualType getIntTypeForBitwidth(unsigned DestWidth,
497 unsigned Signed) const;
498 /// getRealTypeForBitwidth -
499 /// sets floating point QualTy according to specified bitwidth.
500 /// Returns empty type if there is no appropriate target types.
501 QualType getRealTypeForBitwidth(unsigned DestWidth) const;
503 bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const;
505 const LangOptions& getLangOpts() const { return LangOpts; }
507 DiagnosticsEngine &getDiagnostics() const;
509 FullSourceLoc getFullLoc(SourceLocation Loc) const {
510 return FullSourceLoc(Loc,SourceMgr);
513 /// \brief All comments in this translation unit.
514 RawCommentList Comments;
516 /// \brief True if comments are already loaded from ExternalASTSource.
517 mutable bool CommentsLoaded;
519 class RawCommentAndCacheFlags {
522 /// We searched for a comment attached to the particular declaration, but
528 /// We have found a comment attached to this particular declaration.
533 /// This declaration does not have an attached comment, and we have
534 /// searched the redeclaration chain.
536 /// If getRaw() == 0, the whole redeclaration chain does not have any
539 /// If getRaw() != 0, it is a comment propagated from other
544 Kind getKind() const LLVM_READONLY {
545 return Data.getInt();
548 void setKind(Kind K) {
552 const RawComment *getRaw() const LLVM_READONLY {
553 return Data.getPointer();
556 void setRaw(const RawComment *RC) {
560 const Decl *getOriginalDecl() const LLVM_READONLY {
564 void setOriginalDecl(const Decl *Orig) {
569 llvm::PointerIntPair<const RawComment *, 2, Kind> Data;
570 const Decl *OriginalDecl;
573 /// \brief Mapping from declarations to comments attached to any
576 /// Raw comments are owned by Comments list. This mapping is populated
578 mutable llvm::DenseMap<const Decl *, RawCommentAndCacheFlags> RedeclComments;
580 /// \brief Mapping from declarations to parsed comments attached to any
582 mutable llvm::DenseMap<const Decl *, comments::FullComment *> ParsedComments;
584 /// \brief Return the documentation comment attached to a given declaration,
585 /// without looking into cache.
586 RawComment *getRawCommentForDeclNoCache(const Decl *D) const;
589 RawCommentList &getRawCommentList() {
593 void addComment(const RawComment &RC) {
594 assert(LangOpts.RetainCommentsFromSystemHeaders ||
595 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
596 Comments.addComment(RC, BumpAlloc);
599 /// \brief Return the documentation comment attached to a given declaration.
600 /// Returns NULL if no comment is attached.
602 /// \param OriginalDecl if not NULL, is set to declaration AST node that had
603 /// the comment, if the comment we found comes from a redeclaration.
604 const RawComment *getRawCommentForAnyRedecl(
606 const Decl **OriginalDecl = NULL) const;
608 /// Return parsed documentation comment attached to a given declaration.
609 /// Returns NULL if no comment is attached.
611 /// \param PP the Preprocessor used with this TU. Could be NULL if
612 /// preprocessor is not available.
613 comments::FullComment *getCommentForDecl(const Decl *D,
614 const Preprocessor *PP) const;
616 /// Return parsed documentation comment attached to a given declaration.
617 /// Returns NULL if no comment is attached. Does not look at any
618 /// redeclarations of the declaration.
619 comments::FullComment *getLocalCommentForDeclUncached(const Decl *D) const;
621 comments::FullComment *cloneFullComment(comments::FullComment *FC,
622 const Decl *D) const;
625 mutable comments::CommandTraits CommentCommandTraits;
628 comments::CommandTraits &getCommentCommandTraits() const {
629 return CommentCommandTraits;
632 /// \brief Retrieve the attributes for the given declaration.
633 AttrVec& getDeclAttrs(const Decl *D);
635 /// \brief Erase the attributes corresponding to the given declaration.
636 void eraseDeclAttrs(const Decl *D);
638 /// \brief If this variable is an instantiated static data member of a
639 /// class template specialization, returns the templated static data member
640 /// from which it was instantiated.
642 MemberSpecializationInfo *getInstantiatedFromStaticDataMember(
645 TemplateOrSpecializationInfo
646 getTemplateOrSpecializationInfo(const VarDecl *Var);
648 FunctionDecl *getClassScopeSpecializationPattern(const FunctionDecl *FD);
650 void setClassScopeSpecializationPattern(FunctionDecl *FD,
651 FunctionDecl *Pattern);
653 /// \brief Note that the static data member \p Inst is an instantiation of
654 /// the static data member template \p Tmpl of a class template.
655 void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
656 TemplateSpecializationKind TSK,
657 SourceLocation PointOfInstantiation = SourceLocation());
659 void setTemplateOrSpecializationInfo(VarDecl *Inst,
660 TemplateOrSpecializationInfo TSI);
662 /// \brief If the given using decl \p Inst is an instantiation of a
663 /// (possibly unresolved) using decl from a template instantiation,
665 NamedDecl *getInstantiatedFromUsingDecl(UsingDecl *Inst);
667 /// \brief Remember that the using decl \p Inst is an instantiation
668 /// of the using decl \p Pattern of a class template.
669 void setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern);
671 void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
672 UsingShadowDecl *Pattern);
673 UsingShadowDecl *getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst);
675 FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field);
677 void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl);
679 // Access to the set of methods overridden by the given C++ method.
680 typedef CXXMethodVector::const_iterator overridden_cxx_method_iterator;
681 overridden_cxx_method_iterator
682 overridden_methods_begin(const CXXMethodDecl *Method) const;
684 overridden_cxx_method_iterator
685 overridden_methods_end(const CXXMethodDecl *Method) const;
687 unsigned overridden_methods_size(const CXXMethodDecl *Method) const;
689 /// \brief Note that the given C++ \p Method overrides the given \p
690 /// Overridden method.
691 void addOverriddenMethod(const CXXMethodDecl *Method,
692 const CXXMethodDecl *Overridden);
694 /// \brief Return C++ or ObjC overridden methods for the given \p Method.
696 /// An ObjC method is considered to override any method in the class's
697 /// base classes, its protocols, or its categories' protocols, that has
698 /// the same selector and is of the same kind (class or instance).
699 /// A method in an implementation is not considered as overriding the same
700 /// method in the interface or its categories.
701 void getOverriddenMethods(
702 const NamedDecl *Method,
703 SmallVectorImpl<const NamedDecl *> &Overridden) const;
705 /// \brief Notify the AST context that a new import declaration has been
706 /// parsed or implicitly created within this translation unit.
707 void addedLocalImportDecl(ImportDecl *Import);
709 static ImportDecl *getNextLocalImport(ImportDecl *Import) {
710 return Import->NextLocalImport;
713 /// \brief Iterator that visits import declarations.
714 class import_iterator {
718 typedef ImportDecl *value_type;
719 typedef ImportDecl *reference;
720 typedef ImportDecl *pointer;
721 typedef int difference_type;
722 typedef std::forward_iterator_tag iterator_category;
724 import_iterator() : Import() { }
725 explicit import_iterator(ImportDecl *Import) : Import(Import) { }
727 reference operator*() const { return Import; }
728 pointer operator->() const { return Import; }
730 import_iterator &operator++() {
731 Import = ASTContext::getNextLocalImport(Import);
735 import_iterator operator++(int) {
736 import_iterator Other(*this);
741 friend bool operator==(import_iterator X, import_iterator Y) {
742 return X.Import == Y.Import;
745 friend bool operator!=(import_iterator X, import_iterator Y) {
746 return X.Import != Y.Import;
750 import_iterator local_import_begin() const {
751 return import_iterator(FirstLocalImport);
753 import_iterator local_import_end() const { return import_iterator(); }
755 Decl *getPrimaryMergedDecl(Decl *D) {
756 Decl *Result = MergedDecls.lookup(D);
757 return Result ? Result : D;
759 void setPrimaryMergedDecl(Decl *D, Decl *Primary) {
760 MergedDecls[D] = Primary;
763 TranslationUnitDecl *getTranslationUnitDecl() const { return TUDecl; }
770 CanQualType WCharTy; // [C++ 3.9.1p5].
771 CanQualType WideCharTy; // Same as WCharTy in C++, integer type in C99.
772 CanQualType WIntTy; // [C99 7.24.1], integer type unchanged by default promotions.
773 CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99.
774 CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99.
775 CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty;
776 CanQualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy;
777 CanQualType UnsignedLongLongTy, UnsignedInt128Ty;
778 CanQualType FloatTy, DoubleTy, LongDoubleTy;
779 CanQualType HalfTy; // [OpenCL 6.1.1.1], ARM NEON
780 CanQualType FloatComplexTy, DoubleComplexTy, LongDoubleComplexTy;
781 CanQualType VoidPtrTy, NullPtrTy;
782 CanQualType DependentTy, OverloadTy, BoundMemberTy, UnknownAnyTy;
783 CanQualType BuiltinFnTy;
784 CanQualType PseudoObjectTy, ARCUnbridgedCastTy;
785 CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy;
786 CanQualType ObjCBuiltinBoolTy;
787 CanQualType OCLImage1dTy, OCLImage1dArrayTy, OCLImage1dBufferTy;
788 CanQualType OCLImage2dTy, OCLImage2dArrayTy;
789 CanQualType OCLImage3dTy;
790 CanQualType OCLSamplerTy, OCLEventTy;
792 // Types for deductions in C++0x [stmt.ranged]'s desugaring. Built on demand.
793 mutable QualType AutoDeductTy; // Deduction against 'auto'.
794 mutable QualType AutoRRefDeductTy; // Deduction against 'auto &&'.
796 // Type used to help define __builtin_va_list for some targets.
797 // The type is built when constructing 'BuiltinVaListDecl'.
798 mutable QualType VaListTagTy;
800 ASTContext(LangOptions& LOpts, SourceManager &SM, const TargetInfo *t,
801 IdentifierTable &idents, SelectorTable &sels,
802 Builtin::Context &builtins,
803 unsigned size_reserve,
804 bool DelayInitialization = false);
808 /// \brief Attach an external AST source to the AST context.
810 /// The external AST source provides the ability to load parts of
811 /// the abstract syntax tree as needed from some external storage,
812 /// e.g., a precompiled header.
813 void setExternalSource(OwningPtr<ExternalASTSource> &Source);
815 /// \brief Retrieve a pointer to the external AST source associated
816 /// with this AST context, if any.
817 ExternalASTSource *getExternalSource() const { return ExternalSource.get(); }
819 /// \brief Attach an AST mutation listener to the AST context.
821 /// The AST mutation listener provides the ability to track modifications to
822 /// the abstract syntax tree entities committed after they were initially
824 void setASTMutationListener(ASTMutationListener *Listener) {
825 this->Listener = Listener;
828 /// \brief Retrieve a pointer to the AST mutation listener associated
829 /// with this AST context, if any.
830 ASTMutationListener *getASTMutationListener() const { return Listener; }
832 void PrintStats() const;
833 const SmallVectorImpl<Type *>& getTypes() const { return Types; }
835 /// \brief Retrieve the declaration for the 128-bit signed integer type.
836 TypedefDecl *getInt128Decl() const;
838 /// \brief Retrieve the declaration for the 128-bit unsigned integer type.
839 TypedefDecl *getUInt128Decl() const;
841 /// \brief Retrieve the declaration for a 128-bit float stub type.
842 TypeDecl *getFloat128StubType() const;
844 //===--------------------------------------------------------------------===//
846 //===--------------------------------------------------------------------===//
849 /// \brief Return a type with extended qualifiers.
850 QualType getExtQualType(const Type *Base, Qualifiers Quals) const;
852 QualType getTypeDeclTypeSlow(const TypeDecl *Decl) const;
855 /// \brief Return the uniqued reference to the type for an address space
856 /// qualified type with the specified type and address space.
858 /// The resulting type has a union of the qualifiers from T and the address
859 /// space. If T already has an address space specifier, it is silently
861 QualType getAddrSpaceQualType(QualType T, unsigned AddressSpace) const;
863 /// \brief Return the uniqued reference to the type for an Objective-C
864 /// gc-qualified type.
866 /// The retulting type has a union of the qualifiers from T and the gc
868 QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const;
870 /// \brief Return the uniqued reference to the type for a \c restrict
873 /// The resulting type has a union of the qualifiers from \p T and
875 QualType getRestrictType(QualType T) const {
876 return T.withFastQualifiers(Qualifiers::Restrict);
879 /// \brief Return the uniqued reference to the type for a \c volatile
882 /// The resulting type has a union of the qualifiers from \p T and
884 QualType getVolatileType(QualType T) const {
885 return T.withFastQualifiers(Qualifiers::Volatile);
888 /// \brief Return the uniqued reference to the type for a \c const
891 /// The resulting type has a union of the qualifiers from \p T and \c const.
893 /// It can be reasonably expected that this will always be equivalent to
894 /// calling T.withConst().
895 QualType getConstType(QualType T) const { return T.withConst(); }
897 /// \brief Change the ExtInfo on a function type.
898 const FunctionType *adjustFunctionType(const FunctionType *Fn,
899 FunctionType::ExtInfo EInfo);
901 /// \brief Change the result type of a function type once it is deduced.
902 void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType);
904 /// \brief Return the uniqued reference to the type for a complex
905 /// number with the specified element type.
906 QualType getComplexType(QualType T) const;
907 CanQualType getComplexType(CanQualType T) const {
908 return CanQualType::CreateUnsafe(getComplexType((QualType) T));
911 /// \brief Return the uniqued reference to the type for a pointer to
912 /// the specified type.
913 QualType getPointerType(QualType T) const;
914 CanQualType getPointerType(CanQualType T) const {
915 return CanQualType::CreateUnsafe(getPointerType((QualType) T));
918 /// \brief Return the uniqued reference to the decayed version of the given
919 /// type. Can only be called on array and function types which decay to
921 QualType getDecayedType(QualType T) const;
922 CanQualType getDecayedType(CanQualType T) const {
923 return CanQualType::CreateUnsafe(getDecayedType((QualType) T));
926 /// \brief Return the uniqued reference to the atomic type for the specified
928 QualType getAtomicType(QualType T) const;
930 /// \brief Return the uniqued reference to the type for a block of the
932 QualType getBlockPointerType(QualType T) const;
934 /// Gets the struct used to keep track of the descriptor for pointer to
936 QualType getBlockDescriptorType() const;
938 /// Gets the struct used to keep track of the extended descriptor for
939 /// pointer to blocks.
940 QualType getBlockDescriptorExtendedType() const;
942 void setcudaConfigureCallDecl(FunctionDecl *FD) {
943 cudaConfigureCallDecl = FD;
945 FunctionDecl *getcudaConfigureCallDecl() {
946 return cudaConfigureCallDecl;
949 /// Returns true iff we need copy/dispose helpers for the given type.
950 bool BlockRequiresCopying(QualType Ty, const VarDecl *D);
953 /// Returns true, if given type has a known lifetime. HasByrefExtendedLayout is set
954 /// to false in this case. If HasByrefExtendedLayout returns true, byref variable
955 /// has extended lifetime.
956 bool getByrefLifetime(QualType Ty,
957 Qualifiers::ObjCLifetime &Lifetime,
958 bool &HasByrefExtendedLayout) const;
960 /// \brief Return the uniqued reference to the type for an lvalue reference
961 /// to the specified type.
962 QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true)
965 /// \brief Return the uniqued reference to the type for an rvalue reference
966 /// to the specified type.
967 QualType getRValueReferenceType(QualType T) const;
969 /// \brief Return the uniqued reference to the type for a member pointer to
970 /// the specified type in the specified class.
972 /// The class \p Cls is a \c Type because it could be a dependent name.
973 QualType getMemberPointerType(QualType T, const Type *Cls) const;
975 /// \brief Return a non-unique reference to the type for a variable array of
976 /// the specified element type.
977 QualType getVariableArrayType(QualType EltTy, Expr *NumElts,
978 ArrayType::ArraySizeModifier ASM,
979 unsigned IndexTypeQuals,
980 SourceRange Brackets) const;
982 /// \brief Return a non-unique reference to the type for a dependently-sized
983 /// array of the specified element type.
985 /// FIXME: We will need these to be uniqued, or at least comparable, at some
987 QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
988 ArrayType::ArraySizeModifier ASM,
989 unsigned IndexTypeQuals,
990 SourceRange Brackets) const;
992 /// \brief Return a unique reference to the type for an incomplete array of
993 /// the specified element type.
994 QualType getIncompleteArrayType(QualType EltTy,
995 ArrayType::ArraySizeModifier ASM,
996 unsigned IndexTypeQuals) const;
998 /// \brief Return the unique reference to the type for a constant array of
999 /// the specified element type.
1000 QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize,
1001 ArrayType::ArraySizeModifier ASM,
1002 unsigned IndexTypeQuals) const;
1004 /// \brief Returns a vla type where known sizes are replaced with [*].
1005 QualType getVariableArrayDecayedType(QualType Ty) const;
1007 /// \brief Return the unique reference to a vector type of the specified
1008 /// element type and size.
1010 /// \pre \p VectorType must be a built-in type.
1011 QualType getVectorType(QualType VectorType, unsigned NumElts,
1012 VectorType::VectorKind VecKind) const;
1014 /// \brief Return the unique reference to an extended vector type
1015 /// of the specified element type and size.
1017 /// \pre \p VectorType must be a built-in type.
1018 QualType getExtVectorType(QualType VectorType, unsigned NumElts) const;
1020 /// \pre Return a non-unique reference to the type for a dependently-sized
1021 /// vector of the specified element type.
1023 /// FIXME: We will need these to be uniqued, or at least comparable, at some
1025 QualType getDependentSizedExtVectorType(QualType VectorType,
1027 SourceLocation AttrLoc) const;
1029 /// \brief Return a K&R style C function type like 'int()'.
1030 QualType getFunctionNoProtoType(QualType ResultTy,
1031 const FunctionType::ExtInfo &Info) const;
1033 QualType getFunctionNoProtoType(QualType ResultTy) const {
1034 return getFunctionNoProtoType(ResultTy, FunctionType::ExtInfo());
1037 /// \brief Return a normal function type with a typed argument list.
1038 QualType getFunctionType(QualType ResultTy, ArrayRef<QualType> Args,
1039 const FunctionProtoType::ExtProtoInfo &EPI) const;
1041 /// \brief Return the unique reference to the type for the specified type
1043 QualType getTypeDeclType(const TypeDecl *Decl,
1044 const TypeDecl *PrevDecl = 0) const {
1045 assert(Decl && "Passed null for Decl param");
1046 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1049 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
1050 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1051 return QualType(PrevDecl->TypeForDecl, 0);
1054 return getTypeDeclTypeSlow(Decl);
1057 /// \brief Return the unique reference to the type for the specified
1058 /// typedef-name decl.
1059 QualType getTypedefType(const TypedefNameDecl *Decl,
1060 QualType Canon = QualType()) const;
1062 QualType getRecordType(const RecordDecl *Decl) const;
1064 QualType getEnumType(const EnumDecl *Decl) const;
1066 QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const;
1068 QualType getAttributedType(AttributedType::Kind attrKind,
1069 QualType modifiedType,
1070 QualType equivalentType);
1072 QualType getSubstTemplateTypeParmType(const TemplateTypeParmType *Replaced,
1073 QualType Replacement) const;
1074 QualType getSubstTemplateTypeParmPackType(
1075 const TemplateTypeParmType *Replaced,
1076 const TemplateArgument &ArgPack);
1078 QualType getTemplateTypeParmType(unsigned Depth, unsigned Index,
1080 TemplateTypeParmDecl *ParmDecl = 0) const;
1082 QualType getTemplateSpecializationType(TemplateName T,
1083 const TemplateArgument *Args,
1085 QualType Canon = QualType()) const;
1087 QualType getCanonicalTemplateSpecializationType(TemplateName T,
1088 const TemplateArgument *Args,
1089 unsigned NumArgs) const;
1091 QualType getTemplateSpecializationType(TemplateName T,
1092 const TemplateArgumentListInfo &Args,
1093 QualType Canon = QualType()) const;
1096 getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc,
1097 const TemplateArgumentListInfo &Args,
1098 QualType Canon = QualType()) const;
1100 QualType getParenType(QualType NamedType) const;
1102 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1103 NestedNameSpecifier *NNS,
1104 QualType NamedType) const;
1105 QualType getDependentNameType(ElaboratedTypeKeyword Keyword,
1106 NestedNameSpecifier *NNS,
1107 const IdentifierInfo *Name,
1108 QualType Canon = QualType()) const;
1110 QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
1111 NestedNameSpecifier *NNS,
1112 const IdentifierInfo *Name,
1113 const TemplateArgumentListInfo &Args) const;
1114 QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
1115 NestedNameSpecifier *NNS,
1116 const IdentifierInfo *Name,
1118 const TemplateArgument *Args) const;
1120 QualType getPackExpansionType(QualType Pattern,
1121 Optional<unsigned> NumExpansions);
1123 QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
1124 ObjCInterfaceDecl *PrevDecl = 0) const;
1126 QualType getObjCObjectType(QualType Base,
1127 ObjCProtocolDecl * const *Protocols,
1128 unsigned NumProtocols) const;
1130 /// \brief Return a ObjCObjectPointerType type for the given ObjCObjectType.
1131 QualType getObjCObjectPointerType(QualType OIT) const;
1133 /// \brief GCC extension.
1134 QualType getTypeOfExprType(Expr *e) const;
1135 QualType getTypeOfType(QualType t) const;
1137 /// \brief C++11 decltype.
1138 QualType getDecltypeType(Expr *e, QualType UnderlyingType) const;
1140 /// \brief Unary type transforms
1141 QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
1142 UnaryTransformType::UTTKind UKind) const;
1144 /// \brief C++11 deduced auto type.
1145 QualType getAutoType(QualType DeducedType, bool IsDecltypeAuto,
1146 bool IsDependent) const;
1148 /// \brief C++11 deduction pattern for 'auto' type.
1149 QualType getAutoDeductType() const;
1151 /// \brief C++11 deduction pattern for 'auto &&' type.
1152 QualType getAutoRRefDeductType() const;
1154 /// \brief Return the unique reference to the type for the specified TagDecl
1155 /// (struct/union/class/enum) decl.
1156 QualType getTagDeclType(const TagDecl *Decl) const;
1158 /// \brief Return the unique type for "size_t" (C99 7.17), defined in
1161 /// The sizeof operator requires this (C99 6.5.3.4p4).
1162 CanQualType getSizeType() const;
1164 /// \brief Return the unique type for "intmax_t" (C99 7.18.1.5), defined in
1166 CanQualType getIntMaxType() const;
1168 /// \brief Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in
1170 CanQualType getUIntMaxType() const;
1172 /// \brief Return the unique wchar_t type available in C++ (and available as
1173 /// __wchar_t as a Microsoft extension).
1174 QualType getWCharType() const { return WCharTy; }
1176 /// \brief Return the type of wide characters. In C++, this returns the
1177 /// unique wchar_t type. In C99, this returns a type compatible with the type
1178 /// defined in <stddef.h> as defined by the target.
1179 QualType getWideCharType() const { return WideCharTy; }
1181 /// \brief Return the type of "signed wchar_t".
1183 /// Used when in C++, as a GCC extension.
1184 QualType getSignedWCharType() const;
1186 /// \brief Return the type of "unsigned wchar_t".
1188 /// Used when in C++, as a GCC extension.
1189 QualType getUnsignedWCharType() const;
1191 /// \brief In C99, this returns a type compatible with the type
1192 /// defined in <stddef.h> as defined by the target.
1193 QualType getWIntType() const { return WIntTy; }
1195 /// \brief Return a type compatible with "intptr_t" (C99 7.18.1.4),
1196 /// as defined by the target.
1197 QualType getIntPtrType() const;
1199 /// \brief Return a type compatible with "uintptr_t" (C99 7.18.1.4),
1200 /// as defined by the target.
1201 QualType getUIntPtrType() const;
1203 /// \brief Return the unique type for "ptrdiff_t" (C99 7.17) defined in
1204 /// <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1205 QualType getPointerDiffType() const;
1207 /// \brief Return the unique type for "pid_t" defined in
1208 /// <sys/types.h>. We need this to compute the correct type for vfork().
1209 QualType getProcessIDType() const;
1211 /// \brief Return the C structure type used to represent constant CFStrings.
1212 QualType getCFConstantStringType() const;
1214 /// \brief Returns the C struct type for objc_super
1215 QualType getObjCSuperType() const;
1216 void setObjCSuperType(QualType ST) { ObjCSuperType = ST; }
1218 /// Get the structure type used to representation CFStrings, or NULL
1219 /// if it hasn't yet been built.
1220 QualType getRawCFConstantStringType() const {
1221 if (CFConstantStringTypeDecl)
1222 return getTagDeclType(CFConstantStringTypeDecl);
1225 void setCFConstantStringType(QualType T);
1227 // This setter/getter represents the ObjC type for an NSConstantString.
1228 void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl);
1229 QualType getObjCConstantStringInterface() const {
1230 return ObjCConstantStringType;
1233 QualType getObjCNSStringType() const {
1234 return ObjCNSStringType;
1237 void setObjCNSStringType(QualType T) {
1238 ObjCNSStringType = T;
1241 /// \brief Retrieve the type that \c id has been defined to, which may be
1242 /// different from the built-in \c id if \c id has been typedef'd.
1243 QualType getObjCIdRedefinitionType() const {
1244 if (ObjCIdRedefinitionType.isNull())
1245 return getObjCIdType();
1246 return ObjCIdRedefinitionType;
1249 /// \brief Set the user-written type that redefines \c id.
1250 void setObjCIdRedefinitionType(QualType RedefType) {
1251 ObjCIdRedefinitionType = RedefType;
1254 /// \brief Retrieve the type that \c Class has been defined to, which may be
1255 /// different from the built-in \c Class if \c Class has been typedef'd.
1256 QualType getObjCClassRedefinitionType() const {
1257 if (ObjCClassRedefinitionType.isNull())
1258 return getObjCClassType();
1259 return ObjCClassRedefinitionType;
1262 /// \brief Set the user-written type that redefines 'SEL'.
1263 void setObjCClassRedefinitionType(QualType RedefType) {
1264 ObjCClassRedefinitionType = RedefType;
1267 /// \brief Retrieve the type that 'SEL' has been defined to, which may be
1268 /// different from the built-in 'SEL' if 'SEL' has been typedef'd.
1269 QualType getObjCSelRedefinitionType() const {
1270 if (ObjCSelRedefinitionType.isNull())
1271 return getObjCSelType();
1272 return ObjCSelRedefinitionType;
1276 /// \brief Set the user-written type that redefines 'SEL'.
1277 void setObjCSelRedefinitionType(QualType RedefType) {
1278 ObjCSelRedefinitionType = RedefType;
1281 /// \brief Retrieve the Objective-C "instancetype" type, if already known;
1282 /// otherwise, returns a NULL type;
1283 QualType getObjCInstanceType() {
1284 return getTypeDeclType(getObjCInstanceTypeDecl());
1287 /// \brief Retrieve the typedef declaration corresponding to the Objective-C
1288 /// "instancetype" type.
1289 TypedefDecl *getObjCInstanceTypeDecl();
1291 /// \brief Set the type for the C FILE type.
1292 void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; }
1294 /// \brief Retrieve the C FILE type.
1295 QualType getFILEType() const {
1297 return getTypeDeclType(FILEDecl);
1301 /// \brief Set the type for the C jmp_buf type.
1302 void setjmp_bufDecl(TypeDecl *jmp_bufDecl) {
1303 this->jmp_bufDecl = jmp_bufDecl;
1306 /// \brief Retrieve the C jmp_buf type.
1307 QualType getjmp_bufType() const {
1309 return getTypeDeclType(jmp_bufDecl);
1313 /// \brief Set the type for the C sigjmp_buf type.
1314 void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) {
1315 this->sigjmp_bufDecl = sigjmp_bufDecl;
1318 /// \brief Retrieve the C sigjmp_buf type.
1319 QualType getsigjmp_bufType() const {
1321 return getTypeDeclType(sigjmp_bufDecl);
1325 /// \brief Set the type for the C ucontext_t type.
1326 void setucontext_tDecl(TypeDecl *ucontext_tDecl) {
1327 this->ucontext_tDecl = ucontext_tDecl;
1330 /// \brief Retrieve the C ucontext_t type.
1331 QualType getucontext_tType() const {
1333 return getTypeDeclType(ucontext_tDecl);
1337 /// \brief The result type of logical operations, '<', '>', '!=', etc.
1338 QualType getLogicalOperationType() const {
1339 return getLangOpts().CPlusPlus ? BoolTy : IntTy;
1342 /// \brief Emit the Objective-CC type encoding for the given type \p T into
1345 /// If \p Field is specified then record field names are also encoded.
1346 void getObjCEncodingForType(QualType T, std::string &S,
1347 const FieldDecl *Field=0) const;
1349 void getLegacyIntegralTypeEncoding(QualType &t) const;
1351 /// \brief Put the string version of the type qualifiers \p QT into \p S.
1352 void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
1353 std::string &S) const;
1355 /// \brief Emit the encoded type for the function \p Decl into \p S.
1357 /// This is in the same format as Objective-C method encodings.
1359 /// \returns true if an error occurred (e.g., because one of the parameter
1360 /// types is incomplete), false otherwise.
1361 bool getObjCEncodingForFunctionDecl(const FunctionDecl *Decl, std::string& S);
1363 /// \brief Emit the encoded type for the method declaration \p Decl into
1366 /// \returns true if an error occurred (e.g., because one of the parameter
1367 /// types is incomplete), false otherwise.
1368 bool getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, std::string &S,
1369 bool Extended = false)
1372 /// \brief Return the encoded type for this block declaration.
1373 std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const;
1375 /// getObjCEncodingForPropertyDecl - Return the encoded type for
1376 /// this method declaration. If non-NULL, Container must be either
1377 /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
1378 /// only be NULL when getting encodings for protocol properties.
1379 void getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
1380 const Decl *Container,
1381 std::string &S) const;
1383 bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
1384 ObjCProtocolDecl *rProto) const;
1386 /// \brief Return the size of type \p T for Objective-C encoding purpose,
1388 CharUnits getObjCEncodingTypeSize(QualType T) const;
1390 /// \brief Retrieve the typedef corresponding to the predefined \c id type
1392 TypedefDecl *getObjCIdDecl() const;
1394 /// \brief Represents the Objective-CC \c id type.
1396 /// This is set up lazily, by Sema. \c id is always a (typedef for a)
1397 /// pointer type, a pointer to a struct.
1398 QualType getObjCIdType() const {
1399 return getTypeDeclType(getObjCIdDecl());
1402 /// \brief Retrieve the typedef corresponding to the predefined 'SEL' type
1404 TypedefDecl *getObjCSelDecl() const;
1406 /// \brief Retrieve the type that corresponds to the predefined Objective-C
1408 QualType getObjCSelType() const {
1409 return getTypeDeclType(getObjCSelDecl());
1412 /// \brief Retrieve the typedef declaration corresponding to the predefined
1413 /// Objective-C 'Class' type.
1414 TypedefDecl *getObjCClassDecl() const;
1416 /// \brief Represents the Objective-C \c Class type.
1418 /// This is set up lazily, by Sema. \c Class is always a (typedef for a)
1419 /// pointer type, a pointer to a struct.
1420 QualType getObjCClassType() const {
1421 return getTypeDeclType(getObjCClassDecl());
1424 /// \brief Retrieve the Objective-C class declaration corresponding to
1425 /// the predefined \c Protocol class.
1426 ObjCInterfaceDecl *getObjCProtocolDecl() const;
1428 /// \brief Retrieve declaration of 'BOOL' typedef
1429 TypedefDecl *getBOOLDecl() const {
1433 /// \brief Save declaration of 'BOOL' typedef
1434 void setBOOLDecl(TypedefDecl *TD) {
1438 /// \brief type of 'BOOL' type.
1439 QualType getBOOLType() const {
1440 return getTypeDeclType(getBOOLDecl());
1443 /// \brief Retrieve the type of the Objective-C \c Protocol class.
1444 QualType getObjCProtoType() const {
1445 return getObjCInterfaceType(getObjCProtocolDecl());
1448 /// \brief Retrieve the C type declaration corresponding to the predefined
1449 /// \c __builtin_va_list type.
1450 TypedefDecl *getBuiltinVaListDecl() const;
1452 /// \brief Retrieve the type of the \c __builtin_va_list type.
1453 QualType getBuiltinVaListType() const {
1454 return getTypeDeclType(getBuiltinVaListDecl());
1457 /// \brief Retrieve the C type declaration corresponding to the predefined
1458 /// \c __va_list_tag type used to help define the \c __builtin_va_list type
1459 /// for some targets.
1460 QualType getVaListTagType() const;
1462 /// \brief Return a type with additional \c const, \c volatile, or
1463 /// \c restrict qualifiers.
1464 QualType getCVRQualifiedType(QualType T, unsigned CVR) const {
1465 return getQualifiedType(T, Qualifiers::fromCVRMask(CVR));
1468 /// \brief Un-split a SplitQualType.
1469 QualType getQualifiedType(SplitQualType split) const {
1470 return getQualifiedType(split.Ty, split.Quals);
1473 /// \brief Return a type with additional qualifiers.
1474 QualType getQualifiedType(QualType T, Qualifiers Qs) const {
1475 if (!Qs.hasNonFastQualifiers())
1476 return T.withFastQualifiers(Qs.getFastQualifiers());
1477 QualifierCollector Qc(Qs);
1478 const Type *Ptr = Qc.strip(T);
1479 return getExtQualType(Ptr, Qc);
1482 /// \brief Return a type with additional qualifiers.
1483 QualType getQualifiedType(const Type *T, Qualifiers Qs) const {
1484 if (!Qs.hasNonFastQualifiers())
1485 return QualType(T, Qs.getFastQualifiers());
1486 return getExtQualType(T, Qs);
1489 /// \brief Return a type with the given lifetime qualifier.
1491 /// \pre Neither type.ObjCLifetime() nor \p lifetime may be \c OCL_None.
1492 QualType getLifetimeQualifiedType(QualType type,
1493 Qualifiers::ObjCLifetime lifetime) {
1494 assert(type.getObjCLifetime() == Qualifiers::OCL_None);
1495 assert(lifetime != Qualifiers::OCL_None);
1498 qs.addObjCLifetime(lifetime);
1499 return getQualifiedType(type, qs);
1502 /// getUnqualifiedObjCPointerType - Returns version of
1503 /// Objective-C pointer type with lifetime qualifier removed.
1504 QualType getUnqualifiedObjCPointerType(QualType type) const {
1505 if (!type.getTypePtr()->isObjCObjectPointerType() ||
1506 !type.getQualifiers().hasObjCLifetime())
1508 Qualifiers Qs = type.getQualifiers();
1509 Qs.removeObjCLifetime();
1510 return getQualifiedType(type.getUnqualifiedType(), Qs);
1513 DeclarationNameInfo getNameForTemplate(TemplateName Name,
1514 SourceLocation NameLoc) const;
1516 TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin,
1517 UnresolvedSetIterator End) const;
1519 TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
1520 bool TemplateKeyword,
1521 TemplateDecl *Template) const;
1523 TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1524 const IdentifierInfo *Name) const;
1525 TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1526 OverloadedOperatorKind Operator) const;
1527 TemplateName getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
1528 TemplateName replacement) const;
1529 TemplateName getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
1530 const TemplateArgument &ArgPack) const;
1532 enum GetBuiltinTypeError {
1533 GE_None, ///< No error
1534 GE_Missing_stdio, ///< Missing a type from <stdio.h>
1535 GE_Missing_setjmp, ///< Missing a type from <setjmp.h>
1536 GE_Missing_ucontext ///< Missing a type from <ucontext.h>
1539 /// \brief Return the type for the specified builtin.
1541 /// If \p IntegerConstantArgs is non-null, it is filled in with a bitmask of
1542 /// arguments to the builtin that are required to be integer constant
1544 QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error,
1545 unsigned *IntegerConstantArgs = 0) const;
1548 CanQualType getFromTargetType(unsigned Type) const;
1549 std::pair<uint64_t, unsigned> getTypeInfoImpl(const Type *T) const;
1551 //===--------------------------------------------------------------------===//
1553 //===--------------------------------------------------------------------===//
1556 /// \brief Return one of the GCNone, Weak or Strong Objective-C garbage
1557 /// collection attributes.
1558 Qualifiers::GC getObjCGCAttrKind(QualType Ty) const;
1560 /// \brief Return true if the given vector types are of the same unqualified
1561 /// type or if they are equivalent to the same GCC vector type.
1563 /// \note This ignores whether they are target-specific (AltiVec or Neon)
1565 bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec);
1567 /// \brief Return true if this is an \c NSObject object with its \c NSObject
1569 static bool isObjCNSObjectType(QualType Ty) {
1570 return Ty->isObjCNSObjectType();
1573 //===--------------------------------------------------------------------===//
1574 // Type Sizing and Analysis
1575 //===--------------------------------------------------------------------===//
1577 /// \brief Return the APFloat 'semantics' for the specified scalar floating
1579 const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
1581 /// \brief Get the size and alignment of the specified complete type in bits.
1582 std::pair<uint64_t, unsigned> getTypeInfo(const Type *T) const;
1583 std::pair<uint64_t, unsigned> getTypeInfo(QualType T) const {
1584 return getTypeInfo(T.getTypePtr());
1587 /// \brief Return the size of the specified (complete) type \p T, in bits.
1588 uint64_t getTypeSize(QualType T) const {
1589 return getTypeInfo(T).first;
1591 uint64_t getTypeSize(const Type *T) const {
1592 return getTypeInfo(T).first;
1595 /// \brief Return the size of the character type, in bits.
1596 uint64_t getCharWidth() const {
1597 return getTypeSize(CharTy);
1600 /// \brief Convert a size in bits to a size in characters.
1601 CharUnits toCharUnitsFromBits(int64_t BitSize) const;
1603 /// \brief Convert a size in characters to a size in bits.
1604 int64_t toBits(CharUnits CharSize) const;
1606 /// \brief Return the size of the specified (complete) type \p T, in
1608 CharUnits getTypeSizeInChars(QualType T) const;
1609 CharUnits getTypeSizeInChars(const Type *T) const;
1611 /// \brief Return the ABI-specified alignment of a (complete) type \p T, in
1613 unsigned getTypeAlign(QualType T) const {
1614 return getTypeInfo(T).second;
1616 unsigned getTypeAlign(const Type *T) const {
1617 return getTypeInfo(T).second;
1620 /// \brief Return the ABI-specified alignment of a (complete) type \p T, in
1622 CharUnits getTypeAlignInChars(QualType T) const;
1623 CharUnits getTypeAlignInChars(const Type *T) const;
1625 // getTypeInfoDataSizeInChars - Return the size of a type, in chars. If the
1626 // type is a record, its data size is returned.
1627 std::pair<CharUnits, CharUnits> getTypeInfoDataSizeInChars(QualType T) const;
1629 std::pair<CharUnits, CharUnits> getTypeInfoInChars(const Type *T) const;
1630 std::pair<CharUnits, CharUnits> getTypeInfoInChars(QualType T) const;
1632 /// \brief Return the "preferred" alignment of the specified type \p T for
1633 /// the current target, in bits.
1635 /// This can be different than the ABI alignment in cases where it is
1636 /// beneficial for performance to overalign a data type.
1637 unsigned getPreferredTypeAlign(const Type *T) const;
1639 /// \brief Return the alignment in bits that should be given to a
1640 /// global variable with type \p T.
1641 unsigned getAlignOfGlobalVar(QualType T) const;
1643 /// \brief Return the alignment in characters that should be given to a
1644 /// global variable with type \p T.
1645 CharUnits getAlignOfGlobalVarInChars(QualType T) const;
1647 /// \brief Return a conservative estimate of the alignment of the specified
1650 /// \pre \p D must not be a bitfield type, as bitfields do not have a valid
1653 /// If \p ForAlignof, references are treated like their underlying type
1654 /// and large arrays don't get any special treatment. If not \p ForAlignof
1655 /// it computes the value expected by CodeGen: references are treated like
1656 /// pointers and large arrays get extra alignment.
1657 CharUnits getDeclAlign(const Decl *D, bool ForAlignof = false) const;
1659 /// \brief Get or compute information about the layout of the specified
1660 /// record (struct/union/class) \p D, which indicates its size and field
1661 /// position information.
1662 const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D) const;
1663 const ASTRecordLayout *BuildMicrosoftASTRecordLayout(const RecordDecl *D) const;
1665 /// \brief Get or compute information about the layout of the specified
1666 /// Objective-C interface.
1667 const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D)
1670 void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS,
1671 bool Simple = false) const;
1673 /// \brief Get or compute information about the layout of the specified
1674 /// Objective-C implementation.
1676 /// This may differ from the interface if synthesized ivars are present.
1677 const ASTRecordLayout &
1678 getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const;
1680 /// \brief Get our current best idea for the key function of the
1681 /// given record decl, or NULL if there isn't one.
1683 /// The key function is, according to the Itanium C++ ABI section 5.2.3:
1684 /// ...the first non-pure virtual function that is not inline at the
1685 /// point of class definition.
1687 /// Other ABIs use the same idea. However, the ARM C++ ABI ignores
1688 /// virtual functions that are defined 'inline', which means that
1689 /// the result of this computation can change.
1690 const CXXMethodDecl *getCurrentKeyFunction(const CXXRecordDecl *RD);
1692 /// \brief Observe that the given method cannot be a key function.
1693 /// Checks the key-function cache for the method's class and clears it
1694 /// if matches the given declaration.
1696 /// This is used in ABIs where out-of-line definitions marked
1697 /// inline are not considered to be key functions.
1699 /// \param method should be the declaration from the class definition
1700 void setNonKeyFunction(const CXXMethodDecl *method);
1702 /// Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
1703 uint64_t getFieldOffset(const ValueDecl *FD) const;
1705 bool isNearlyEmpty(const CXXRecordDecl *RD) const;
1707 MangleContext *createMangleContext();
1709 void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass,
1710 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const;
1712 unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const;
1713 void CollectInheritedProtocols(const Decl *CDecl,
1714 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols);
1716 //===--------------------------------------------------------------------===//
1718 //===--------------------------------------------------------------------===//
1720 /// \brief Return the canonical (structural) type corresponding to the
1721 /// specified potentially non-canonical type \p T.
1723 /// The non-canonical version of a type may have many "decorated" versions of
1724 /// types. Decorators can include typedefs, 'typeof' operators, etc. The
1725 /// returned type is guaranteed to be free of any of these, allowing two
1726 /// canonical types to be compared for exact equality with a simple pointer
1728 CanQualType getCanonicalType(QualType T) const {
1729 return CanQualType::CreateUnsafe(T.getCanonicalType());
1732 const Type *getCanonicalType(const Type *T) const {
1733 return T->getCanonicalTypeInternal().getTypePtr();
1736 /// \brief Return the canonical parameter type corresponding to the specific
1737 /// potentially non-canonical one.
1739 /// Qualifiers are stripped off, functions are turned into function
1740 /// pointers, and arrays decay one level into pointers.
1741 CanQualType getCanonicalParamType(QualType T) const;
1743 /// \brief Determine whether the given types \p T1 and \p T2 are equivalent.
1744 bool hasSameType(QualType T1, QualType T2) const {
1745 return getCanonicalType(T1) == getCanonicalType(T2);
1748 /// \brief Return this type as a completely-unqualified array type,
1749 /// capturing the qualifiers in \p Quals.
1751 /// This will remove the minimal amount of sugaring from the types, similar
1752 /// to the behavior of QualType::getUnqualifiedType().
1754 /// \param T is the qualified type, which may be an ArrayType
1756 /// \param Quals will receive the full set of qualifiers that were
1757 /// applied to the array.
1759 /// \returns if this is an array type, the completely unqualified array type
1760 /// that corresponds to it. Otherwise, returns T.getUnqualifiedType().
1761 QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals);
1763 /// \brief Determine whether the given types are equivalent after
1764 /// cvr-qualifiers have been removed.
1765 bool hasSameUnqualifiedType(QualType T1, QualType T2) const {
1766 return getCanonicalType(T1).getTypePtr() ==
1767 getCanonicalType(T2).getTypePtr();
1770 bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
1771 const ObjCMethodDecl *MethodImp);
1773 bool UnwrapSimilarPointerTypes(QualType &T1, QualType &T2);
1775 /// \brief Retrieves the "canonical" nested name specifier for a
1776 /// given nested name specifier.
1778 /// The canonical nested name specifier is a nested name specifier
1779 /// that uniquely identifies a type or namespace within the type
1780 /// system. For example, given:
1785 /// template<typename T> struct X { typename T* type; };
1789 /// template<typename T> struct Y {
1790 /// typename N::S::X<T>::type member;
1794 /// Here, the nested-name-specifier for N::S::X<T>:: will be
1795 /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined
1796 /// by declarations in the type system and the canonical type for
1797 /// the template type parameter 'T' is template-param-0-0.
1798 NestedNameSpecifier *
1799 getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const;
1801 /// \brief Retrieves the default calling convention for the current target.
1802 CallingConv getDefaultCallingConvention(bool isVariadic,
1803 bool IsCXXMethod) const;
1805 /// \brief Retrieves the "canonical" template name that refers to a
1808 /// The canonical template name is the simplest expression that can
1809 /// be used to refer to a given template. For most templates, this
1810 /// expression is just the template declaration itself. For example,
1811 /// the template std::vector can be referred to via a variety of
1812 /// names---std::vector, \::std::vector, vector (if vector is in
1813 /// scope), etc.---but all of these names map down to the same
1814 /// TemplateDecl, which is used to form the canonical template name.
1816 /// Dependent template names are more interesting. Here, the
1817 /// template name could be something like T::template apply or
1818 /// std::allocator<T>::template rebind, where the nested name
1819 /// specifier itself is dependent. In this case, the canonical
1820 /// template name uses the shortest form of the dependent
1821 /// nested-name-specifier, which itself contains all canonical
1822 /// types, values, and templates.
1823 TemplateName getCanonicalTemplateName(TemplateName Name) const;
1825 /// \brief Determine whether the given template names refer to the same
1827 bool hasSameTemplateName(TemplateName X, TemplateName Y);
1829 /// \brief Retrieve the "canonical" template argument.
1831 /// The canonical template argument is the simplest template argument
1832 /// (which may be a type, value, expression, or declaration) that
1833 /// expresses the value of the argument.
1834 TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg)
1837 /// Type Query functions. If the type is an instance of the specified class,
1838 /// return the Type pointer for the underlying maximally pretty type. This
1839 /// is a member of ASTContext because this may need to do some amount of
1840 /// canonicalization, e.g. to move type qualifiers into the element type.
1841 const ArrayType *getAsArrayType(QualType T) const;
1842 const ConstantArrayType *getAsConstantArrayType(QualType T) const {
1843 return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T));
1845 const VariableArrayType *getAsVariableArrayType(QualType T) const {
1846 return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T));
1848 const IncompleteArrayType *getAsIncompleteArrayType(QualType T) const {
1849 return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
1851 const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T)
1853 return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T));
1856 /// \brief Return the innermost element type of an array type.
1858 /// For example, will return "int" for int[m][n]
1859 QualType getBaseElementType(const ArrayType *VAT) const;
1861 /// \brief Return the innermost element type of a type (which needn't
1862 /// actually be an array type).
1863 QualType getBaseElementType(QualType QT) const;
1865 /// \brief Return number of constant array elements.
1866 uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const;
1868 /// \brief Perform adjustment on the parameter type of a function.
1870 /// This routine adjusts the given parameter type @p T to the actual
1871 /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
1872 /// C++ [dcl.fct]p3). The adjusted parameter type is returned.
1873 QualType getAdjustedParameterType(QualType T) const;
1875 /// \brief Retrieve the parameter type as adjusted for use in the signature
1876 /// of a function, decaying array and function types and removing top-level
1878 QualType getSignatureParameterType(QualType T) const;
1880 /// \brief Return the properly qualified result of decaying the specified
1881 /// array type to a pointer.
1883 /// This operation is non-trivial when handling typedefs etc. The canonical
1884 /// type of \p T must be an array type, this returns a pointer to a properly
1885 /// qualified element of the array.
1887 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
1888 QualType getArrayDecayedType(QualType T) const;
1890 /// \brief Return the type that \p PromotableType will promote to: C99
1891 /// 6.3.1.1p2, assuming that \p PromotableType is a promotable integer type.
1892 QualType getPromotedIntegerType(QualType PromotableType) const;
1894 /// \brief Recurses in pointer/array types until it finds an Objective-C
1895 /// retainable type and returns its ownership.
1896 Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const;
1898 /// \brief Whether this is a promotable bitfield reference according
1899 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
1901 /// \returns the type this bit-field will promote to, or NULL if no
1902 /// promotion occurs.
1903 QualType isPromotableBitField(Expr *E) const;
1905 /// \brief Return the highest ranked integer type, see C99 6.3.1.8p1.
1907 /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
1908 /// \p LHS < \p RHS, return -1.
1909 int getIntegerTypeOrder(QualType LHS, QualType RHS) const;
1911 /// \brief Compare the rank of the two specified floating point types,
1912 /// ignoring the domain of the type (i.e. 'double' == '_Complex double').
1914 /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
1915 /// \p LHS < \p RHS, return -1.
1916 int getFloatingTypeOrder(QualType LHS, QualType RHS) const;
1918 /// \brief Return a real floating point or a complex type (based on
1919 /// \p typeDomain/\p typeSize).
1921 /// \param typeDomain a real floating point or complex type.
1922 /// \param typeSize a real floating point or complex type.
1923 QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
1924 QualType typeDomain) const;
1926 unsigned getTargetAddressSpace(QualType T) const {
1927 return getTargetAddressSpace(T.getQualifiers());
1930 unsigned getTargetAddressSpace(Qualifiers Q) const {
1931 return getTargetAddressSpace(Q.getAddressSpace());
1934 unsigned getTargetAddressSpace(unsigned AS) const {
1935 if (AS < LangAS::Offset || AS >= LangAS::Offset + LangAS::Count)
1938 return (*AddrSpaceMap)[AS - LangAS::Offset];
1941 bool addressSpaceMapManglingFor(unsigned AS) const {
1942 return AddrSpaceMapMangling ||
1943 AS < LangAS::Offset ||
1944 AS >= LangAS::Offset + LangAS::Count;
1948 // Helper for integer ordering
1949 unsigned getIntegerRank(const Type *T) const;
1953 //===--------------------------------------------------------------------===//
1954 // Type Compatibility Predicates
1955 //===--------------------------------------------------------------------===//
1957 /// Compatibility predicates used to check assignment expressions.
1958 bool typesAreCompatible(QualType T1, QualType T2,
1959 bool CompareUnqualified = false); // C99 6.2.7p1
1961 bool propertyTypesAreCompatible(QualType, QualType);
1962 bool typesAreBlockPointerCompatible(QualType, QualType);
1964 bool isObjCIdType(QualType T) const {
1965 return T == getObjCIdType();
1967 bool isObjCClassType(QualType T) const {
1968 return T == getObjCClassType();
1970 bool isObjCSelType(QualType T) const {
1971 return T == getObjCSelType();
1973 bool ObjCQualifiedIdTypesAreCompatible(QualType LHS, QualType RHS,
1976 bool ObjCQualifiedClassTypesAreCompatible(QualType LHS, QualType RHS);
1978 // Check the safety of assignment from LHS to RHS
1979 bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
1980 const ObjCObjectPointerType *RHSOPT);
1981 bool canAssignObjCInterfaces(const ObjCObjectType *LHS,
1982 const ObjCObjectType *RHS);
1983 bool canAssignObjCInterfacesInBlockPointer(
1984 const ObjCObjectPointerType *LHSOPT,
1985 const ObjCObjectPointerType *RHSOPT,
1986 bool BlockReturnType);
1987 bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
1988 QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT,
1989 const ObjCObjectPointerType *RHSOPT);
1990 bool canBindObjCObjectType(QualType To, QualType From);
1992 // Functions for calculating composite types
1993 QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false,
1994 bool Unqualified = false, bool BlockReturnType = false);
1995 QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false,
1996 bool Unqualified = false);
1997 QualType mergeFunctionArgumentTypes(QualType, QualType,
1998 bool OfBlockPointer=false,
1999 bool Unqualified = false);
2000 QualType mergeTransparentUnionType(QualType, QualType,
2001 bool OfBlockPointer=false,
2002 bool Unqualified = false);
2004 QualType mergeObjCGCQualifiers(QualType, QualType);
2006 bool FunctionTypesMatchOnNSConsumedAttrs(
2007 const FunctionProtoType *FromFunctionType,
2008 const FunctionProtoType *ToFunctionType);
2010 void ResetObjCLayout(const ObjCContainerDecl *CD) {
2011 ObjCLayouts[CD] = 0;
2014 //===--------------------------------------------------------------------===//
2015 // Integer Predicates
2016 //===--------------------------------------------------------------------===//
2018 // The width of an integer, as defined in C99 6.2.6.2. This is the number
2019 // of bits in an integer type excluding any padding bits.
2020 unsigned getIntWidth(QualType T) const;
2022 // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
2023 // unsigned integer type. This method takes a signed type, and returns the
2024 // corresponding unsigned integer type.
2025 QualType getCorrespondingUnsignedType(QualType T) const;
2027 //===--------------------------------------------------------------------===//
2029 //===--------------------------------------------------------------------===//
2031 typedef SmallVectorImpl<Type *>::iterator type_iterator;
2032 typedef SmallVectorImpl<Type *>::const_iterator const_type_iterator;
2034 type_iterator types_begin() { return Types.begin(); }
2035 type_iterator types_end() { return Types.end(); }
2036 const_type_iterator types_begin() const { return Types.begin(); }
2037 const_type_iterator types_end() const { return Types.end(); }
2039 //===--------------------------------------------------------------------===//
2041 //===--------------------------------------------------------------------===//
2043 /// \brief Make an APSInt of the appropriate width and signedness for the
2044 /// given \p Value and integer \p Type.
2045 llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const {
2046 llvm::APSInt Res(getIntWidth(Type),
2047 !Type->isSignedIntegerOrEnumerationType());
2052 bool isSentinelNullExpr(const Expr *E);
2054 /// \brief Get the implementation of the ObjCInterfaceDecl \p D, or NULL if
2056 ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D);
2057 /// \brief Get the implementation of the ObjCCategoryDecl \p D, or NULL if
2059 ObjCCategoryImplDecl *getObjCImplementation(ObjCCategoryDecl *D);
2061 /// \brief Return true if there is at least one \@implementation in the TU.
2062 bool AnyObjCImplementation() {
2063 return !ObjCImpls.empty();
2066 /// \brief Set the implementation of ObjCInterfaceDecl.
2067 void setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2068 ObjCImplementationDecl *ImplD);
2069 /// \brief Set the implementation of ObjCCategoryDecl.
2070 void setObjCImplementation(ObjCCategoryDecl *CatD,
2071 ObjCCategoryImplDecl *ImplD);
2073 /// \brief Get the duplicate declaration of a ObjCMethod in the same
2074 /// interface, or null if none exists.
2075 const ObjCMethodDecl *getObjCMethodRedeclaration(
2076 const ObjCMethodDecl *MD) const {
2077 return ObjCMethodRedecls.lookup(MD);
2080 void setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2081 const ObjCMethodDecl *Redecl) {
2082 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2083 ObjCMethodRedecls[MD] = Redecl;
2086 /// \brief Returns the Objective-C interface that \p ND belongs to if it is
2087 /// an Objective-C method/property/ivar etc. that is part of an interface,
2088 /// otherwise returns null.
2089 const ObjCInterfaceDecl *getObjContainingInterface(const NamedDecl *ND) const;
2091 /// \brief Set the copy inialization expression of a block var decl.
2092 void setBlockVarCopyInits(VarDecl*VD, Expr* Init);
2093 /// \brief Get the copy initialization expression of the VarDecl \p VD, or
2094 /// NULL if none exists.
2095 Expr *getBlockVarCopyInits(const VarDecl* VD);
2097 /// \brief Allocate an uninitialized TypeSourceInfo.
2099 /// The caller should initialize the memory held by TypeSourceInfo using
2100 /// the TypeLoc wrappers.
2102 /// \param T the type that will be the basis for type source info. This type
2103 /// should refer to how the declarator was written in source code, not to
2104 /// what type semantic analysis resolved the declarator to.
2106 /// \param Size the size of the type info to create, or 0 if the size
2107 /// should be calculated based on the type.
2108 TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0) const;
2110 /// \brief Allocate a TypeSourceInfo where all locations have been
2111 /// initialized to a given location, which defaults to the empty
2114 getTrivialTypeSourceInfo(QualType T,
2115 SourceLocation Loc = SourceLocation()) const;
2117 TypeSourceInfo *getNullTypeSourceInfo() { return &NullTypeSourceInfo; }
2119 /// \brief Add a deallocation callback that will be invoked when the
2120 /// ASTContext is destroyed.
2122 /// \param Callback A callback function that will be invoked on destruction.
2124 /// \param Data Pointer data that will be provided to the callback function
2125 /// when it is called.
2126 void AddDeallocation(void (*Callback)(void*), void *Data);
2128 GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD);
2129 GVALinkage GetGVALinkageForVariable(const VarDecl *VD);
2131 /// \brief Determines if the decl can be CodeGen'ed or deserialized from PCH
2132 /// lazily, only when used; this is only relevant for function or file scoped
2133 /// var definitions.
2135 /// \returns true if the function/var must be CodeGen'ed/deserialized even if
2137 bool DeclMustBeEmitted(const Decl *D);
2139 void setManglingNumber(const NamedDecl *ND, unsigned Number);
2140 unsigned getManglingNumber(const NamedDecl *ND) const;
2142 /// \brief Retrieve the context for computing mangling numbers in the given
2144 MangleNumberingContext &getManglingNumberContext(const DeclContext *DC);
2146 MangleNumberingContext *createMangleNumberingContext() const;
2148 /// \brief Used by ParmVarDecl to store on the side the
2149 /// index of the parameter when it exceeds the size of the normal bitfield.
2150 void setParameterIndex(const ParmVarDecl *D, unsigned index);
2152 /// \brief Used by ParmVarDecl to retrieve on the side the
2153 /// index of the parameter when it exceeds the size of the normal bitfield.
2154 unsigned getParameterIndex(const ParmVarDecl *D) const;
2156 /// \brief Get the storage for the constant value of a materialized temporary
2157 /// of static storage duration.
2158 APValue *getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
2161 //===--------------------------------------------------------------------===//
2163 //===--------------------------------------------------------------------===//
2165 /// \brief The number of implicitly-declared default constructors.
2166 static unsigned NumImplicitDefaultConstructors;
2168 /// \brief The number of implicitly-declared default constructors for
2169 /// which declarations were built.
2170 static unsigned NumImplicitDefaultConstructorsDeclared;
2172 /// \brief The number of implicitly-declared copy constructors.
2173 static unsigned NumImplicitCopyConstructors;
2175 /// \brief The number of implicitly-declared copy constructors for
2176 /// which declarations were built.
2177 static unsigned NumImplicitCopyConstructorsDeclared;
2179 /// \brief The number of implicitly-declared move constructors.
2180 static unsigned NumImplicitMoveConstructors;
2182 /// \brief The number of implicitly-declared move constructors for
2183 /// which declarations were built.
2184 static unsigned NumImplicitMoveConstructorsDeclared;
2186 /// \brief The number of implicitly-declared copy assignment operators.
2187 static unsigned NumImplicitCopyAssignmentOperators;
2189 /// \brief The number of implicitly-declared copy assignment operators for
2190 /// which declarations were built.
2191 static unsigned NumImplicitCopyAssignmentOperatorsDeclared;
2193 /// \brief The number of implicitly-declared move assignment operators.
2194 static unsigned NumImplicitMoveAssignmentOperators;
2196 /// \brief The number of implicitly-declared move assignment operators for
2197 /// which declarations were built.
2198 static unsigned NumImplicitMoveAssignmentOperatorsDeclared;
2200 /// \brief The number of implicitly-declared destructors.
2201 static unsigned NumImplicitDestructors;
2203 /// \brief The number of implicitly-declared destructors for which
2204 /// declarations were built.
2205 static unsigned NumImplicitDestructorsDeclared;
2208 ASTContext(const ASTContext &) LLVM_DELETED_FUNCTION;
2209 void operator=(const ASTContext &) LLVM_DELETED_FUNCTION;
2212 /// \brief Initialize built-in types.
2214 /// This routine may only be invoked once for a given ASTContext object.
2215 /// It is normally invoked by the ASTContext constructor. However, the
2216 /// constructor can be asked to delay initialization, which places the burden
2217 /// of calling this function on the user of that object.
2219 /// \param Target The target
2220 void InitBuiltinTypes(const TargetInfo &Target);
2223 void InitBuiltinType(CanQualType &R, BuiltinType::Kind K);
2225 // Return the Objective-C type encoding for a given type.
2226 void getObjCEncodingForTypeImpl(QualType t, std::string &S,
2227 bool ExpandPointedToStructures,
2228 bool ExpandStructures,
2229 const FieldDecl *Field,
2230 bool OutermostType = false,
2231 bool EncodingProperty = false,
2232 bool StructField = false,
2233 bool EncodeBlockParameters = false,
2234 bool EncodeClassNames = false,
2235 bool EncodePointerToObjCTypedef = false) const;
2237 // Adds the encoding of the structure's members.
2238 void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S,
2239 const FieldDecl *Field,
2240 bool includeVBases = true) const;
2242 // Adds the encoding of a method parameter or return type.
2243 void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
2244 QualType T, std::string& S,
2245 bool Extended) const;
2247 const ASTRecordLayout &
2248 getObjCLayout(const ObjCInterfaceDecl *D,
2249 const ObjCImplementationDecl *Impl) const;
2252 /// \brief A set of deallocations that should be performed when the
2253 /// ASTContext is destroyed.
2254 typedef llvm::SmallDenseMap<void(*)(void*), llvm::SmallVector<void*, 16> >
2256 DeallocationMap Deallocations;
2258 // FIXME: This currently contains the set of StoredDeclMaps used
2259 // by DeclContext objects. This probably should not be in ASTContext,
2260 // but we include it here so that ASTContext can quickly deallocate them.
2261 llvm::PointerIntPair<StoredDeclsMap*,1> LastSDM;
2263 friend class DeclContext;
2264 friend class DeclarationNameTable;
2265 void ReleaseDeclContextMaps();
2267 llvm::OwningPtr<ParentMap> AllParents;
2270 /// \brief Utility function for constructing a nullary selector.
2271 static inline Selector GetNullarySelector(StringRef name, ASTContext& Ctx) {
2272 IdentifierInfo* II = &Ctx.Idents.get(name);
2273 return Ctx.Selectors.getSelector(0, &II);
2276 /// \brief Utility function for constructing an unary selector.
2277 static inline Selector GetUnarySelector(StringRef name, ASTContext& Ctx) {
2278 IdentifierInfo* II = &Ctx.Idents.get(name);
2279 return Ctx.Selectors.getSelector(1, &II);
2282 } // end namespace clang
2284 // operator new and delete aren't allowed inside namespaces.
2286 /// @brief Placement new for using the ASTContext's allocator.
2288 /// This placement form of operator new uses the ASTContext's allocator for
2289 /// obtaining memory.
2291 /// IMPORTANT: These are also declared in clang/AST/AttrIterator.h! Any changes
2292 /// here need to also be made there.
2294 /// We intentionally avoid using a nothrow specification here so that the calls
2295 /// to this operator will not perform a null check on the result -- the
2296 /// underlying allocator never returns null pointers.
2298 /// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
2300 /// // Default alignment (8)
2301 /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
2302 /// // Specific alignment
2303 /// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
2305 /// Please note that you cannot use delete on the pointer; it must be
2306 /// deallocated using an explicit destructor call followed by
2307 /// @c Context.Deallocate(Ptr).
2309 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
2310 /// @param C The ASTContext that provides the allocator.
2311 /// @param Alignment The alignment of the allocated memory (if the underlying
2312 /// allocator supports it).
2313 /// @return The allocated memory. Could be NULL.
2314 inline void *operator new(size_t Bytes, const clang::ASTContext &C,
2316 return C.Allocate(Bytes, Alignment);
2318 /// @brief Placement delete companion to the new above.
2320 /// This operator is just a companion to the new above. There is no way of
2321 /// invoking it directly; see the new operator for more details. This operator
2322 /// is called implicitly by the compiler if a placement new expression using
2323 /// the ASTContext throws in the object constructor.
2324 inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t) {
2328 /// This placement form of operator new[] uses the ASTContext's allocator for
2329 /// obtaining memory.
2331 /// We intentionally avoid using a nothrow specification here so that the calls
2332 /// to this operator will not perform a null check on the result -- the
2333 /// underlying allocator never returns null pointers.
2335 /// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
2337 /// // Default alignment (8)
2338 /// char *data = new (Context) char[10];
2339 /// // Specific alignment
2340 /// char *data = new (Context, 4) char[10];
2342 /// Please note that you cannot use delete on the pointer; it must be
2343 /// deallocated using an explicit destructor call followed by
2344 /// @c Context.Deallocate(Ptr).
2346 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
2347 /// @param C The ASTContext that provides the allocator.
2348 /// @param Alignment The alignment of the allocated memory (if the underlying
2349 /// allocator supports it).
2350 /// @return The allocated memory. Could be NULL.
2351 inline void *operator new[](size_t Bytes, const clang::ASTContext& C,
2352 size_t Alignment = 8) {
2353 return C.Allocate(Bytes, Alignment);
2356 /// @brief Placement delete[] companion to the new[] above.
2358 /// This operator is just a companion to the new[] above. There is no way of
2359 /// invoking it directly; see the new[] operator for more details. This operator
2360 /// is called implicitly by the compiler if a placement new[] expression using
2361 /// the ASTContext throws in the object constructor.
2362 inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_t) {