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/Module.h"
32 #include "clang/Basic/OperatorKinds.h"
33 #include "clang/Basic/PartialDiagnostic.h"
34 #include "clang/Basic/SanitizerBlacklist.h"
35 #include "clang/Basic/VersionTuple.h"
36 #include "llvm/ADT/DenseMap.h"
37 #include "llvm/ADT/FoldingSet.h"
38 #include "llvm/ADT/IntrusiveRefCntPtr.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/TinyPtrVector.h"
41 #include "llvm/Support/Allocator.h"
52 class ASTRecordLayout;
55 class DiagnosticsEngine;
57 class ASTMutationListener;
58 class IdentifierTable;
59 class MaterializeTemporaryExpr;
63 class MangleNumberingContext;
67 class ObjCPropertyDecl;
68 class UnresolvedSetIterator;
70 class UsingShadowDecl;
71 class VTableContextBase;
73 namespace Builtin { class Context; }
74 enum BuiltinTemplateKind : int;
83 bool AlignIsRequired : 1;
84 TypeInfo() : Width(0), Align(0), AlignIsRequired(false) {}
85 TypeInfo(uint64_t Width, unsigned Align, bool AlignIsRequired)
86 : Width(Width), Align(Align), AlignIsRequired(AlignIsRequired) {}
89 /// \brief Holds long-lived AST nodes (such as types and decls) that can be
90 /// referred to throughout the semantic analysis of a file.
91 class ASTContext : public RefCountedBase<ASTContext> {
92 ASTContext &this_() { return *this; }
94 mutable SmallVector<Type *, 0> Types;
95 mutable llvm::FoldingSet<ExtQuals> ExtQualNodes;
96 mutable llvm::FoldingSet<ComplexType> ComplexTypes;
97 mutable llvm::FoldingSet<PointerType> PointerTypes;
98 mutable llvm::FoldingSet<AdjustedType> AdjustedTypes;
99 mutable llvm::FoldingSet<BlockPointerType> BlockPointerTypes;
100 mutable llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes;
101 mutable llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes;
102 mutable llvm::FoldingSet<MemberPointerType> MemberPointerTypes;
103 mutable llvm::FoldingSet<ConstantArrayType> ConstantArrayTypes;
104 mutable llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
105 mutable std::vector<VariableArrayType*> VariableArrayTypes;
106 mutable llvm::FoldingSet<DependentSizedArrayType> DependentSizedArrayTypes;
107 mutable llvm::FoldingSet<DependentSizedExtVectorType>
108 DependentSizedExtVectorTypes;
109 mutable llvm::FoldingSet<VectorType> VectorTypes;
110 mutable llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes;
111 mutable llvm::ContextualFoldingSet<FunctionProtoType, ASTContext&>
113 mutable llvm::FoldingSet<DependentTypeOfExprType> DependentTypeOfExprTypes;
114 mutable llvm::FoldingSet<DependentDecltypeType> DependentDecltypeTypes;
115 mutable llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes;
116 mutable llvm::FoldingSet<SubstTemplateTypeParmType>
117 SubstTemplateTypeParmTypes;
118 mutable llvm::FoldingSet<SubstTemplateTypeParmPackType>
119 SubstTemplateTypeParmPackTypes;
120 mutable llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&>
121 TemplateSpecializationTypes;
122 mutable llvm::FoldingSet<ParenType> ParenTypes;
123 mutable llvm::FoldingSet<ElaboratedType> ElaboratedTypes;
124 mutable llvm::FoldingSet<DependentNameType> DependentNameTypes;
125 mutable llvm::ContextualFoldingSet<DependentTemplateSpecializationType,
127 DependentTemplateSpecializationTypes;
128 llvm::FoldingSet<PackExpansionType> PackExpansionTypes;
129 mutable llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes;
130 mutable llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes;
131 mutable llvm::FoldingSet<AutoType> AutoTypes;
132 mutable llvm::FoldingSet<AtomicType> AtomicTypes;
133 llvm::FoldingSet<AttributedType> AttributedTypes;
135 mutable llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames;
136 mutable llvm::FoldingSet<DependentTemplateName> DependentTemplateNames;
137 mutable llvm::FoldingSet<SubstTemplateTemplateParmStorage>
138 SubstTemplateTemplateParms;
139 mutable llvm::ContextualFoldingSet<SubstTemplateTemplateParmPackStorage,
141 SubstTemplateTemplateParmPacks;
143 /// \brief The set of nested name specifiers.
145 /// This set is managed by the NestedNameSpecifier class.
146 mutable llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers;
147 mutable NestedNameSpecifier *GlobalNestedNameSpecifier;
148 friend class NestedNameSpecifier;
150 /// \brief A cache mapping from RecordDecls to ASTRecordLayouts.
152 /// This is lazily created. This is intentionally not serialized.
153 mutable llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>
155 mutable llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>
158 /// \brief A cache from types to size and alignment information.
159 typedef llvm::DenseMap<const Type *, struct TypeInfo> TypeInfoMap;
160 mutable TypeInfoMap MemoizedTypeInfo;
162 /// \brief A cache mapping from CXXRecordDecls to key functions.
163 llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr> KeyFunctions;
165 /// \brief Mapping from ObjCContainers to their ObjCImplementations.
166 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls;
168 /// \brief Mapping from ObjCMethod to its duplicate declaration in the same
170 llvm::DenseMap<const ObjCMethodDecl*,const ObjCMethodDecl*> ObjCMethodRedecls;
172 /// \brief Mapping from __block VarDecls to their copy initialization expr.
173 llvm::DenseMap<const VarDecl*, Expr*> BlockVarCopyInits;
175 /// \brief Mapping from class scope functions specialization to their
176 /// template patterns.
177 llvm::DenseMap<const FunctionDecl*, FunctionDecl*>
178 ClassScopeSpecializationPattern;
180 /// \brief Mapping from materialized temporaries with static storage duration
181 /// that appear in constant initializers to their evaluated values. These are
182 /// allocated in a std::map because their address must be stable.
183 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue *>
184 MaterializedTemporaryValues;
186 /// \brief Representation of a "canonical" template template parameter that
187 /// is used in canonical template names.
188 class CanonicalTemplateTemplateParm : public llvm::FoldingSetNode {
189 TemplateTemplateParmDecl *Parm;
192 CanonicalTemplateTemplateParm(TemplateTemplateParmDecl *Parm)
195 TemplateTemplateParmDecl *getParam() const { return Parm; }
197 void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, Parm); }
199 static void Profile(llvm::FoldingSetNodeID &ID,
200 TemplateTemplateParmDecl *Parm);
202 mutable llvm::FoldingSet<CanonicalTemplateTemplateParm>
203 CanonTemplateTemplateParms;
205 TemplateTemplateParmDecl *
206 getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const;
208 /// \brief The typedef for the __int128_t type.
209 mutable TypedefDecl *Int128Decl;
211 /// \brief The typedef for the __uint128_t type.
212 mutable TypedefDecl *UInt128Decl;
214 /// \brief The typedef for the __float128 stub type.
215 mutable TypeDecl *Float128StubDecl;
217 /// \brief The typedef for the target specific predefined
218 /// __builtin_va_list type.
219 mutable TypedefDecl *BuiltinVaListDecl;
221 /// The typedef for the predefined \c __builtin_ms_va_list type.
222 mutable TypedefDecl *BuiltinMSVaListDecl;
224 /// \brief The typedef for the predefined \c id type.
225 mutable TypedefDecl *ObjCIdDecl;
227 /// \brief The typedef for the predefined \c SEL type.
228 mutable TypedefDecl *ObjCSelDecl;
230 /// \brief The typedef for the predefined \c Class type.
231 mutable TypedefDecl *ObjCClassDecl;
233 /// \brief The typedef for the predefined \c Protocol class in Objective-C.
234 mutable ObjCInterfaceDecl *ObjCProtocolClassDecl;
236 /// \brief The typedef for the predefined 'BOOL' type.
237 mutable TypedefDecl *BOOLDecl;
239 // Typedefs which may be provided defining the structure of Objective-C
241 QualType ObjCIdRedefinitionType;
242 QualType ObjCClassRedefinitionType;
243 QualType ObjCSelRedefinitionType;
245 /// The identifier 'NSObject'.
246 IdentifierInfo *NSObjectName = nullptr;
248 /// The identifier 'NSCopying'.
249 IdentifierInfo *NSCopyingName = nullptr;
251 /// The identifier '__make_integer_seq'.
252 mutable IdentifierInfo *MakeIntegerSeqName = nullptr;
254 QualType ObjCConstantStringType;
255 mutable RecordDecl *CFConstantStringTypeDecl;
257 mutable QualType ObjCSuperType;
259 QualType ObjCNSStringType;
261 /// \brief The typedef declaration for the Objective-C "instancetype" type.
262 TypedefDecl *ObjCInstanceTypeDecl;
264 /// \brief The type for the C FILE type.
267 /// \brief The type for the C jmp_buf type.
268 TypeDecl *jmp_bufDecl;
270 /// \brief The type for the C sigjmp_buf type.
271 TypeDecl *sigjmp_bufDecl;
273 /// \brief The type for the C ucontext_t type.
274 TypeDecl *ucontext_tDecl;
276 /// \brief Type for the Block descriptor for Blocks CodeGen.
278 /// Since this is only used for generation of debug info, it is not
280 mutable RecordDecl *BlockDescriptorType;
282 /// \brief Type for the Block descriptor for Blocks CodeGen.
284 /// Since this is only used for generation of debug info, it is not
286 mutable RecordDecl *BlockDescriptorExtendedType;
288 /// \brief Declaration for the CUDA cudaConfigureCall function.
289 FunctionDecl *cudaConfigureCallDecl;
291 /// \brief Keeps track of all declaration attributes.
293 /// Since so few decls have attrs, we keep them in a hash map instead of
294 /// wasting space in the Decl class.
295 llvm::DenseMap<const Decl*, AttrVec*> DeclAttrs;
297 /// \brief A mapping from non-redeclarable declarations in modules that were
298 /// merged with other declarations to the canonical declaration that they were
300 llvm::DenseMap<Decl*, Decl*> MergedDecls;
302 /// \brief A mapping from a defining declaration to a list of modules (other
303 /// than the owning module of the declaration) that contain merged
304 /// definitions of that entity.
305 llvm::DenseMap<NamedDecl*, llvm::TinyPtrVector<Module*>> MergedDefModules;
308 /// \brief A type synonym for the TemplateOrInstantiation mapping.
309 typedef llvm::PointerUnion<VarTemplateDecl *, MemberSpecializationInfo *>
310 TemplateOrSpecializationInfo;
314 /// \brief A mapping to contain the template or declaration that
315 /// a variable declaration describes or was instantiated from,
318 /// For non-templates, this value will be NULL. For variable
319 /// declarations that describe a variable template, this will be a
320 /// pointer to a VarTemplateDecl. For static data members
321 /// of class template specializations, this will be the
322 /// MemberSpecializationInfo referring to the member variable that was
323 /// instantiated or specialized. Thus, the mapping will keep track of
324 /// the static data member templates from which static data members of
325 /// class template specializations were instantiated.
327 /// Given the following example:
330 /// template<typename T>
335 /// template<typename T>
336 /// T X<T>::value = T(17);
338 /// int *x = &X<int>::value;
341 /// This mapping will contain an entry that maps from the VarDecl for
342 /// X<int>::value to the corresponding VarDecl for X<T>::value (within the
343 /// class template X) and will be marked TSK_ImplicitInstantiation.
344 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>
345 TemplateOrInstantiation;
347 /// \brief Keeps track of the declaration from which a UsingDecl was
348 /// created during instantiation.
350 /// The source declaration is always a UsingDecl, an UnresolvedUsingValueDecl,
351 /// or an UnresolvedUsingTypenameDecl.
355 /// template<typename T>
360 /// template<typename T>
361 /// struct B : A<T> {
365 /// template struct B<int>;
368 /// This mapping will contain an entry that maps from the UsingDecl in
369 /// B<int> to the UnresolvedUsingDecl in B<T>.
370 llvm::DenseMap<UsingDecl *, NamedDecl *> InstantiatedFromUsingDecl;
372 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>
373 InstantiatedFromUsingShadowDecl;
375 llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl;
377 /// \brief Mapping that stores the methods overridden by a given C++
380 /// Since most C++ member functions aren't virtual and therefore
381 /// don't override anything, we store the overridden functions in
382 /// this map on the side rather than within the CXXMethodDecl structure.
383 typedef llvm::TinyPtrVector<const CXXMethodDecl*> CXXMethodVector;
384 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector> OverriddenMethods;
386 /// \brief Mapping from each declaration context to its corresponding
387 /// mangling numbering context (used for constructs like lambdas which
388 /// need to be consistently numbered for the mangler).
389 llvm::DenseMap<const DeclContext *, MangleNumberingContext *>
390 MangleNumberingContexts;
392 /// \brief Side-table of mangling numbers for declarations which rarely
393 /// need them (like static local vars).
394 llvm::DenseMap<const NamedDecl *, unsigned> MangleNumbers;
395 llvm::DenseMap<const VarDecl *, unsigned> StaticLocalNumbers;
397 /// \brief Mapping that stores parameterIndex values for ParmVarDecls when
398 /// that value exceeds the bitfield size of ParmVarDeclBits.ParameterIndex.
399 typedef llvm::DenseMap<const VarDecl *, unsigned> ParameterIndexTable;
400 ParameterIndexTable ParamIndices;
402 ImportDecl *FirstLocalImport;
403 ImportDecl *LastLocalImport;
405 TranslationUnitDecl *TUDecl;
406 mutable ExternCContextDecl *ExternCContext;
407 mutable BuiltinTemplateDecl *MakeIntegerSeqDecl;
409 /// \brief The associated SourceManager object.a
410 SourceManager &SourceMgr;
412 /// \brief The language options used to create the AST associated with
413 /// this ASTContext object.
414 LangOptions &LangOpts;
416 /// \brief Blacklist object that is used by sanitizers to decide which
417 /// entities should not be instrumented.
418 std::unique_ptr<SanitizerBlacklist> SanitizerBL;
420 /// \brief The allocator used to create AST objects.
422 /// AST objects are never destructed; rather, all memory associated with the
423 /// AST objects will be released when the ASTContext itself is destroyed.
424 mutable llvm::BumpPtrAllocator BumpAlloc;
426 /// \brief Allocator for partial diagnostics.
427 PartialDiagnostic::StorageAllocator DiagAllocator;
429 /// \brief The current C++ ABI.
430 std::unique_ptr<CXXABI> ABI;
431 CXXABI *createCXXABI(const TargetInfo &T);
433 /// \brief The logical -> physical address space map.
434 const LangAS::Map *AddrSpaceMap;
436 /// \brief Address space map mangling must be used with language specific
437 /// address spaces (e.g. OpenCL/CUDA)
438 bool AddrSpaceMapMangling;
440 friend class ASTDeclReader;
441 friend class ASTReader;
442 friend class ASTWriter;
443 friend class CXXRecordDecl;
445 const TargetInfo *Target;
446 const TargetInfo *AuxTarget;
447 clang::PrintingPolicy PrintingPolicy;
450 IdentifierTable &Idents;
451 SelectorTable &Selectors;
452 Builtin::Context &BuiltinInfo;
453 mutable DeclarationNameTable DeclarationNames;
454 IntrusiveRefCntPtr<ExternalASTSource> ExternalSource;
455 ASTMutationListener *Listener;
457 /// \brief Contains parents of a node.
458 typedef llvm::SmallVector<ast_type_traits::DynTypedNode, 2> ParentVector;
460 /// \brief Maps from a node to its parents. This is used for nodes that have
461 /// pointer identity only, which are more common and we can save space by
462 /// only storing a unique pointer to them.
463 typedef llvm::DenseMap<const void *,
464 llvm::PointerUnion4<const Decl *, const Stmt *,
465 ast_type_traits::DynTypedNode *,
466 ParentVector *>> ParentMapPointers;
468 /// Parent map for nodes without pointer identity. We store a full
469 /// DynTypedNode for all keys.
470 typedef llvm::DenseMap<
471 ast_type_traits::DynTypedNode,
472 llvm::PointerUnion4<const Decl *, const Stmt *,
473 ast_type_traits::DynTypedNode *, ParentVector *>>
476 /// Container for either a single DynTypedNode or for an ArrayRef to
477 /// DynTypedNode. For use with ParentMap.
478 class DynTypedNodeList {
479 typedef ast_type_traits::DynTypedNode DynTypedNode;
480 llvm::AlignedCharArrayUnion<ast_type_traits::DynTypedNode,
481 ArrayRef<DynTypedNode>> Storage;
485 DynTypedNodeList(const DynTypedNode &N) : IsSingleNode(true) {
486 new (Storage.buffer) DynTypedNode(N);
488 DynTypedNodeList(ArrayRef<DynTypedNode> A) : IsSingleNode(false) {
489 new (Storage.buffer) ArrayRef<DynTypedNode>(A);
492 const ast_type_traits::DynTypedNode *begin() const {
494 return reinterpret_cast<const ArrayRef<DynTypedNode> *>(Storage.buffer)
496 return reinterpret_cast<const DynTypedNode *>(Storage.buffer);
499 const ast_type_traits::DynTypedNode *end() const {
501 return reinterpret_cast<const ArrayRef<DynTypedNode> *>(Storage.buffer)
503 return reinterpret_cast<const DynTypedNode *>(Storage.buffer) + 1;
506 size_t size() const { return end() - begin(); }
507 bool empty() const { return begin() == end(); }
508 const DynTypedNode &operator[](size_t N) const {
509 assert(N < size() && "Out of bounds!");
510 return *(begin() + N);
514 /// \brief Returns the parents of the given node.
516 /// Note that this will lazily compute the parents of all nodes
517 /// and store them for later retrieval. Thus, the first call is O(n)
518 /// in the number of AST nodes.
520 /// Caveats and FIXMEs:
521 /// Calculating the parent map over all AST nodes will need to load the
522 /// full AST. This can be undesirable in the case where the full AST is
523 /// expensive to create (for example, when using precompiled header
524 /// preambles). Thus, there are good opportunities for optimization here.
525 /// One idea is to walk the given node downwards, looking for references
526 /// to declaration contexts - once a declaration context is found, compute
527 /// the parent map for the declaration context; if that can satisfy the
528 /// request, loading the whole AST can be avoided. Note that this is made
529 /// more complex by statements in templates having multiple parents - those
530 /// problems can be solved by building closure over the templated parts of
531 /// the AST, which also avoids touching large parts of the AST.
532 /// Additionally, we will want to add an interface to already give a hint
533 /// where to search for the parents, for example when looking at a statement
534 /// inside a certain function.
536 /// 'NodeT' can be one of Decl, Stmt, Type, TypeLoc,
537 /// NestedNameSpecifier or NestedNameSpecifierLoc.
538 template <typename NodeT> DynTypedNodeList getParents(const NodeT &Node) {
539 return getParents(ast_type_traits::DynTypedNode::create(Node));
542 DynTypedNodeList getParents(const ast_type_traits::DynTypedNode &Node);
544 const clang::PrintingPolicy &getPrintingPolicy() const {
545 return PrintingPolicy;
548 void setPrintingPolicy(const clang::PrintingPolicy &Policy) {
549 PrintingPolicy = Policy;
552 SourceManager& getSourceManager() { return SourceMgr; }
553 const SourceManager& getSourceManager() const { return SourceMgr; }
555 llvm::BumpPtrAllocator &getAllocator() const {
559 void *Allocate(size_t Size, unsigned Align = 8) const {
560 return BumpAlloc.Allocate(Size, Align);
562 template <typename T> T *Allocate(size_t Num = 1) const {
563 return static_cast<T *>(Allocate(Num * sizeof(T), llvm::alignOf<T>()));
565 void Deallocate(void *Ptr) const { }
567 /// Return the total amount of physical memory allocated for representing
568 /// AST nodes and type information.
569 size_t getASTAllocatedMemory() const {
570 return BumpAlloc.getTotalMemory();
572 /// Return the total memory used for various side tables.
573 size_t getSideTableAllocatedMemory() const;
575 PartialDiagnostic::StorageAllocator &getDiagAllocator() {
576 return DiagAllocator;
579 const TargetInfo &getTargetInfo() const { return *Target; }
580 const TargetInfo *getAuxTargetInfo() const { return AuxTarget; }
582 /// getIntTypeForBitwidth -
583 /// sets integer QualTy according to specified details:
584 /// bitwidth, signed/unsigned.
585 /// Returns empty type if there is no appropriate target types.
586 QualType getIntTypeForBitwidth(unsigned DestWidth,
587 unsigned Signed) const;
588 /// getRealTypeForBitwidth -
589 /// sets floating point QualTy according to specified bitwidth.
590 /// Returns empty type if there is no appropriate target types.
591 QualType getRealTypeForBitwidth(unsigned DestWidth) const;
593 bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const;
595 const LangOptions& getLangOpts() const { return LangOpts; }
597 const SanitizerBlacklist &getSanitizerBlacklist() const {
601 DiagnosticsEngine &getDiagnostics() const;
603 FullSourceLoc getFullLoc(SourceLocation Loc) const {
604 return FullSourceLoc(Loc,SourceMgr);
607 /// \brief All comments in this translation unit.
608 RawCommentList Comments;
610 /// \brief True if comments are already loaded from ExternalASTSource.
611 mutable bool CommentsLoaded;
613 class RawCommentAndCacheFlags {
616 /// We searched for a comment attached to the particular declaration, but
622 /// We have found a comment attached to this particular declaration.
627 /// This declaration does not have an attached comment, and we have
628 /// searched the redeclaration chain.
630 /// If getRaw() == 0, the whole redeclaration chain does not have any
633 /// If getRaw() != 0, it is a comment propagated from other
638 Kind getKind() const LLVM_READONLY {
639 return Data.getInt();
642 void setKind(Kind K) {
646 const RawComment *getRaw() const LLVM_READONLY {
647 return Data.getPointer();
650 void setRaw(const RawComment *RC) {
654 const Decl *getOriginalDecl() const LLVM_READONLY {
658 void setOriginalDecl(const Decl *Orig) {
663 llvm::PointerIntPair<const RawComment *, 2, Kind> Data;
664 const Decl *OriginalDecl;
667 /// \brief Mapping from declarations to comments attached to any
670 /// Raw comments are owned by Comments list. This mapping is populated
672 mutable llvm::DenseMap<const Decl *, RawCommentAndCacheFlags> RedeclComments;
674 /// \brief Mapping from declarations to parsed comments attached to any
676 mutable llvm::DenseMap<const Decl *, comments::FullComment *> ParsedComments;
678 /// \brief Return the documentation comment attached to a given declaration,
679 /// without looking into cache.
680 RawComment *getRawCommentForDeclNoCache(const Decl *D) const;
683 RawCommentList &getRawCommentList() {
687 void addComment(const RawComment &RC) {
688 assert(LangOpts.RetainCommentsFromSystemHeaders ||
689 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
690 Comments.addComment(RC, BumpAlloc);
693 /// \brief Return the documentation comment attached to a given declaration.
694 /// Returns NULL if no comment is attached.
696 /// \param OriginalDecl if not NULL, is set to declaration AST node that had
697 /// the comment, if the comment we found comes from a redeclaration.
699 getRawCommentForAnyRedecl(const Decl *D,
700 const Decl **OriginalDecl = nullptr) const;
702 /// Return parsed documentation comment attached to a given declaration.
703 /// Returns NULL if no comment is attached.
705 /// \param PP the Preprocessor used with this TU. Could be NULL if
706 /// preprocessor is not available.
707 comments::FullComment *getCommentForDecl(const Decl *D,
708 const Preprocessor *PP) const;
710 /// Return parsed documentation comment attached to a given declaration.
711 /// Returns NULL if no comment is attached. Does not look at any
712 /// redeclarations of the declaration.
713 comments::FullComment *getLocalCommentForDeclUncached(const Decl *D) const;
715 comments::FullComment *cloneFullComment(comments::FullComment *FC,
716 const Decl *D) const;
719 mutable comments::CommandTraits CommentCommandTraits;
721 /// \brief Iterator that visits import declarations.
722 class import_iterator {
726 typedef ImportDecl *value_type;
727 typedef ImportDecl *reference;
728 typedef ImportDecl *pointer;
729 typedef int difference_type;
730 typedef std::forward_iterator_tag iterator_category;
732 import_iterator() : Import() {}
733 explicit import_iterator(ImportDecl *Import) : Import(Import) {}
735 reference operator*() const { return Import; }
736 pointer operator->() const { return Import; }
738 import_iterator &operator++() {
739 Import = ASTContext::getNextLocalImport(Import);
743 import_iterator operator++(int) {
744 import_iterator Other(*this);
749 friend bool operator==(import_iterator X, import_iterator Y) {
750 return X.Import == Y.Import;
753 friend bool operator!=(import_iterator X, import_iterator Y) {
754 return X.Import != Y.Import;
759 comments::CommandTraits &getCommentCommandTraits() const {
760 return CommentCommandTraits;
763 /// \brief Retrieve the attributes for the given declaration.
764 AttrVec& getDeclAttrs(const Decl *D);
766 /// \brief Erase the attributes corresponding to the given declaration.
767 void eraseDeclAttrs(const Decl *D);
769 /// \brief If this variable is an instantiated static data member of a
770 /// class template specialization, returns the templated static data member
771 /// from which it was instantiated.
773 MemberSpecializationInfo *getInstantiatedFromStaticDataMember(
776 TemplateOrSpecializationInfo
777 getTemplateOrSpecializationInfo(const VarDecl *Var);
779 FunctionDecl *getClassScopeSpecializationPattern(const FunctionDecl *FD);
781 void setClassScopeSpecializationPattern(FunctionDecl *FD,
782 FunctionDecl *Pattern);
784 /// \brief Note that the static data member \p Inst is an instantiation of
785 /// the static data member template \p Tmpl of a class template.
786 void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
787 TemplateSpecializationKind TSK,
788 SourceLocation PointOfInstantiation = SourceLocation());
790 void setTemplateOrSpecializationInfo(VarDecl *Inst,
791 TemplateOrSpecializationInfo TSI);
793 /// \brief If the given using decl \p Inst is an instantiation of a
794 /// (possibly unresolved) using decl from a template instantiation,
796 NamedDecl *getInstantiatedFromUsingDecl(UsingDecl *Inst);
798 /// \brief Remember that the using decl \p Inst is an instantiation
799 /// of the using decl \p Pattern of a class template.
800 void setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern);
802 void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
803 UsingShadowDecl *Pattern);
804 UsingShadowDecl *getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst);
806 FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field);
808 void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl);
810 // Access to the set of methods overridden by the given C++ method.
811 typedef CXXMethodVector::const_iterator overridden_cxx_method_iterator;
812 overridden_cxx_method_iterator
813 overridden_methods_begin(const CXXMethodDecl *Method) const;
815 overridden_cxx_method_iterator
816 overridden_methods_end(const CXXMethodDecl *Method) const;
818 unsigned overridden_methods_size(const CXXMethodDecl *Method) const;
820 /// \brief Note that the given C++ \p Method overrides the given \p
821 /// Overridden method.
822 void addOverriddenMethod(const CXXMethodDecl *Method,
823 const CXXMethodDecl *Overridden);
825 /// \brief Return C++ or ObjC overridden methods for the given \p Method.
827 /// An ObjC method is considered to override any method in the class's
828 /// base classes, its protocols, or its categories' protocols, that has
829 /// the same selector and is of the same kind (class or instance).
830 /// A method in an implementation is not considered as overriding the same
831 /// method in the interface or its categories.
832 void getOverriddenMethods(
833 const NamedDecl *Method,
834 SmallVectorImpl<const NamedDecl *> &Overridden) const;
836 /// \brief Notify the AST context that a new import declaration has been
837 /// parsed or implicitly created within this translation unit.
838 void addedLocalImportDecl(ImportDecl *Import);
840 static ImportDecl *getNextLocalImport(ImportDecl *Import) {
841 return Import->NextLocalImport;
844 typedef llvm::iterator_range<import_iterator> import_range;
845 import_range local_imports() const {
846 return import_range(import_iterator(FirstLocalImport), import_iterator());
849 Decl *getPrimaryMergedDecl(Decl *D) {
850 Decl *Result = MergedDecls.lookup(D);
851 return Result ? Result : D;
853 void setPrimaryMergedDecl(Decl *D, Decl *Primary) {
854 MergedDecls[D] = Primary;
857 /// \brief Note that the definition \p ND has been merged into module \p M,
858 /// and should be visible whenever \p M is visible.
859 void mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
860 bool NotifyListeners = true);
861 /// \brief Clean up the merged definition list. Call this if you might have
862 /// added duplicates into the list.
863 void deduplicateMergedDefinitonsFor(NamedDecl *ND);
865 /// \brief Get the additional modules in which the definition \p Def has
867 ArrayRef<Module*> getModulesWithMergedDefinition(NamedDecl *Def) {
868 auto MergedIt = MergedDefModules.find(Def);
869 if (MergedIt == MergedDefModules.end())
871 return MergedIt->second;
874 TranslationUnitDecl *getTranslationUnitDecl() const { return TUDecl; }
876 ExternCContextDecl *getExternCContextDecl() const;
877 BuiltinTemplateDecl *getMakeIntegerSeqDecl() const;
883 CanQualType WCharTy; // [C++ 3.9.1p5].
884 CanQualType WideCharTy; // Same as WCharTy in C++, integer type in C99.
885 CanQualType WIntTy; // [C99 7.24.1], integer type unchanged by default promotions.
886 CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99.
887 CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99.
888 CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty;
889 CanQualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy;
890 CanQualType UnsignedLongLongTy, UnsignedInt128Ty;
891 CanQualType FloatTy, DoubleTy, LongDoubleTy;
892 CanQualType HalfTy; // [OpenCL 6.1.1.1], ARM NEON
893 CanQualType FloatComplexTy, DoubleComplexTy, LongDoubleComplexTy;
894 CanQualType VoidPtrTy, NullPtrTy;
895 CanQualType DependentTy, OverloadTy, BoundMemberTy, UnknownAnyTy;
896 CanQualType BuiltinFnTy;
897 CanQualType PseudoObjectTy, ARCUnbridgedCastTy;
898 CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy;
899 CanQualType ObjCBuiltinBoolTy;
900 CanQualType OCLImage1dTy, OCLImage1dArrayTy, OCLImage1dBufferTy;
901 CanQualType OCLImage2dTy, OCLImage2dArrayTy, OCLImage2dDepthTy;
902 CanQualType OCLImage2dArrayDepthTy, OCLImage2dMSAATy, OCLImage2dArrayMSAATy;
903 CanQualType OCLImage2dMSAADepthTy, OCLImage2dArrayMSAADepthTy;
904 CanQualType OCLImage3dTy;
905 CanQualType OCLSamplerTy, OCLEventTy, OCLClkEventTy;
906 CanQualType OCLQueueTy, OCLNDRangeTy, OCLReserveIDTy;
907 CanQualType OMPArraySectionTy;
909 // Types for deductions in C++0x [stmt.ranged]'s desugaring. Built on demand.
910 mutable QualType AutoDeductTy; // Deduction against 'auto'.
911 mutable QualType AutoRRefDeductTy; // Deduction against 'auto &&'.
913 // Decl used to help define __builtin_va_list for some targets.
914 // The decl is built when constructing 'BuiltinVaListDecl'.
915 mutable Decl *VaListTagDecl;
917 ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents,
918 SelectorTable &sels, Builtin::Context &builtins);
922 /// \brief Attach an external AST source to the AST context.
924 /// The external AST source provides the ability to load parts of
925 /// the abstract syntax tree as needed from some external storage,
926 /// e.g., a precompiled header.
927 void setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source);
929 /// \brief Retrieve a pointer to the external AST source associated
930 /// with this AST context, if any.
931 ExternalASTSource *getExternalSource() const {
932 return ExternalSource.get();
935 /// \brief Attach an AST mutation listener to the AST context.
937 /// The AST mutation listener provides the ability to track modifications to
938 /// the abstract syntax tree entities committed after they were initially
940 void setASTMutationListener(ASTMutationListener *Listener) {
941 this->Listener = Listener;
944 /// \brief Retrieve a pointer to the AST mutation listener associated
945 /// with this AST context, if any.
946 ASTMutationListener *getASTMutationListener() const { return Listener; }
948 void PrintStats() const;
949 const SmallVectorImpl<Type *>& getTypes() const { return Types; }
951 BuiltinTemplateDecl *buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
952 const IdentifierInfo *II) const;
954 /// \brief Create a new implicit TU-level CXXRecordDecl or RecordDecl
956 RecordDecl *buildImplicitRecord(StringRef Name,
957 RecordDecl::TagKind TK = TTK_Struct) const;
959 /// \brief Create a new implicit TU-level typedef declaration.
960 TypedefDecl *buildImplicitTypedef(QualType T, StringRef Name) const;
962 /// \brief Retrieve the declaration for the 128-bit signed integer type.
963 TypedefDecl *getInt128Decl() const;
965 /// \brief Retrieve the declaration for the 128-bit unsigned integer type.
966 TypedefDecl *getUInt128Decl() const;
968 /// \brief Retrieve the declaration for a 128-bit float stub type.
969 TypeDecl *getFloat128StubType() const;
971 //===--------------------------------------------------------------------===//
973 //===--------------------------------------------------------------------===//
976 /// \brief Return a type with extended qualifiers.
977 QualType getExtQualType(const Type *Base, Qualifiers Quals) const;
979 QualType getTypeDeclTypeSlow(const TypeDecl *Decl) const;
982 /// \brief Return the uniqued reference to the type for an address space
983 /// qualified type with the specified type and address space.
985 /// The resulting type has a union of the qualifiers from T and the address
986 /// space. If T already has an address space specifier, it is silently
988 QualType getAddrSpaceQualType(QualType T, unsigned AddressSpace) const;
990 /// \brief Return the uniqued reference to the type for an Objective-C
991 /// gc-qualified type.
993 /// The retulting type has a union of the qualifiers from T and the gc
995 QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const;
997 /// \brief Return the uniqued reference to the type for a \c restrict
1000 /// The resulting type has a union of the qualifiers from \p T and
1002 QualType getRestrictType(QualType T) const {
1003 return T.withFastQualifiers(Qualifiers::Restrict);
1006 /// \brief Return the uniqued reference to the type for a \c volatile
1009 /// The resulting type has a union of the qualifiers from \p T and
1011 QualType getVolatileType(QualType T) const {
1012 return T.withFastQualifiers(Qualifiers::Volatile);
1015 /// \brief Return the uniqued reference to the type for a \c const
1018 /// The resulting type has a union of the qualifiers from \p T and \c const.
1020 /// It can be reasonably expected that this will always be equivalent to
1021 /// calling T.withConst().
1022 QualType getConstType(QualType T) const { return T.withConst(); }
1024 /// \brief Change the ExtInfo on a function type.
1025 const FunctionType *adjustFunctionType(const FunctionType *Fn,
1026 FunctionType::ExtInfo EInfo);
1028 /// Adjust the given function result type.
1029 CanQualType getCanonicalFunctionResultType(QualType ResultType) const;
1031 /// \brief Change the result type of a function type once it is deduced.
1032 void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType);
1034 /// \brief Change the exception specification on a function once it is
1035 /// delay-parsed, instantiated, or computed.
1036 void adjustExceptionSpec(FunctionDecl *FD,
1037 const FunctionProtoType::ExceptionSpecInfo &ESI,
1038 bool AsWritten = false);
1040 /// \brief Return the uniqued reference to the type for a complex
1041 /// number with the specified element type.
1042 QualType getComplexType(QualType T) const;
1043 CanQualType getComplexType(CanQualType T) const {
1044 return CanQualType::CreateUnsafe(getComplexType((QualType) T));
1047 /// \brief Return the uniqued reference to the type for a pointer to
1048 /// the specified type.
1049 QualType getPointerType(QualType T) const;
1050 CanQualType getPointerType(CanQualType T) const {
1051 return CanQualType::CreateUnsafe(getPointerType((QualType) T));
1054 /// \brief Return the uniqued reference to a type adjusted from the original
1055 /// type to a new type.
1056 QualType getAdjustedType(QualType Orig, QualType New) const;
1057 CanQualType getAdjustedType(CanQualType Orig, CanQualType New) const {
1058 return CanQualType::CreateUnsafe(
1059 getAdjustedType((QualType)Orig, (QualType)New));
1062 /// \brief Return the uniqued reference to the decayed version of the given
1063 /// type. Can only be called on array and function types which decay to
1065 QualType getDecayedType(QualType T) const;
1066 CanQualType getDecayedType(CanQualType T) const {
1067 return CanQualType::CreateUnsafe(getDecayedType((QualType) T));
1070 /// \brief Return the uniqued reference to the atomic type for the specified
1072 QualType getAtomicType(QualType T) const;
1074 /// \brief Return the uniqued reference to the type for a block of the
1076 QualType getBlockPointerType(QualType T) const;
1078 /// Gets the struct used to keep track of the descriptor for pointer to
1080 QualType getBlockDescriptorType() const;
1082 /// Gets the struct used to keep track of the extended descriptor for
1083 /// pointer to blocks.
1084 QualType getBlockDescriptorExtendedType() const;
1086 void setcudaConfigureCallDecl(FunctionDecl *FD) {
1087 cudaConfigureCallDecl = FD;
1089 FunctionDecl *getcudaConfigureCallDecl() {
1090 return cudaConfigureCallDecl;
1093 /// Returns true iff we need copy/dispose helpers for the given type.
1094 bool BlockRequiresCopying(QualType Ty, const VarDecl *D);
1097 /// Returns true, if given type has a known lifetime. HasByrefExtendedLayout is set
1098 /// to false in this case. If HasByrefExtendedLayout returns true, byref variable
1099 /// has extended lifetime.
1100 bool getByrefLifetime(QualType Ty,
1101 Qualifiers::ObjCLifetime &Lifetime,
1102 bool &HasByrefExtendedLayout) const;
1104 /// \brief Return the uniqued reference to the type for an lvalue reference
1105 /// to the specified type.
1106 QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true)
1109 /// \brief Return the uniqued reference to the type for an rvalue reference
1110 /// to the specified type.
1111 QualType getRValueReferenceType(QualType T) const;
1113 /// \brief Return the uniqued reference to the type for a member pointer to
1114 /// the specified type in the specified class.
1116 /// The class \p Cls is a \c Type because it could be a dependent name.
1117 QualType getMemberPointerType(QualType T, const Type *Cls) const;
1119 /// \brief Return a non-unique reference to the type for a variable array of
1120 /// the specified element type.
1121 QualType getVariableArrayType(QualType EltTy, Expr *NumElts,
1122 ArrayType::ArraySizeModifier ASM,
1123 unsigned IndexTypeQuals,
1124 SourceRange Brackets) const;
1126 /// \brief Return a non-unique reference to the type for a dependently-sized
1127 /// array of the specified element type.
1129 /// FIXME: We will need these to be uniqued, or at least comparable, at some
1131 QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
1132 ArrayType::ArraySizeModifier ASM,
1133 unsigned IndexTypeQuals,
1134 SourceRange Brackets) const;
1136 /// \brief Return a unique reference to the type for an incomplete array of
1137 /// the specified element type.
1138 QualType getIncompleteArrayType(QualType EltTy,
1139 ArrayType::ArraySizeModifier ASM,
1140 unsigned IndexTypeQuals) const;
1142 /// \brief Return the unique reference to the type for a constant array of
1143 /// the specified element type.
1144 QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize,
1145 ArrayType::ArraySizeModifier ASM,
1146 unsigned IndexTypeQuals) const;
1148 /// \brief Returns a vla type where known sizes are replaced with [*].
1149 QualType getVariableArrayDecayedType(QualType Ty) const;
1151 /// \brief Return the unique reference to a vector type of the specified
1152 /// element type and size.
1154 /// \pre \p VectorType must be a built-in type.
1155 QualType getVectorType(QualType VectorType, unsigned NumElts,
1156 VectorType::VectorKind VecKind) const;
1158 /// \brief Return the unique reference to an extended vector type
1159 /// of the specified element type and size.
1161 /// \pre \p VectorType must be a built-in type.
1162 QualType getExtVectorType(QualType VectorType, unsigned NumElts) const;
1164 /// \pre Return a non-unique reference to the type for a dependently-sized
1165 /// vector of the specified element type.
1167 /// FIXME: We will need these to be uniqued, or at least comparable, at some
1169 QualType getDependentSizedExtVectorType(QualType VectorType,
1171 SourceLocation AttrLoc) const;
1173 /// \brief Return a K&R style C function type like 'int()'.
1174 QualType getFunctionNoProtoType(QualType ResultTy,
1175 const FunctionType::ExtInfo &Info) const;
1177 QualType getFunctionNoProtoType(QualType ResultTy) const {
1178 return getFunctionNoProtoType(ResultTy, FunctionType::ExtInfo());
1181 /// \brief Return a normal function type with a typed argument list.
1182 QualType getFunctionType(QualType ResultTy, ArrayRef<QualType> Args,
1183 const FunctionProtoType::ExtProtoInfo &EPI) const;
1185 /// \brief Return the unique reference to the type for the specified type
1187 QualType getTypeDeclType(const TypeDecl *Decl,
1188 const TypeDecl *PrevDecl = nullptr) const {
1189 assert(Decl && "Passed null for Decl param");
1190 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1193 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
1194 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1195 return QualType(PrevDecl->TypeForDecl, 0);
1198 return getTypeDeclTypeSlow(Decl);
1201 /// \brief Return the unique reference to the type for the specified
1202 /// typedef-name decl.
1203 QualType getTypedefType(const TypedefNameDecl *Decl,
1204 QualType Canon = QualType()) const;
1206 QualType getRecordType(const RecordDecl *Decl) const;
1208 QualType getEnumType(const EnumDecl *Decl) const;
1210 QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const;
1212 QualType getAttributedType(AttributedType::Kind attrKind,
1213 QualType modifiedType,
1214 QualType equivalentType);
1216 QualType getSubstTemplateTypeParmType(const TemplateTypeParmType *Replaced,
1217 QualType Replacement) const;
1218 QualType getSubstTemplateTypeParmPackType(
1219 const TemplateTypeParmType *Replaced,
1220 const TemplateArgument &ArgPack);
1223 getTemplateTypeParmType(unsigned Depth, unsigned Index,
1225 TemplateTypeParmDecl *ParmDecl = nullptr) const;
1227 QualType getTemplateSpecializationType(TemplateName T,
1228 const TemplateArgument *Args,
1230 QualType Canon = QualType()) const;
1232 QualType getCanonicalTemplateSpecializationType(TemplateName T,
1233 const TemplateArgument *Args,
1234 unsigned NumArgs) const;
1236 QualType getTemplateSpecializationType(TemplateName T,
1237 const TemplateArgumentListInfo &Args,
1238 QualType Canon = QualType()) const;
1241 getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc,
1242 const TemplateArgumentListInfo &Args,
1243 QualType Canon = QualType()) const;
1245 QualType getParenType(QualType NamedType) const;
1247 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1248 NestedNameSpecifier *NNS,
1249 QualType NamedType) const;
1250 QualType getDependentNameType(ElaboratedTypeKeyword Keyword,
1251 NestedNameSpecifier *NNS,
1252 const IdentifierInfo *Name,
1253 QualType Canon = QualType()) const;
1255 QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
1256 NestedNameSpecifier *NNS,
1257 const IdentifierInfo *Name,
1258 const TemplateArgumentListInfo &Args) const;
1259 QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
1260 NestedNameSpecifier *NNS,
1261 const IdentifierInfo *Name,
1263 const TemplateArgument *Args) const;
1265 QualType getPackExpansionType(QualType Pattern,
1266 Optional<unsigned> NumExpansions);
1268 QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
1269 ObjCInterfaceDecl *PrevDecl = nullptr) const;
1271 /// Legacy interface: cannot provide type arguments or __kindof.
1272 QualType getObjCObjectType(QualType Base,
1273 ObjCProtocolDecl * const *Protocols,
1274 unsigned NumProtocols) const;
1276 QualType getObjCObjectType(QualType Base,
1277 ArrayRef<QualType> typeArgs,
1278 ArrayRef<ObjCProtocolDecl *> protocols,
1279 bool isKindOf) const;
1281 bool ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *Decl);
1282 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
1283 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
1285 bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
1286 ObjCInterfaceDecl *IDecl);
1288 /// \brief Return a ObjCObjectPointerType type for the given ObjCObjectType.
1289 QualType getObjCObjectPointerType(QualType OIT) const;
1291 /// \brief GCC extension.
1292 QualType getTypeOfExprType(Expr *e) const;
1293 QualType getTypeOfType(QualType t) const;
1295 /// \brief C++11 decltype.
1296 QualType getDecltypeType(Expr *e, QualType UnderlyingType) const;
1298 /// \brief Unary type transforms
1299 QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
1300 UnaryTransformType::UTTKind UKind) const;
1302 /// \brief C++11 deduced auto type.
1303 QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
1304 bool IsDependent) const;
1306 /// \brief C++11 deduction pattern for 'auto' type.
1307 QualType getAutoDeductType() const;
1309 /// \brief C++11 deduction pattern for 'auto &&' type.
1310 QualType getAutoRRefDeductType() const;
1312 /// \brief Return the unique reference to the type for the specified TagDecl
1313 /// (struct/union/class/enum) decl.
1314 QualType getTagDeclType(const TagDecl *Decl) const;
1316 /// \brief Return the unique type for "size_t" (C99 7.17), defined in
1319 /// The sizeof operator requires this (C99 6.5.3.4p4).
1320 CanQualType getSizeType() const;
1322 /// \brief Return the unique type for "intmax_t" (C99 7.18.1.5), defined in
1324 CanQualType getIntMaxType() const;
1326 /// \brief Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in
1328 CanQualType getUIntMaxType() const;
1330 /// \brief Return the unique wchar_t type available in C++ (and available as
1331 /// __wchar_t as a Microsoft extension).
1332 QualType getWCharType() const { return WCharTy; }
1334 /// \brief Return the type of wide characters. In C++, this returns the
1335 /// unique wchar_t type. In C99, this returns a type compatible with the type
1336 /// defined in <stddef.h> as defined by the target.
1337 QualType getWideCharType() const { return WideCharTy; }
1339 /// \brief Return the type of "signed wchar_t".
1341 /// Used when in C++, as a GCC extension.
1342 QualType getSignedWCharType() const;
1344 /// \brief Return the type of "unsigned wchar_t".
1346 /// Used when in C++, as a GCC extension.
1347 QualType getUnsignedWCharType() const;
1349 /// \brief In C99, this returns a type compatible with the type
1350 /// defined in <stddef.h> as defined by the target.
1351 QualType getWIntType() const { return WIntTy; }
1353 /// \brief Return a type compatible with "intptr_t" (C99 7.18.1.4),
1354 /// as defined by the target.
1355 QualType getIntPtrType() const;
1357 /// \brief Return a type compatible with "uintptr_t" (C99 7.18.1.4),
1358 /// as defined by the target.
1359 QualType getUIntPtrType() const;
1361 /// \brief Return the unique type for "ptrdiff_t" (C99 7.17) defined in
1362 /// <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1363 QualType getPointerDiffType() const;
1365 /// \brief Return the unique type for "pid_t" defined in
1366 /// <sys/types.h>. We need this to compute the correct type for vfork().
1367 QualType getProcessIDType() const;
1369 /// \brief Return the C structure type used to represent constant CFStrings.
1370 QualType getCFConstantStringType() const;
1372 /// \brief Returns the C struct type for objc_super
1373 QualType getObjCSuperType() const;
1374 void setObjCSuperType(QualType ST) { ObjCSuperType = ST; }
1376 /// Get the structure type used to representation CFStrings, or NULL
1377 /// if it hasn't yet been built.
1378 QualType getRawCFConstantStringType() const {
1379 if (CFConstantStringTypeDecl)
1380 return getTagDeclType(CFConstantStringTypeDecl);
1383 void setCFConstantStringType(QualType T);
1385 // This setter/getter represents the ObjC type for an NSConstantString.
1386 void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl);
1387 QualType getObjCConstantStringInterface() const {
1388 return ObjCConstantStringType;
1391 QualType getObjCNSStringType() const {
1392 return ObjCNSStringType;
1395 void setObjCNSStringType(QualType T) {
1396 ObjCNSStringType = T;
1399 /// \brief Retrieve the type that \c id has been defined to, which may be
1400 /// different from the built-in \c id if \c id has been typedef'd.
1401 QualType getObjCIdRedefinitionType() const {
1402 if (ObjCIdRedefinitionType.isNull())
1403 return getObjCIdType();
1404 return ObjCIdRedefinitionType;
1407 /// \brief Set the user-written type that redefines \c id.
1408 void setObjCIdRedefinitionType(QualType RedefType) {
1409 ObjCIdRedefinitionType = RedefType;
1412 /// \brief Retrieve the type that \c Class has been defined to, which may be
1413 /// different from the built-in \c Class if \c Class has been typedef'd.
1414 QualType getObjCClassRedefinitionType() const {
1415 if (ObjCClassRedefinitionType.isNull())
1416 return getObjCClassType();
1417 return ObjCClassRedefinitionType;
1420 /// \brief Set the user-written type that redefines 'SEL'.
1421 void setObjCClassRedefinitionType(QualType RedefType) {
1422 ObjCClassRedefinitionType = RedefType;
1425 /// \brief Retrieve the type that 'SEL' has been defined to, which may be
1426 /// different from the built-in 'SEL' if 'SEL' has been typedef'd.
1427 QualType getObjCSelRedefinitionType() const {
1428 if (ObjCSelRedefinitionType.isNull())
1429 return getObjCSelType();
1430 return ObjCSelRedefinitionType;
1434 /// \brief Set the user-written type that redefines 'SEL'.
1435 void setObjCSelRedefinitionType(QualType RedefType) {
1436 ObjCSelRedefinitionType = RedefType;
1439 /// Retrieve the identifier 'NSObject'.
1440 IdentifierInfo *getNSObjectName() {
1441 if (!NSObjectName) {
1442 NSObjectName = &Idents.get("NSObject");
1445 return NSObjectName;
1448 /// Retrieve the identifier 'NSCopying'.
1449 IdentifierInfo *getNSCopyingName() {
1450 if (!NSCopyingName) {
1451 NSCopyingName = &Idents.get("NSCopying");
1454 return NSCopyingName;
1457 IdentifierInfo *getMakeIntegerSeqName() const {
1458 if (!MakeIntegerSeqName)
1459 MakeIntegerSeqName = &Idents.get("__make_integer_seq");
1460 return MakeIntegerSeqName;
1463 /// \brief Retrieve the Objective-C "instancetype" type, if already known;
1464 /// otherwise, returns a NULL type;
1465 QualType getObjCInstanceType() {
1466 return getTypeDeclType(getObjCInstanceTypeDecl());
1469 /// \brief Retrieve the typedef declaration corresponding to the Objective-C
1470 /// "instancetype" type.
1471 TypedefDecl *getObjCInstanceTypeDecl();
1473 /// \brief Set the type for the C FILE type.
1474 void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; }
1476 /// \brief Retrieve the C FILE type.
1477 QualType getFILEType() const {
1479 return getTypeDeclType(FILEDecl);
1483 /// \brief Set the type for the C jmp_buf type.
1484 void setjmp_bufDecl(TypeDecl *jmp_bufDecl) {
1485 this->jmp_bufDecl = jmp_bufDecl;
1488 /// \brief Retrieve the C jmp_buf type.
1489 QualType getjmp_bufType() const {
1491 return getTypeDeclType(jmp_bufDecl);
1495 /// \brief Set the type for the C sigjmp_buf type.
1496 void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) {
1497 this->sigjmp_bufDecl = sigjmp_bufDecl;
1500 /// \brief Retrieve the C sigjmp_buf type.
1501 QualType getsigjmp_bufType() const {
1503 return getTypeDeclType(sigjmp_bufDecl);
1507 /// \brief Set the type for the C ucontext_t type.
1508 void setucontext_tDecl(TypeDecl *ucontext_tDecl) {
1509 this->ucontext_tDecl = ucontext_tDecl;
1512 /// \brief Retrieve the C ucontext_t type.
1513 QualType getucontext_tType() const {
1515 return getTypeDeclType(ucontext_tDecl);
1519 /// \brief The result type of logical operations, '<', '>', '!=', etc.
1520 QualType getLogicalOperationType() const {
1521 return getLangOpts().CPlusPlus ? BoolTy : IntTy;
1524 /// \brief Emit the Objective-CC type encoding for the given type \p T into
1527 /// If \p Field is specified then record field names are also encoded.
1528 void getObjCEncodingForType(QualType T, std::string &S,
1529 const FieldDecl *Field=nullptr,
1530 QualType *NotEncodedT=nullptr) const;
1532 /// \brief Emit the Objective-C property type encoding for the given
1533 /// type \p T into \p S.
1534 void getObjCEncodingForPropertyType(QualType T, std::string &S) const;
1536 void getLegacyIntegralTypeEncoding(QualType &t) const;
1538 /// \brief Put the string version of the type qualifiers \p QT into \p S.
1539 void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
1540 std::string &S) const;
1542 /// \brief Emit the encoded type for the function \p Decl into \p S.
1544 /// This is in the same format as Objective-C method encodings.
1546 /// \returns true if an error occurred (e.g., because one of the parameter
1547 /// types is incomplete), false otherwise.
1548 bool getObjCEncodingForFunctionDecl(const FunctionDecl *Decl, std::string& S);
1550 /// \brief Emit the encoded type for the method declaration \p Decl into
1553 /// \returns true if an error occurred (e.g., because one of the parameter
1554 /// types is incomplete), false otherwise.
1555 bool getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, std::string &S,
1556 bool Extended = false)
1559 /// \brief Return the encoded type for this block declaration.
1560 std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const;
1562 /// getObjCEncodingForPropertyDecl - Return the encoded type for
1563 /// this method declaration. If non-NULL, Container must be either
1564 /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
1565 /// only be NULL when getting encodings for protocol properties.
1566 void getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
1567 const Decl *Container,
1568 std::string &S) const;
1570 bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
1571 ObjCProtocolDecl *rProto) const;
1573 ObjCPropertyImplDecl *getObjCPropertyImplDeclForPropertyDecl(
1574 const ObjCPropertyDecl *PD,
1575 const Decl *Container) const;
1577 /// \brief Return the size of type \p T for Objective-C encoding purpose,
1579 CharUnits getObjCEncodingTypeSize(QualType T) const;
1581 /// \brief Retrieve the typedef corresponding to the predefined \c id type
1583 TypedefDecl *getObjCIdDecl() const;
1585 /// \brief Represents the Objective-CC \c id type.
1587 /// This is set up lazily, by Sema. \c id is always a (typedef for a)
1588 /// pointer type, a pointer to a struct.
1589 QualType getObjCIdType() const {
1590 return getTypeDeclType(getObjCIdDecl());
1593 /// \brief Retrieve the typedef corresponding to the predefined 'SEL' type
1595 TypedefDecl *getObjCSelDecl() const;
1597 /// \brief Retrieve the type that corresponds to the predefined Objective-C
1599 QualType getObjCSelType() const {
1600 return getTypeDeclType(getObjCSelDecl());
1603 /// \brief Retrieve the typedef declaration corresponding to the predefined
1604 /// Objective-C 'Class' type.
1605 TypedefDecl *getObjCClassDecl() const;
1607 /// \brief Represents the Objective-C \c Class type.
1609 /// This is set up lazily, by Sema. \c Class is always a (typedef for a)
1610 /// pointer type, a pointer to a struct.
1611 QualType getObjCClassType() const {
1612 return getTypeDeclType(getObjCClassDecl());
1615 /// \brief Retrieve the Objective-C class declaration corresponding to
1616 /// the predefined \c Protocol class.
1617 ObjCInterfaceDecl *getObjCProtocolDecl() const;
1619 /// \brief Retrieve declaration of 'BOOL' typedef
1620 TypedefDecl *getBOOLDecl() const {
1624 /// \brief Save declaration of 'BOOL' typedef
1625 void setBOOLDecl(TypedefDecl *TD) {
1629 /// \brief type of 'BOOL' type.
1630 QualType getBOOLType() const {
1631 return getTypeDeclType(getBOOLDecl());
1634 /// \brief Retrieve the type of the Objective-C \c Protocol class.
1635 QualType getObjCProtoType() const {
1636 return getObjCInterfaceType(getObjCProtocolDecl());
1639 /// \brief Retrieve the C type declaration corresponding to the predefined
1640 /// \c __builtin_va_list type.
1641 TypedefDecl *getBuiltinVaListDecl() const;
1643 /// \brief Retrieve the type of the \c __builtin_va_list type.
1644 QualType getBuiltinVaListType() const {
1645 return getTypeDeclType(getBuiltinVaListDecl());
1648 /// \brief Retrieve the C type declaration corresponding to the predefined
1649 /// \c __va_list_tag type used to help define the \c __builtin_va_list type
1650 /// for some targets.
1651 Decl *getVaListTagDecl() const;
1653 /// Retrieve the C type declaration corresponding to the predefined
1654 /// \c __builtin_ms_va_list type.
1655 TypedefDecl *getBuiltinMSVaListDecl() const;
1657 /// Retrieve the type of the \c __builtin_ms_va_list type.
1658 QualType getBuiltinMSVaListType() const {
1659 return getTypeDeclType(getBuiltinMSVaListDecl());
1662 /// \brief Return a type with additional \c const, \c volatile, or
1663 /// \c restrict qualifiers.
1664 QualType getCVRQualifiedType(QualType T, unsigned CVR) const {
1665 return getQualifiedType(T, Qualifiers::fromCVRMask(CVR));
1668 /// \brief Un-split a SplitQualType.
1669 QualType getQualifiedType(SplitQualType split) const {
1670 return getQualifiedType(split.Ty, split.Quals);
1673 /// \brief Return a type with additional qualifiers.
1674 QualType getQualifiedType(QualType T, Qualifiers Qs) const {
1675 if (!Qs.hasNonFastQualifiers())
1676 return T.withFastQualifiers(Qs.getFastQualifiers());
1677 QualifierCollector Qc(Qs);
1678 const Type *Ptr = Qc.strip(T);
1679 return getExtQualType(Ptr, Qc);
1682 /// \brief Return a type with additional qualifiers.
1683 QualType getQualifiedType(const Type *T, Qualifiers Qs) const {
1684 if (!Qs.hasNonFastQualifiers())
1685 return QualType(T, Qs.getFastQualifiers());
1686 return getExtQualType(T, Qs);
1689 /// \brief Return a type with the given lifetime qualifier.
1691 /// \pre Neither type.ObjCLifetime() nor \p lifetime may be \c OCL_None.
1692 QualType getLifetimeQualifiedType(QualType type,
1693 Qualifiers::ObjCLifetime lifetime) {
1694 assert(type.getObjCLifetime() == Qualifiers::OCL_None);
1695 assert(lifetime != Qualifiers::OCL_None);
1698 qs.addObjCLifetime(lifetime);
1699 return getQualifiedType(type, qs);
1702 /// getUnqualifiedObjCPointerType - Returns version of
1703 /// Objective-C pointer type with lifetime qualifier removed.
1704 QualType getUnqualifiedObjCPointerType(QualType type) const {
1705 if (!type.getTypePtr()->isObjCObjectPointerType() ||
1706 !type.getQualifiers().hasObjCLifetime())
1708 Qualifiers Qs = type.getQualifiers();
1709 Qs.removeObjCLifetime();
1710 return getQualifiedType(type.getUnqualifiedType(), Qs);
1713 DeclarationNameInfo getNameForTemplate(TemplateName Name,
1714 SourceLocation NameLoc) const;
1716 TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin,
1717 UnresolvedSetIterator End) const;
1719 TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
1720 bool TemplateKeyword,
1721 TemplateDecl *Template) const;
1723 TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1724 const IdentifierInfo *Name) const;
1725 TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1726 OverloadedOperatorKind Operator) const;
1727 TemplateName getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
1728 TemplateName replacement) const;
1729 TemplateName getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
1730 const TemplateArgument &ArgPack) const;
1732 enum GetBuiltinTypeError {
1733 GE_None, ///< No error
1734 GE_Missing_stdio, ///< Missing a type from <stdio.h>
1735 GE_Missing_setjmp, ///< Missing a type from <setjmp.h>
1736 GE_Missing_ucontext ///< Missing a type from <ucontext.h>
1739 /// \brief Return the type for the specified builtin.
1741 /// If \p IntegerConstantArgs is non-null, it is filled in with a bitmask of
1742 /// arguments to the builtin that are required to be integer constant
1744 QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error,
1745 unsigned *IntegerConstantArgs = nullptr) const;
1748 CanQualType getFromTargetType(unsigned Type) const;
1749 TypeInfo getTypeInfoImpl(const Type *T) const;
1751 //===--------------------------------------------------------------------===//
1753 //===--------------------------------------------------------------------===//
1756 /// \brief Return one of the GCNone, Weak or Strong Objective-C garbage
1757 /// collection attributes.
1758 Qualifiers::GC getObjCGCAttrKind(QualType Ty) const;
1760 /// \brief Return true if the given vector types are of the same unqualified
1761 /// type or if they are equivalent to the same GCC vector type.
1763 /// \note This ignores whether they are target-specific (AltiVec or Neon)
1765 bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec);
1767 /// \brief Return true if this is an \c NSObject object with its \c NSObject
1769 static bool isObjCNSObjectType(QualType Ty) {
1770 return Ty->isObjCNSObjectType();
1773 //===--------------------------------------------------------------------===//
1774 // Type Sizing and Analysis
1775 //===--------------------------------------------------------------------===//
1777 /// \brief Return the APFloat 'semantics' for the specified scalar floating
1779 const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
1781 /// \brief Get the size and alignment of the specified complete type in bits.
1782 TypeInfo getTypeInfo(const Type *T) const;
1783 TypeInfo getTypeInfo(QualType T) const { return getTypeInfo(T.getTypePtr()); }
1785 /// \brief Get default simd alignment of the specified complete type in bits.
1786 unsigned getOpenMPDefaultSimdAlign(QualType T) const;
1788 /// \brief Return the size of the specified (complete) type \p T, in bits.
1789 uint64_t getTypeSize(QualType T) const { return getTypeInfo(T).Width; }
1790 uint64_t getTypeSize(const Type *T) const { return getTypeInfo(T).Width; }
1792 /// \brief Return the size of the character type, in bits.
1793 uint64_t getCharWidth() const {
1794 return getTypeSize(CharTy);
1797 /// \brief Convert a size in bits to a size in characters.
1798 CharUnits toCharUnitsFromBits(int64_t BitSize) const;
1800 /// \brief Convert a size in characters to a size in bits.
1801 int64_t toBits(CharUnits CharSize) const;
1803 /// \brief Return the size of the specified (complete) type \p T, in
1805 CharUnits getTypeSizeInChars(QualType T) const;
1806 CharUnits getTypeSizeInChars(const Type *T) const;
1808 /// \brief Return the ABI-specified alignment of a (complete) type \p T, in
1810 unsigned getTypeAlign(QualType T) const { return getTypeInfo(T).Align; }
1811 unsigned getTypeAlign(const Type *T) const { return getTypeInfo(T).Align; }
1813 /// \brief Return the ABI-specified alignment of a (complete) type \p T, in
1815 CharUnits getTypeAlignInChars(QualType T) const;
1816 CharUnits getTypeAlignInChars(const Type *T) const;
1818 // getTypeInfoDataSizeInChars - Return the size of a type, in chars. If the
1819 // type is a record, its data size is returned.
1820 std::pair<CharUnits, CharUnits> getTypeInfoDataSizeInChars(QualType T) const;
1822 std::pair<CharUnits, CharUnits> getTypeInfoInChars(const Type *T) const;
1823 std::pair<CharUnits, CharUnits> getTypeInfoInChars(QualType T) const;
1825 /// \brief Determine if the alignment the type has was required using an
1826 /// alignment attribute.
1827 bool isAlignmentRequired(const Type *T) const;
1828 bool isAlignmentRequired(QualType T) const;
1830 /// \brief Return the "preferred" alignment of the specified type \p T for
1831 /// the current target, in bits.
1833 /// This can be different than the ABI alignment in cases where it is
1834 /// beneficial for performance to overalign a data type.
1835 unsigned getPreferredTypeAlign(const Type *T) const;
1837 /// \brief Return the default alignment for __attribute__((aligned)) on
1838 /// this target, to be used if no alignment value is specified.
1839 unsigned getTargetDefaultAlignForAttributeAligned(void) const;
1841 /// \brief Return the alignment in bits that should be given to a
1842 /// global variable with type \p T.
1843 unsigned getAlignOfGlobalVar(QualType T) const;
1845 /// \brief Return the alignment in characters that should be given to a
1846 /// global variable with type \p T.
1847 CharUnits getAlignOfGlobalVarInChars(QualType T) const;
1849 /// \brief Return a conservative estimate of the alignment of the specified
1852 /// \pre \p D must not be a bitfield type, as bitfields do not have a valid
1855 /// If \p ForAlignof, references are treated like their underlying type
1856 /// and large arrays don't get any special treatment. If not \p ForAlignof
1857 /// it computes the value expected by CodeGen: references are treated like
1858 /// pointers and large arrays get extra alignment.
1859 CharUnits getDeclAlign(const Decl *D, bool ForAlignof = false) const;
1861 /// \brief Get or compute information about the layout of the specified
1862 /// record (struct/union/class) \p D, which indicates its size and field
1863 /// position information.
1864 const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D) const;
1866 /// \brief Get or compute information about the layout of the specified
1867 /// Objective-C interface.
1868 const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D)
1871 void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS,
1872 bool Simple = false) const;
1874 /// \brief Get or compute information about the layout of the specified
1875 /// Objective-C implementation.
1877 /// This may differ from the interface if synthesized ivars are present.
1878 const ASTRecordLayout &
1879 getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const;
1881 /// \brief Get our current best idea for the key function of the
1882 /// given record decl, or NULL if there isn't one.
1884 /// The key function is, according to the Itanium C++ ABI section 5.2.3:
1885 /// ...the first non-pure virtual function that is not inline at the
1886 /// point of class definition.
1888 /// Other ABIs use the same idea. However, the ARM C++ ABI ignores
1889 /// virtual functions that are defined 'inline', which means that
1890 /// the result of this computation can change.
1891 const CXXMethodDecl *getCurrentKeyFunction(const CXXRecordDecl *RD);
1893 /// \brief Observe that the given method cannot be a key function.
1894 /// Checks the key-function cache for the method's class and clears it
1895 /// if matches the given declaration.
1897 /// This is used in ABIs where out-of-line definitions marked
1898 /// inline are not considered to be key functions.
1900 /// \param method should be the declaration from the class definition
1901 void setNonKeyFunction(const CXXMethodDecl *method);
1903 /// Loading virtual member pointers using the virtual inheritance model
1904 /// always results in an adjustment using the vbtable even if the index is
1907 /// This is usually OK because the first slot in the vbtable points
1908 /// backwards to the top of the MDC. However, the MDC might be reusing a
1909 /// vbptr from an nv-base. In this case, the first slot in the vbtable
1910 /// points to the start of the nv-base which introduced the vbptr and *not*
1911 /// the MDC. Modify the NonVirtualBaseAdjustment to account for this.
1912 CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const;
1914 /// Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
1915 uint64_t getFieldOffset(const ValueDecl *FD) const;
1917 bool isNearlyEmpty(const CXXRecordDecl *RD) const;
1919 VTableContextBase *getVTableContext();
1921 MangleContext *createMangleContext();
1923 void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass,
1924 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const;
1926 unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const;
1927 void CollectInheritedProtocols(const Decl *CDecl,
1928 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols);
1930 //===--------------------------------------------------------------------===//
1932 //===--------------------------------------------------------------------===//
1934 /// \brief Return the canonical (structural) type corresponding to the
1935 /// specified potentially non-canonical type \p T.
1937 /// The non-canonical version of a type may have many "decorated" versions of
1938 /// types. Decorators can include typedefs, 'typeof' operators, etc. The
1939 /// returned type is guaranteed to be free of any of these, allowing two
1940 /// canonical types to be compared for exact equality with a simple pointer
1942 CanQualType getCanonicalType(QualType T) const {
1943 return CanQualType::CreateUnsafe(T.getCanonicalType());
1946 const Type *getCanonicalType(const Type *T) const {
1947 return T->getCanonicalTypeInternal().getTypePtr();
1950 /// \brief Return the canonical parameter type corresponding to the specific
1951 /// potentially non-canonical one.
1953 /// Qualifiers are stripped off, functions are turned into function
1954 /// pointers, and arrays decay one level into pointers.
1955 CanQualType getCanonicalParamType(QualType T) const;
1957 /// \brief Determine whether the given types \p T1 and \p T2 are equivalent.
1958 bool hasSameType(QualType T1, QualType T2) const {
1959 return getCanonicalType(T1) == getCanonicalType(T2);
1962 bool hasSameType(const Type *T1, const Type *T2) const {
1963 return getCanonicalType(T1) == getCanonicalType(T2);
1966 /// \brief Return this type as a completely-unqualified array type,
1967 /// capturing the qualifiers in \p Quals.
1969 /// This will remove the minimal amount of sugaring from the types, similar
1970 /// to the behavior of QualType::getUnqualifiedType().
1972 /// \param T is the qualified type, which may be an ArrayType
1974 /// \param Quals will receive the full set of qualifiers that were
1975 /// applied to the array.
1977 /// \returns if this is an array type, the completely unqualified array type
1978 /// that corresponds to it. Otherwise, returns T.getUnqualifiedType().
1979 QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals);
1981 /// \brief Determine whether the given types are equivalent after
1982 /// cvr-qualifiers have been removed.
1983 bool hasSameUnqualifiedType(QualType T1, QualType T2) const {
1984 return getCanonicalType(T1).getTypePtr() ==
1985 getCanonicalType(T2).getTypePtr();
1988 bool hasSameNullabilityTypeQualifier(QualType SubT, QualType SuperT,
1989 bool IsParam) const {
1990 auto SubTnullability = SubT->getNullability(*this);
1991 auto SuperTnullability = SuperT->getNullability(*this);
1992 if (SubTnullability.hasValue() == SuperTnullability.hasValue()) {
1993 // Neither has nullability; return true
1994 if (!SubTnullability)
1996 // Both have nullability qualifier.
1997 if (*SubTnullability == *SuperTnullability ||
1998 *SubTnullability == NullabilityKind::Unspecified ||
1999 *SuperTnullability == NullabilityKind::Unspecified)
2003 // Ok for the superclass method parameter to be "nonnull" and the subclass
2004 // method parameter to be "nullable"
2005 return (*SuperTnullability == NullabilityKind::NonNull &&
2006 *SubTnullability == NullabilityKind::Nullable);
2009 // For the return type, it's okay for the superclass method to specify
2010 // "nullable" and the subclass method specify "nonnull"
2011 return (*SuperTnullability == NullabilityKind::Nullable &&
2012 *SubTnullability == NullabilityKind::NonNull);
2018 bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
2019 const ObjCMethodDecl *MethodImp);
2021 bool UnwrapSimilarPointerTypes(QualType &T1, QualType &T2);
2023 /// \brief Retrieves the "canonical" nested name specifier for a
2024 /// given nested name specifier.
2026 /// The canonical nested name specifier is a nested name specifier
2027 /// that uniquely identifies a type or namespace within the type
2028 /// system. For example, given:
2033 /// template<typename T> struct X { typename T* type; };
2037 /// template<typename T> struct Y {
2038 /// typename N::S::X<T>::type member;
2042 /// Here, the nested-name-specifier for N::S::X<T>:: will be
2043 /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined
2044 /// by declarations in the type system and the canonical type for
2045 /// the template type parameter 'T' is template-param-0-0.
2046 NestedNameSpecifier *
2047 getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const;
2049 /// \brief Retrieves the default calling convention for the current target.
2050 CallingConv getDefaultCallingConvention(bool isVariadic,
2051 bool IsCXXMethod) const;
2053 /// \brief Retrieves the "canonical" template name that refers to a
2056 /// The canonical template name is the simplest expression that can
2057 /// be used to refer to a given template. For most templates, this
2058 /// expression is just the template declaration itself. For example,
2059 /// the template std::vector can be referred to via a variety of
2060 /// names---std::vector, \::std::vector, vector (if vector is in
2061 /// scope), etc.---but all of these names map down to the same
2062 /// TemplateDecl, which is used to form the canonical template name.
2064 /// Dependent template names are more interesting. Here, the
2065 /// template name could be something like T::template apply or
2066 /// std::allocator<T>::template rebind, where the nested name
2067 /// specifier itself is dependent. In this case, the canonical
2068 /// template name uses the shortest form of the dependent
2069 /// nested-name-specifier, which itself contains all canonical
2070 /// types, values, and templates.
2071 TemplateName getCanonicalTemplateName(TemplateName Name) const;
2073 /// \brief Determine whether the given template names refer to the same
2075 bool hasSameTemplateName(TemplateName X, TemplateName Y);
2077 /// \brief Retrieve the "canonical" template argument.
2079 /// The canonical template argument is the simplest template argument
2080 /// (which may be a type, value, expression, or declaration) that
2081 /// expresses the value of the argument.
2082 TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg)
2085 /// Type Query functions. If the type is an instance of the specified class,
2086 /// return the Type pointer for the underlying maximally pretty type. This
2087 /// is a member of ASTContext because this may need to do some amount of
2088 /// canonicalization, e.g. to move type qualifiers into the element type.
2089 const ArrayType *getAsArrayType(QualType T) const;
2090 const ConstantArrayType *getAsConstantArrayType(QualType T) const {
2091 return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T));
2093 const VariableArrayType *getAsVariableArrayType(QualType T) const {
2094 return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T));
2096 const IncompleteArrayType *getAsIncompleteArrayType(QualType T) const {
2097 return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
2099 const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T)
2101 return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T));
2104 /// \brief Return the innermost element type of an array type.
2106 /// For example, will return "int" for int[m][n]
2107 QualType getBaseElementType(const ArrayType *VAT) const;
2109 /// \brief Return the innermost element type of a type (which needn't
2110 /// actually be an array type).
2111 QualType getBaseElementType(QualType QT) const;
2113 /// \brief Return number of constant array elements.
2114 uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const;
2116 /// \brief Perform adjustment on the parameter type of a function.
2118 /// This routine adjusts the given parameter type @p T to the actual
2119 /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
2120 /// C++ [dcl.fct]p3). The adjusted parameter type is returned.
2121 QualType getAdjustedParameterType(QualType T) const;
2123 /// \brief Retrieve the parameter type as adjusted for use in the signature
2124 /// of a function, decaying array and function types and removing top-level
2126 QualType getSignatureParameterType(QualType T) const;
2128 QualType getExceptionObjectType(QualType T) const;
2130 /// \brief Return the properly qualified result of decaying the specified
2131 /// array type to a pointer.
2133 /// This operation is non-trivial when handling typedefs etc. The canonical
2134 /// type of \p T must be an array type, this returns a pointer to a properly
2135 /// qualified element of the array.
2137 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2138 QualType getArrayDecayedType(QualType T) const;
2140 /// \brief Return the type that \p PromotableType will promote to: C99
2141 /// 6.3.1.1p2, assuming that \p PromotableType is a promotable integer type.
2142 QualType getPromotedIntegerType(QualType PromotableType) const;
2144 /// \brief Recurses in pointer/array types until it finds an Objective-C
2145 /// retainable type and returns its ownership.
2146 Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const;
2148 /// \brief Whether this is a promotable bitfield reference according
2149 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2151 /// \returns the type this bit-field will promote to, or NULL if no
2152 /// promotion occurs.
2153 QualType isPromotableBitField(Expr *E) const;
2155 /// \brief Return the highest ranked integer type, see C99 6.3.1.8p1.
2157 /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
2158 /// \p LHS < \p RHS, return -1.
2159 int getIntegerTypeOrder(QualType LHS, QualType RHS) const;
2161 /// \brief Compare the rank of the two specified floating point types,
2162 /// ignoring the domain of the type (i.e. 'double' == '_Complex double').
2164 /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
2165 /// \p LHS < \p RHS, return -1.
2166 int getFloatingTypeOrder(QualType LHS, QualType RHS) const;
2168 /// \brief Return a real floating point or a complex type (based on
2169 /// \p typeDomain/\p typeSize).
2171 /// \param typeDomain a real floating point or complex type.
2172 /// \param typeSize a real floating point or complex type.
2173 QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
2174 QualType typeDomain) const;
2176 unsigned getTargetAddressSpace(QualType T) const {
2177 return getTargetAddressSpace(T.getQualifiers());
2180 unsigned getTargetAddressSpace(Qualifiers Q) const {
2181 return getTargetAddressSpace(Q.getAddressSpace());
2184 unsigned getTargetAddressSpace(unsigned AS) const {
2185 if (AS < LangAS::Offset || AS >= LangAS::Offset + LangAS::Count)
2188 return (*AddrSpaceMap)[AS - LangAS::Offset];
2191 bool addressSpaceMapManglingFor(unsigned AS) const {
2192 return AddrSpaceMapMangling ||
2193 AS < LangAS::Offset ||
2194 AS >= LangAS::Offset + LangAS::Count;
2198 // Helper for integer ordering
2199 unsigned getIntegerRank(const Type *T) const;
2203 //===--------------------------------------------------------------------===//
2204 // Type Compatibility Predicates
2205 //===--------------------------------------------------------------------===//
2207 /// Compatibility predicates used to check assignment expressions.
2208 bool typesAreCompatible(QualType T1, QualType T2,
2209 bool CompareUnqualified = false); // C99 6.2.7p1
2211 bool propertyTypesAreCompatible(QualType, QualType);
2212 bool typesAreBlockPointerCompatible(QualType, QualType);
2214 bool isObjCIdType(QualType T) const {
2215 return T == getObjCIdType();
2217 bool isObjCClassType(QualType T) const {
2218 return T == getObjCClassType();
2220 bool isObjCSelType(QualType T) const {
2221 return T == getObjCSelType();
2223 bool ObjCQualifiedIdTypesAreCompatible(QualType LHS, QualType RHS,
2226 bool ObjCQualifiedClassTypesAreCompatible(QualType LHS, QualType RHS);
2228 // Check the safety of assignment from LHS to RHS
2229 bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
2230 const ObjCObjectPointerType *RHSOPT);
2231 bool canAssignObjCInterfaces(const ObjCObjectType *LHS,
2232 const ObjCObjectType *RHS);
2233 bool canAssignObjCInterfacesInBlockPointer(
2234 const ObjCObjectPointerType *LHSOPT,
2235 const ObjCObjectPointerType *RHSOPT,
2236 bool BlockReturnType);
2237 bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
2238 QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT,
2239 const ObjCObjectPointerType *RHSOPT);
2240 bool canBindObjCObjectType(QualType To, QualType From);
2242 // Functions for calculating composite types
2243 QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false,
2244 bool Unqualified = false, bool BlockReturnType = false);
2245 QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false,
2246 bool Unqualified = false);
2247 QualType mergeFunctionParameterTypes(QualType, QualType,
2248 bool OfBlockPointer = false,
2249 bool Unqualified = false);
2250 QualType mergeTransparentUnionType(QualType, QualType,
2251 bool OfBlockPointer=false,
2252 bool Unqualified = false);
2254 QualType mergeObjCGCQualifiers(QualType, QualType);
2256 bool FunctionTypesMatchOnNSConsumedAttrs(
2257 const FunctionProtoType *FromFunctionType,
2258 const FunctionProtoType *ToFunctionType);
2260 void ResetObjCLayout(const ObjCContainerDecl *CD);
2262 //===--------------------------------------------------------------------===//
2263 // Integer Predicates
2264 //===--------------------------------------------------------------------===//
2266 // The width of an integer, as defined in C99 6.2.6.2. This is the number
2267 // of bits in an integer type excluding any padding bits.
2268 unsigned getIntWidth(QualType T) const;
2270 // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
2271 // unsigned integer type. This method takes a signed type, and returns the
2272 // corresponding unsigned integer type.
2273 QualType getCorrespondingUnsignedType(QualType T) const;
2275 //===--------------------------------------------------------------------===//
2277 //===--------------------------------------------------------------------===//
2279 /// \brief Make an APSInt of the appropriate width and signedness for the
2280 /// given \p Value and integer \p Type.
2281 llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const {
2282 llvm::APSInt Res(getIntWidth(Type),
2283 !Type->isSignedIntegerOrEnumerationType());
2288 bool isSentinelNullExpr(const Expr *E);
2290 /// \brief Get the implementation of the ObjCInterfaceDecl \p D, or NULL if
2292 ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D);
2293 /// \brief Get the implementation of the ObjCCategoryDecl \p D, or NULL if
2295 ObjCCategoryImplDecl *getObjCImplementation(ObjCCategoryDecl *D);
2297 /// \brief Return true if there is at least one \@implementation in the TU.
2298 bool AnyObjCImplementation() {
2299 return !ObjCImpls.empty();
2302 /// \brief Set the implementation of ObjCInterfaceDecl.
2303 void setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2304 ObjCImplementationDecl *ImplD);
2305 /// \brief Set the implementation of ObjCCategoryDecl.
2306 void setObjCImplementation(ObjCCategoryDecl *CatD,
2307 ObjCCategoryImplDecl *ImplD);
2309 /// \brief Get the duplicate declaration of a ObjCMethod in the same
2310 /// interface, or null if none exists.
2311 const ObjCMethodDecl *
2312 getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const;
2314 void setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2315 const ObjCMethodDecl *Redecl);
2317 /// \brief Returns the Objective-C interface that \p ND belongs to if it is
2318 /// an Objective-C method/property/ivar etc. that is part of an interface,
2319 /// otherwise returns null.
2320 const ObjCInterfaceDecl *getObjContainingInterface(const NamedDecl *ND) const;
2322 /// \brief Set the copy inialization expression of a block var decl.
2323 void setBlockVarCopyInits(VarDecl*VD, Expr* Init);
2324 /// \brief Get the copy initialization expression of the VarDecl \p VD, or
2325 /// NULL if none exists.
2326 Expr *getBlockVarCopyInits(const VarDecl* VD);
2328 /// \brief Allocate an uninitialized TypeSourceInfo.
2330 /// The caller should initialize the memory held by TypeSourceInfo using
2331 /// the TypeLoc wrappers.
2333 /// \param T the type that will be the basis for type source info. This type
2334 /// should refer to how the declarator was written in source code, not to
2335 /// what type semantic analysis resolved the declarator to.
2337 /// \param Size the size of the type info to create, or 0 if the size
2338 /// should be calculated based on the type.
2339 TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0) const;
2341 /// \brief Allocate a TypeSourceInfo where all locations have been
2342 /// initialized to a given location, which defaults to the empty
2345 getTrivialTypeSourceInfo(QualType T,
2346 SourceLocation Loc = SourceLocation()) const;
2348 /// \brief Add a deallocation callback that will be invoked when the
2349 /// ASTContext is destroyed.
2351 /// \param Callback A callback function that will be invoked on destruction.
2353 /// \param Data Pointer data that will be provided to the callback function
2354 /// when it is called.
2355 void AddDeallocation(void (*Callback)(void*), void *Data);
2357 GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const;
2358 GVALinkage GetGVALinkageForVariable(const VarDecl *VD);
2360 /// \brief Determines if the decl can be CodeGen'ed or deserialized from PCH
2361 /// lazily, only when used; this is only relevant for function or file scoped
2362 /// var definitions.
2364 /// \returns true if the function/var must be CodeGen'ed/deserialized even if
2366 bool DeclMustBeEmitted(const Decl *D);
2368 const CXXConstructorDecl *
2369 getCopyConstructorForExceptionObject(CXXRecordDecl *RD);
2371 void addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
2372 CXXConstructorDecl *CD);
2374 void addDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
2375 unsigned ParmIdx, Expr *DAE);
2377 Expr *getDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
2380 void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND);
2382 TypedefNameDecl *getTypedefNameForUnnamedTagDecl(const TagDecl *TD);
2384 void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD);
2386 DeclaratorDecl *getDeclaratorForUnnamedTagDecl(const TagDecl *TD);
2388 void setManglingNumber(const NamedDecl *ND, unsigned Number);
2389 unsigned getManglingNumber(const NamedDecl *ND) const;
2391 void setStaticLocalNumber(const VarDecl *VD, unsigned Number);
2392 unsigned getStaticLocalNumber(const VarDecl *VD) const;
2394 /// \brief Retrieve the context for computing mangling numbers in the given
2396 MangleNumberingContext &getManglingNumberContext(const DeclContext *DC);
2398 MangleNumberingContext *createMangleNumberingContext() const;
2400 /// \brief Used by ParmVarDecl to store on the side the
2401 /// index of the parameter when it exceeds the size of the normal bitfield.
2402 void setParameterIndex(const ParmVarDecl *D, unsigned index);
2404 /// \brief Used by ParmVarDecl to retrieve on the side the
2405 /// index of the parameter when it exceeds the size of the normal bitfield.
2406 unsigned getParameterIndex(const ParmVarDecl *D) const;
2408 /// \brief Get the storage for the constant value of a materialized temporary
2409 /// of static storage duration.
2410 APValue *getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
2413 //===--------------------------------------------------------------------===//
2415 //===--------------------------------------------------------------------===//
2417 /// \brief The number of implicitly-declared default constructors.
2418 static unsigned NumImplicitDefaultConstructors;
2420 /// \brief The number of implicitly-declared default constructors for
2421 /// which declarations were built.
2422 static unsigned NumImplicitDefaultConstructorsDeclared;
2424 /// \brief The number of implicitly-declared copy constructors.
2425 static unsigned NumImplicitCopyConstructors;
2427 /// \brief The number of implicitly-declared copy constructors for
2428 /// which declarations were built.
2429 static unsigned NumImplicitCopyConstructorsDeclared;
2431 /// \brief The number of implicitly-declared move constructors.
2432 static unsigned NumImplicitMoveConstructors;
2434 /// \brief The number of implicitly-declared move constructors for
2435 /// which declarations were built.
2436 static unsigned NumImplicitMoveConstructorsDeclared;
2438 /// \brief The number of implicitly-declared copy assignment operators.
2439 static unsigned NumImplicitCopyAssignmentOperators;
2441 /// \brief The number of implicitly-declared copy assignment operators for
2442 /// which declarations were built.
2443 static unsigned NumImplicitCopyAssignmentOperatorsDeclared;
2445 /// \brief The number of implicitly-declared move assignment operators.
2446 static unsigned NumImplicitMoveAssignmentOperators;
2448 /// \brief The number of implicitly-declared move assignment operators for
2449 /// which declarations were built.
2450 static unsigned NumImplicitMoveAssignmentOperatorsDeclared;
2452 /// \brief The number of implicitly-declared destructors.
2453 static unsigned NumImplicitDestructors;
2455 /// \brief The number of implicitly-declared destructors for which
2456 /// declarations were built.
2457 static unsigned NumImplicitDestructorsDeclared;
2460 ASTContext(const ASTContext &) = delete;
2461 void operator=(const ASTContext &) = delete;
2464 /// \brief Initialize built-in types.
2466 /// This routine may only be invoked once for a given ASTContext object.
2467 /// It is normally invoked after ASTContext construction.
2469 /// \param Target The target
2470 void InitBuiltinTypes(const TargetInfo &Target,
2471 const TargetInfo *AuxTarget = nullptr);
2474 void InitBuiltinType(CanQualType &R, BuiltinType::Kind K);
2476 // Return the Objective-C type encoding for a given type.
2477 void getObjCEncodingForTypeImpl(QualType t, std::string &S,
2478 bool ExpandPointedToStructures,
2479 bool ExpandStructures,
2480 const FieldDecl *Field,
2481 bool OutermostType = false,
2482 bool EncodingProperty = false,
2483 bool StructField = false,
2484 bool EncodeBlockParameters = false,
2485 bool EncodeClassNames = false,
2486 bool EncodePointerToObjCTypedef = false,
2487 QualType *NotEncodedT=nullptr) const;
2489 // Adds the encoding of the structure's members.
2490 void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S,
2491 const FieldDecl *Field,
2492 bool includeVBases = true,
2493 QualType *NotEncodedT=nullptr) const;
2495 // Adds the encoding of a method parameter or return type.
2496 void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
2497 QualType T, std::string& S,
2498 bool Extended) const;
2500 /// \brief Returns true if this is an inline-initialized static data member
2501 /// which is treated as a definition for MSVC compatibility.
2502 bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const;
2505 const ASTRecordLayout &
2506 getObjCLayout(const ObjCInterfaceDecl *D,
2507 const ObjCImplementationDecl *Impl) const;
2509 /// \brief A set of deallocations that should be performed when the
2510 /// ASTContext is destroyed.
2511 // FIXME: We really should have a better mechanism in the ASTContext to
2512 // manage running destructors for types which do variable sized allocation
2513 // within the AST. In some places we thread the AST bump pointer allocator
2514 // into the datastructures which avoids this mess during deallocation but is
2515 // wasteful of memory, and here we require a lot of error prone book keeping
2516 // in order to track and run destructors while we're tearing things down.
2517 typedef llvm::SmallVector<std::pair<void (*)(void *), void *>, 16>
2518 DeallocationFunctionsAndArguments;
2519 DeallocationFunctionsAndArguments Deallocations;
2521 // FIXME: This currently contains the set of StoredDeclMaps used
2522 // by DeclContext objects. This probably should not be in ASTContext,
2523 // but we include it here so that ASTContext can quickly deallocate them.
2524 llvm::PointerIntPair<StoredDeclsMap*,1> LastSDM;
2526 friend class DeclContext;
2527 friend class DeclarationNameTable;
2528 void ReleaseDeclContextMaps();
2529 void ReleaseParentMapEntries();
2531 std::unique_ptr<ParentMapPointers> PointerParents;
2532 std::unique_ptr<ParentMapOtherNodes> OtherParents;
2534 std::unique_ptr<VTableContextBase> VTContext;
2537 enum PragmaSectionFlag : unsigned {
2543 PSF_Invalid = 0x80000000U,
2546 struct SectionInfo {
2547 DeclaratorDecl *Decl;
2548 SourceLocation PragmaSectionLocation;
2551 SectionInfo(DeclaratorDecl *Decl,
2552 SourceLocation PragmaSectionLocation,
2555 PragmaSectionLocation(PragmaSectionLocation),
2556 SectionFlags(SectionFlags) {}
2559 llvm::StringMap<SectionInfo> SectionInfos;
2562 /// \brief Utility function for constructing a nullary selector.
2563 static inline Selector GetNullarySelector(StringRef name, ASTContext& Ctx) {
2564 IdentifierInfo* II = &Ctx.Idents.get(name);
2565 return Ctx.Selectors.getSelector(0, &II);
2568 /// \brief Utility function for constructing an unary selector.
2569 static inline Selector GetUnarySelector(StringRef name, ASTContext& Ctx) {
2570 IdentifierInfo* II = &Ctx.Idents.get(name);
2571 return Ctx.Selectors.getSelector(1, &II);
2574 } // end namespace clang
2576 // operator new and delete aren't allowed inside namespaces.
2578 /// @brief Placement new for using the ASTContext's allocator.
2580 /// This placement form of operator new uses the ASTContext's allocator for
2581 /// obtaining memory.
2583 /// IMPORTANT: These are also declared in clang/AST/AttrIterator.h! Any changes
2584 /// here need to also be made there.
2586 /// We intentionally avoid using a nothrow specification here so that the calls
2587 /// to this operator will not perform a null check on the result -- the
2588 /// underlying allocator never returns null pointers.
2590 /// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
2592 /// // Default alignment (8)
2593 /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
2594 /// // Specific alignment
2595 /// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
2597 /// Memory allocated through this placement new operator does not need to be
2598 /// explicitly freed, as ASTContext will free all of this memory when it gets
2599 /// destroyed. Please note that you cannot use delete on the pointer.
2601 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
2602 /// @param C The ASTContext that provides the allocator.
2603 /// @param Alignment The alignment of the allocated memory (if the underlying
2604 /// allocator supports it).
2605 /// @return The allocated memory. Could be NULL.
2606 inline void *operator new(size_t Bytes, const clang::ASTContext &C,
2608 return C.Allocate(Bytes, Alignment);
2610 /// @brief Placement delete companion to the new above.
2612 /// This operator is just a companion to the new above. There is no way of
2613 /// invoking it directly; see the new operator for more details. This operator
2614 /// is called implicitly by the compiler if a placement new expression using
2615 /// the ASTContext throws in the object constructor.
2616 inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t) {
2620 /// This placement form of operator new[] uses the ASTContext's allocator for
2621 /// obtaining memory.
2623 /// We intentionally avoid using a nothrow specification here so that the calls
2624 /// to this operator will not perform a null check on the result -- the
2625 /// underlying allocator never returns null pointers.
2627 /// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
2629 /// // Default alignment (8)
2630 /// char *data = new (Context) char[10];
2631 /// // Specific alignment
2632 /// char *data = new (Context, 4) char[10];
2634 /// Memory allocated through this placement new[] operator does not need to be
2635 /// explicitly freed, as ASTContext will free all of this memory when it gets
2636 /// destroyed. Please note that you cannot use delete on the pointer.
2638 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
2639 /// @param C The ASTContext that provides the allocator.
2640 /// @param Alignment The alignment of the allocated memory (if the underlying
2641 /// allocator supports it).
2642 /// @return The allocated memory. Could be NULL.
2643 inline void *operator new[](size_t Bytes, const clang::ASTContext& C,
2644 size_t Alignment = 8) {
2645 return C.Allocate(Bytes, Alignment);
2648 /// @brief Placement delete[] companion to the new[] above.
2650 /// This operator is just a companion to the new[] above. There is no way of
2651 /// invoking it directly; see the new[] operator for more details. This operator
2652 /// is called implicitly by the compiler if a placement new[] expression using
2653 /// the ASTContext throws in the object constructor.
2654 inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_t) {
2658 /// \brief Create the representation of a LazyGenerationalUpdatePtr.
2659 template <typename Owner, typename T,
2660 void (clang::ExternalASTSource::*Update)(Owner)>
2661 typename clang::LazyGenerationalUpdatePtr<Owner, T, Update>::ValueType
2662 clang::LazyGenerationalUpdatePtr<Owner, T, Update>::makeValue(
2663 const clang::ASTContext &Ctx, T Value) {
2664 // Note, this is implemented here so that ExternalASTSource.h doesn't need to
2665 // include ASTContext.h. We explicitly instantiate it for all relevant types
2666 // in ASTContext.cpp.
2667 if (auto *Source = Ctx.getExternalSource())
2668 return new (Ctx) LazyData(Source, Value);