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/DeclBase.h"
23 #include "clang/AST/DeclarationName.h"
24 #include "clang/AST/ExternalASTSource.h"
25 #include "clang/AST/NestedNameSpecifier.h"
26 #include "clang/AST/PrettyPrinter.h"
27 #include "clang/AST/RawCommentList.h"
28 #include "clang/AST/TemplateBase.h"
29 #include "clang/AST/TemplateName.h"
30 #include "clang/AST/Type.h"
31 #include "clang/Basic/AddressSpaces.h"
32 #include "clang/Basic/IdentifierTable.h"
33 #include "clang/Basic/LLVM.h"
34 #include "clang/Basic/LangOptions.h"
35 #include "clang/Basic/Linkage.h"
36 #include "clang/Basic/OperatorKinds.h"
37 #include "clang/Basic/PartialDiagnostic.h"
38 #include "clang/Basic/SanitizerBlacklist.h"
39 #include "clang/Basic/SourceLocation.h"
40 #include "clang/Basic/Specifiers.h"
41 #include "clang/Basic/TargetInfo.h"
42 #include "clang/Basic/XRayLists.h"
43 #include "llvm/ADT/APSInt.h"
44 #include "llvm/ADT/ArrayRef.h"
45 #include "llvm/ADT/DenseMap.h"
46 #include "llvm/ADT/FoldingSet.h"
47 #include "llvm/ADT/IntrusiveRefCntPtr.h"
48 #include "llvm/ADT/MapVector.h"
49 #include "llvm/ADT/None.h"
50 #include "llvm/ADT/Optional.h"
51 #include "llvm/ADT/PointerIntPair.h"
52 #include "llvm/ADT/PointerUnion.h"
53 #include "llvm/ADT/SmallVector.h"
54 #include "llvm/ADT/StringMap.h"
55 #include "llvm/ADT/StringRef.h"
56 #include "llvm/ADT/TinyPtrVector.h"
57 #include "llvm/ADT/Triple.h"
58 #include "llvm/ADT/iterator_range.h"
59 #include "llvm/Support/AlignOf.h"
60 #include "llvm/Support/Allocator.h"
61 #include "llvm/Support/Casting.h"
62 #include "llvm/Support/Compiler.h"
69 #include <type_traits>
82 class ASTMutationListener;
83 class ASTRecordLayout;
86 class BuiltinTemplateDecl;
89 class CXXConstructorDecl;
92 class DiagnosticsEngine;
95 class MangleNumberingContext;
96 class MaterializeTemporaryExpr;
97 class MemberSpecializationInfo;
99 class ObjCCategoryDecl;
100 class ObjCCategoryImplDecl;
101 class ObjCContainerDecl;
103 class ObjCImplementationDecl;
104 class ObjCInterfaceDecl;
106 class ObjCMethodDecl;
107 class ObjCPropertyDecl;
108 class ObjCPropertyImplDecl;
109 class ObjCProtocolDecl;
110 class ObjCTypeParamDecl;
113 class StoredDeclsMap;
115 class TemplateParameterList;
116 class TemplateTemplateParmDecl;
117 class TemplateTypeParmDecl;
118 class UnresolvedSetIterator;
119 class UsingShadowDecl;
120 class VarTemplateDecl;
121 class VTableContextBase;
127 } // namespace Builtin
129 enum BuiltinTemplateKind : int;
135 } // namespace comments
140 bool AlignIsRequired : 1;
142 TypeInfo() : AlignIsRequired(false) {}
143 TypeInfo(uint64_t Width, unsigned Align, bool AlignIsRequired)
144 : Width(Width), Align(Align), AlignIsRequired(AlignIsRequired) {}
147 /// \brief Holds long-lived AST nodes (such as types and decls) that can be
148 /// referred to throughout the semantic analysis of a file.
149 class ASTContext : public RefCountedBase<ASTContext> {
150 friend class NestedNameSpecifier;
152 mutable SmallVector<Type *, 0> Types;
153 mutable llvm::FoldingSet<ExtQuals> ExtQualNodes;
154 mutable llvm::FoldingSet<ComplexType> ComplexTypes;
155 mutable llvm::FoldingSet<PointerType> PointerTypes;
156 mutable llvm::FoldingSet<AdjustedType> AdjustedTypes;
157 mutable llvm::FoldingSet<BlockPointerType> BlockPointerTypes;
158 mutable llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes;
159 mutable llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes;
160 mutable llvm::FoldingSet<MemberPointerType> MemberPointerTypes;
161 mutable llvm::FoldingSet<ConstantArrayType> ConstantArrayTypes;
162 mutable llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
163 mutable std::vector<VariableArrayType*> VariableArrayTypes;
164 mutable llvm::FoldingSet<DependentSizedArrayType> DependentSizedArrayTypes;
165 mutable llvm::FoldingSet<DependentSizedExtVectorType>
166 DependentSizedExtVectorTypes;
167 mutable llvm::FoldingSet<DependentAddressSpaceType>
168 DependentAddressSpaceTypes;
169 mutable llvm::FoldingSet<VectorType> VectorTypes;
170 mutable llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes;
171 mutable llvm::ContextualFoldingSet<FunctionProtoType, ASTContext&>
173 mutable llvm::FoldingSet<DependentTypeOfExprType> DependentTypeOfExprTypes;
174 mutable llvm::FoldingSet<DependentDecltypeType> DependentDecltypeTypes;
175 mutable llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes;
176 mutable llvm::FoldingSet<ObjCTypeParamType> ObjCTypeParamTypes;
177 mutable llvm::FoldingSet<SubstTemplateTypeParmType>
178 SubstTemplateTypeParmTypes;
179 mutable llvm::FoldingSet<SubstTemplateTypeParmPackType>
180 SubstTemplateTypeParmPackTypes;
181 mutable llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&>
182 TemplateSpecializationTypes;
183 mutable llvm::FoldingSet<ParenType> ParenTypes;
184 mutable llvm::FoldingSet<ElaboratedType> ElaboratedTypes;
185 mutable llvm::FoldingSet<DependentNameType> DependentNameTypes;
186 mutable llvm::ContextualFoldingSet<DependentTemplateSpecializationType,
188 DependentTemplateSpecializationTypes;
189 llvm::FoldingSet<PackExpansionType> PackExpansionTypes;
190 mutable llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes;
191 mutable llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes;
192 mutable llvm::FoldingSet<DependentUnaryTransformType>
193 DependentUnaryTransformTypes;
194 mutable llvm::FoldingSet<AutoType> AutoTypes;
195 mutable llvm::FoldingSet<DeducedTemplateSpecializationType>
196 DeducedTemplateSpecializationTypes;
197 mutable llvm::FoldingSet<AtomicType> AtomicTypes;
198 llvm::FoldingSet<AttributedType> AttributedTypes;
199 mutable llvm::FoldingSet<PipeType> PipeTypes;
201 mutable llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames;
202 mutable llvm::FoldingSet<DependentTemplateName> DependentTemplateNames;
203 mutable llvm::FoldingSet<SubstTemplateTemplateParmStorage>
204 SubstTemplateTemplateParms;
205 mutable llvm::ContextualFoldingSet<SubstTemplateTemplateParmPackStorage,
207 SubstTemplateTemplateParmPacks;
209 /// \brief The set of nested name specifiers.
211 /// This set is managed by the NestedNameSpecifier class.
212 mutable llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers;
213 mutable NestedNameSpecifier *GlobalNestedNameSpecifier = nullptr;
215 /// \brief A cache mapping from RecordDecls to ASTRecordLayouts.
217 /// This is lazily created. This is intentionally not serialized.
218 mutable llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>
220 mutable llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>
223 /// \brief A cache from types to size and alignment information.
224 using TypeInfoMap = llvm::DenseMap<const Type *, struct TypeInfo>;
225 mutable TypeInfoMap MemoizedTypeInfo;
227 /// \brief A cache mapping from CXXRecordDecls to key functions.
228 llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr> KeyFunctions;
230 /// \brief Mapping from ObjCContainers to their ObjCImplementations.
231 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls;
233 /// \brief Mapping from ObjCMethod to its duplicate declaration in the same
235 llvm::DenseMap<const ObjCMethodDecl*,const ObjCMethodDecl*> ObjCMethodRedecls;
237 /// \brief Mapping from __block VarDecls to their copy initialization expr.
238 llvm::DenseMap<const VarDecl*, Expr*> BlockVarCopyInits;
240 /// \brief Mapping from class scope functions specialization to their
241 /// template patterns.
242 llvm::DenseMap<const FunctionDecl*, FunctionDecl*>
243 ClassScopeSpecializationPattern;
245 /// \brief Mapping from materialized temporaries with static storage duration
246 /// that appear in constant initializers to their evaluated values. These are
247 /// allocated in a std::map because their address must be stable.
248 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue *>
249 MaterializedTemporaryValues;
251 /// \brief Representation of a "canonical" template template parameter that
252 /// is used in canonical template names.
253 class CanonicalTemplateTemplateParm : public llvm::FoldingSetNode {
254 TemplateTemplateParmDecl *Parm;
257 CanonicalTemplateTemplateParm(TemplateTemplateParmDecl *Parm)
260 TemplateTemplateParmDecl *getParam() const { return Parm; }
262 void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, Parm); }
264 static void Profile(llvm::FoldingSetNodeID &ID,
265 TemplateTemplateParmDecl *Parm);
267 mutable llvm::FoldingSet<CanonicalTemplateTemplateParm>
268 CanonTemplateTemplateParms;
270 TemplateTemplateParmDecl *
271 getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const;
273 /// \brief The typedef for the __int128_t type.
274 mutable TypedefDecl *Int128Decl = nullptr;
276 /// \brief The typedef for the __uint128_t type.
277 mutable TypedefDecl *UInt128Decl = nullptr;
279 /// \brief The typedef for the target specific predefined
280 /// __builtin_va_list type.
281 mutable TypedefDecl *BuiltinVaListDecl = nullptr;
283 /// The typedef for the predefined \c __builtin_ms_va_list type.
284 mutable TypedefDecl *BuiltinMSVaListDecl = nullptr;
286 /// \brief The typedef for the predefined \c id type.
287 mutable TypedefDecl *ObjCIdDecl = nullptr;
289 /// \brief The typedef for the predefined \c SEL type.
290 mutable TypedefDecl *ObjCSelDecl = nullptr;
292 /// \brief The typedef for the predefined \c Class type.
293 mutable TypedefDecl *ObjCClassDecl = nullptr;
295 /// \brief The typedef for the predefined \c Protocol class in Objective-C.
296 mutable ObjCInterfaceDecl *ObjCProtocolClassDecl = nullptr;
298 /// \brief The typedef for the predefined 'BOOL' type.
299 mutable TypedefDecl *BOOLDecl = nullptr;
301 // Typedefs which may be provided defining the structure of Objective-C
303 QualType ObjCIdRedefinitionType;
304 QualType ObjCClassRedefinitionType;
305 QualType ObjCSelRedefinitionType;
307 /// The identifier 'bool'.
308 mutable IdentifierInfo *BoolName = nullptr;
310 /// The identifier 'NSObject'.
311 IdentifierInfo *NSObjectName = nullptr;
313 /// The identifier 'NSCopying'.
314 IdentifierInfo *NSCopyingName = nullptr;
316 /// The identifier '__make_integer_seq'.
317 mutable IdentifierInfo *MakeIntegerSeqName = nullptr;
319 /// The identifier '__type_pack_element'.
320 mutable IdentifierInfo *TypePackElementName = nullptr;
322 QualType ObjCConstantStringType;
323 mutable RecordDecl *CFConstantStringTagDecl = nullptr;
324 mutable TypedefDecl *CFConstantStringTypeDecl = nullptr;
326 mutable QualType ObjCSuperType;
328 QualType ObjCNSStringType;
330 /// \brief The typedef declaration for the Objective-C "instancetype" type.
331 TypedefDecl *ObjCInstanceTypeDecl = nullptr;
333 /// \brief The type for the C FILE type.
334 TypeDecl *FILEDecl = nullptr;
336 /// \brief The type for the C jmp_buf type.
337 TypeDecl *jmp_bufDecl = nullptr;
339 /// \brief The type for the C sigjmp_buf type.
340 TypeDecl *sigjmp_bufDecl = nullptr;
342 /// \brief The type for the C ucontext_t type.
343 TypeDecl *ucontext_tDecl = nullptr;
345 /// \brief Type for the Block descriptor for Blocks CodeGen.
347 /// Since this is only used for generation of debug info, it is not
349 mutable RecordDecl *BlockDescriptorType = nullptr;
351 /// \brief Type for the Block descriptor for Blocks CodeGen.
353 /// Since this is only used for generation of debug info, it is not
355 mutable RecordDecl *BlockDescriptorExtendedType = nullptr;
357 /// \brief Declaration for the CUDA cudaConfigureCall function.
358 FunctionDecl *cudaConfigureCallDecl = nullptr;
360 /// \brief Keeps track of all declaration attributes.
362 /// Since so few decls have attrs, we keep them in a hash map instead of
363 /// wasting space in the Decl class.
364 llvm::DenseMap<const Decl*, AttrVec*> DeclAttrs;
366 /// \brief A mapping from non-redeclarable declarations in modules that were
367 /// merged with other declarations to the canonical declaration that they were
369 llvm::DenseMap<Decl*, Decl*> MergedDecls;
371 /// \brief A mapping from a defining declaration to a list of modules (other
372 /// than the owning module of the declaration) that contain merged
373 /// definitions of that entity.
374 llvm::DenseMap<NamedDecl*, llvm::TinyPtrVector<Module*>> MergedDefModules;
376 /// \brief Initializers for a module, in order. Each Decl will be either
377 /// something that has a semantic effect on startup (such as a variable with
378 /// a non-constant initializer), or an ImportDecl (which recursively triggers
379 /// initialization of another module).
380 struct PerModuleInitializers {
381 llvm::SmallVector<Decl*, 4> Initializers;
382 llvm::SmallVector<uint32_t, 4> LazyInitializers;
384 void resolve(ASTContext &Ctx);
386 llvm::DenseMap<Module*, PerModuleInitializers*> ModuleInitializers;
388 ASTContext &this_() { return *this; }
391 /// \brief A type synonym for the TemplateOrInstantiation mapping.
392 using TemplateOrSpecializationInfo =
393 llvm::PointerUnion<VarTemplateDecl *, MemberSpecializationInfo *>;
396 friend class ASTDeclReader;
397 friend class ASTReader;
398 friend class ASTWriter;
399 friend class CXXRecordDecl;
401 /// \brief A mapping to contain the template or declaration that
402 /// a variable declaration describes or was instantiated from,
405 /// For non-templates, this value will be NULL. For variable
406 /// declarations that describe a variable template, this will be a
407 /// pointer to a VarTemplateDecl. For static data members
408 /// of class template specializations, this will be the
409 /// MemberSpecializationInfo referring to the member variable that was
410 /// instantiated or specialized. Thus, the mapping will keep track of
411 /// the static data member templates from which static data members of
412 /// class template specializations were instantiated.
414 /// Given the following example:
417 /// template<typename T>
422 /// template<typename T>
423 /// T X<T>::value = T(17);
425 /// int *x = &X<int>::value;
428 /// This mapping will contain an entry that maps from the VarDecl for
429 /// X<int>::value to the corresponding VarDecl for X<T>::value (within the
430 /// class template X) and will be marked TSK_ImplicitInstantiation.
431 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>
432 TemplateOrInstantiation;
434 /// \brief Keeps track of the declaration from which a using declaration was
435 /// created during instantiation.
437 /// The source and target declarations are always a UsingDecl, an
438 /// UnresolvedUsingValueDecl, or an UnresolvedUsingTypenameDecl.
442 /// template<typename T>
447 /// template<typename T>
448 /// struct B : A<T> {
452 /// template struct B<int>;
455 /// This mapping will contain an entry that maps from the UsingDecl in
456 /// B<int> to the UnresolvedUsingDecl in B<T>.
457 llvm::DenseMap<NamedDecl *, NamedDecl *> InstantiatedFromUsingDecl;
459 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>
460 InstantiatedFromUsingShadowDecl;
462 llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl;
464 /// \brief Mapping that stores the methods overridden by a given C++
467 /// Since most C++ member functions aren't virtual and therefore
468 /// don't override anything, we store the overridden functions in
469 /// this map on the side rather than within the CXXMethodDecl structure.
470 using CXXMethodVector = llvm::TinyPtrVector<const CXXMethodDecl *>;
471 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector> OverriddenMethods;
473 /// \brief Mapping from each declaration context to its corresponding
474 /// mangling numbering context (used for constructs like lambdas which
475 /// need to be consistently numbered for the mangler).
476 llvm::DenseMap<const DeclContext *, std::unique_ptr<MangleNumberingContext>>
477 MangleNumberingContexts;
479 /// \brief Side-table of mangling numbers for declarations which rarely
480 /// need them (like static local vars).
481 llvm::MapVector<const NamedDecl *, unsigned> MangleNumbers;
482 llvm::MapVector<const VarDecl *, unsigned> StaticLocalNumbers;
484 /// \brief Mapping that stores parameterIndex values for ParmVarDecls when
485 /// that value exceeds the bitfield size of ParmVarDeclBits.ParameterIndex.
486 using ParameterIndexTable = llvm::DenseMap<const VarDecl *, unsigned>;
487 ParameterIndexTable ParamIndices;
489 ImportDecl *FirstLocalImport = nullptr;
490 ImportDecl *LastLocalImport = nullptr;
492 TranslationUnitDecl *TUDecl;
493 mutable ExternCContextDecl *ExternCContext = nullptr;
494 mutable BuiltinTemplateDecl *MakeIntegerSeqDecl = nullptr;
495 mutable BuiltinTemplateDecl *TypePackElementDecl = nullptr;
497 /// \brief The associated SourceManager object.
498 SourceManager &SourceMgr;
500 /// \brief The language options used to create the AST associated with
501 /// this ASTContext object.
502 LangOptions &LangOpts;
504 /// \brief Blacklist object that is used by sanitizers to decide which
505 /// entities should not be instrumented.
506 std::unique_ptr<SanitizerBlacklist> SanitizerBL;
508 /// \brief Function filtering mechanism to determine whether a given function
509 /// should be imbued with the XRay "always" or "never" attributes.
510 std::unique_ptr<XRayFunctionFilter> XRayFilter;
512 /// \brief The allocator used to create AST objects.
514 /// AST objects are never destructed; rather, all memory associated with the
515 /// AST objects will be released when the ASTContext itself is destroyed.
516 mutable llvm::BumpPtrAllocator BumpAlloc;
518 /// \brief Allocator for partial diagnostics.
519 PartialDiagnostic::StorageAllocator DiagAllocator;
521 /// \brief The current C++ ABI.
522 std::unique_ptr<CXXABI> ABI;
523 CXXABI *createCXXABI(const TargetInfo &T);
525 /// \brief The logical -> physical address space map.
526 const LangASMap *AddrSpaceMap = nullptr;
528 /// \brief Address space map mangling must be used with language specific
529 /// address spaces (e.g. OpenCL/CUDA)
530 bool AddrSpaceMapMangling;
532 const TargetInfo *Target = nullptr;
533 const TargetInfo *AuxTarget = nullptr;
534 clang::PrintingPolicy PrintingPolicy;
537 IdentifierTable &Idents;
538 SelectorTable &Selectors;
539 Builtin::Context &BuiltinInfo;
540 mutable DeclarationNameTable DeclarationNames;
541 IntrusiveRefCntPtr<ExternalASTSource> ExternalSource;
542 ASTMutationListener *Listener = nullptr;
544 /// \brief Contains parents of a node.
545 using ParentVector = llvm::SmallVector<ast_type_traits::DynTypedNode, 2>;
547 /// \brief Maps from a node to its parents. This is used for nodes that have
548 /// pointer identity only, which are more common and we can save space by
549 /// only storing a unique pointer to them.
550 using ParentMapPointers =
551 llvm::DenseMap<const void *,
552 llvm::PointerUnion4<const Decl *, const Stmt *,
553 ast_type_traits::DynTypedNode *,
556 /// Parent map for nodes without pointer identity. We store a full
557 /// DynTypedNode for all keys.
558 using ParentMapOtherNodes =
559 llvm::DenseMap<ast_type_traits::DynTypedNode,
560 llvm::PointerUnion4<const Decl *, const Stmt *,
561 ast_type_traits::DynTypedNode *,
564 /// Container for either a single DynTypedNode or for an ArrayRef to
565 /// DynTypedNode. For use with ParentMap.
566 class DynTypedNodeList {
567 using DynTypedNode = ast_type_traits::DynTypedNode;
569 llvm::AlignedCharArrayUnion<ast_type_traits::DynTypedNode,
570 ArrayRef<DynTypedNode>> Storage;
574 DynTypedNodeList(const DynTypedNode &N) : IsSingleNode(true) {
575 new (Storage.buffer) DynTypedNode(N);
578 DynTypedNodeList(ArrayRef<DynTypedNode> A) : IsSingleNode(false) {
579 new (Storage.buffer) ArrayRef<DynTypedNode>(A);
582 const ast_type_traits::DynTypedNode *begin() const {
584 return reinterpret_cast<const ArrayRef<DynTypedNode> *>(Storage.buffer)
586 return reinterpret_cast<const DynTypedNode *>(Storage.buffer);
589 const ast_type_traits::DynTypedNode *end() const {
591 return reinterpret_cast<const ArrayRef<DynTypedNode> *>(Storage.buffer)
593 return reinterpret_cast<const DynTypedNode *>(Storage.buffer) + 1;
596 size_t size() const { return end() - begin(); }
597 bool empty() const { return begin() == end(); }
599 const DynTypedNode &operator[](size_t N) const {
600 assert(N < size() && "Out of bounds!");
601 return *(begin() + N);
605 /// \brief Returns the parents of the given node.
607 /// Note that this will lazily compute the parents of all nodes
608 /// and store them for later retrieval. Thus, the first call is O(n)
609 /// in the number of AST nodes.
611 /// Caveats and FIXMEs:
612 /// Calculating the parent map over all AST nodes will need to load the
613 /// full AST. This can be undesirable in the case where the full AST is
614 /// expensive to create (for example, when using precompiled header
615 /// preambles). Thus, there are good opportunities for optimization here.
616 /// One idea is to walk the given node downwards, looking for references
617 /// to declaration contexts - once a declaration context is found, compute
618 /// the parent map for the declaration context; if that can satisfy the
619 /// request, loading the whole AST can be avoided. Note that this is made
620 /// more complex by statements in templates having multiple parents - those
621 /// problems can be solved by building closure over the templated parts of
622 /// the AST, which also avoids touching large parts of the AST.
623 /// Additionally, we will want to add an interface to already give a hint
624 /// where to search for the parents, for example when looking at a statement
625 /// inside a certain function.
627 /// 'NodeT' can be one of Decl, Stmt, Type, TypeLoc,
628 /// NestedNameSpecifier or NestedNameSpecifierLoc.
629 template <typename NodeT> DynTypedNodeList getParents(const NodeT &Node) {
630 return getParents(ast_type_traits::DynTypedNode::create(Node));
633 DynTypedNodeList getParents(const ast_type_traits::DynTypedNode &Node);
635 const clang::PrintingPolicy &getPrintingPolicy() const {
636 return PrintingPolicy;
639 void setPrintingPolicy(const clang::PrintingPolicy &Policy) {
640 PrintingPolicy = Policy;
643 SourceManager& getSourceManager() { return SourceMgr; }
644 const SourceManager& getSourceManager() const { return SourceMgr; }
646 llvm::BumpPtrAllocator &getAllocator() const {
650 void *Allocate(size_t Size, unsigned Align = 8) const {
651 return BumpAlloc.Allocate(Size, Align);
653 template <typename T> T *Allocate(size_t Num = 1) const {
654 return static_cast<T *>(Allocate(Num * sizeof(T), alignof(T)));
656 void Deallocate(void *Ptr) const {}
658 /// Return the total amount of physical memory allocated for representing
659 /// AST nodes and type information.
660 size_t getASTAllocatedMemory() const {
661 return BumpAlloc.getTotalMemory();
664 /// Return the total memory used for various side tables.
665 size_t getSideTableAllocatedMemory() const;
667 PartialDiagnostic::StorageAllocator &getDiagAllocator() {
668 return DiagAllocator;
671 const TargetInfo &getTargetInfo() const { return *Target; }
672 const TargetInfo *getAuxTargetInfo() const { return AuxTarget; }
674 /// getIntTypeForBitwidth -
675 /// sets integer QualTy according to specified details:
676 /// bitwidth, signed/unsigned.
677 /// Returns empty type if there is no appropriate target types.
678 QualType getIntTypeForBitwidth(unsigned DestWidth,
679 unsigned Signed) const;
681 /// getRealTypeForBitwidth -
682 /// sets floating point QualTy according to specified bitwidth.
683 /// Returns empty type if there is no appropriate target types.
684 QualType getRealTypeForBitwidth(unsigned DestWidth) const;
686 bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const;
688 const LangOptions& getLangOpts() const { return LangOpts; }
690 const SanitizerBlacklist &getSanitizerBlacklist() const {
694 const XRayFunctionFilter &getXRayFilter() const {
698 DiagnosticsEngine &getDiagnostics() const;
700 FullSourceLoc getFullLoc(SourceLocation Loc) const {
701 return FullSourceLoc(Loc,SourceMgr);
704 /// \brief All comments in this translation unit.
705 RawCommentList Comments;
707 /// \brief True if comments are already loaded from ExternalASTSource.
708 mutable bool CommentsLoaded = false;
710 class RawCommentAndCacheFlags {
713 /// We searched for a comment attached to the particular declaration, but
719 /// We have found a comment attached to this particular declaration.
724 /// This declaration does not have an attached comment, and we have
725 /// searched the redeclaration chain.
727 /// If getRaw() == 0, the whole redeclaration chain does not have any
730 /// If getRaw() != 0, it is a comment propagated from other
735 Kind getKind() const LLVM_READONLY {
736 return Data.getInt();
739 void setKind(Kind K) {
743 const RawComment *getRaw() const LLVM_READONLY {
744 return Data.getPointer();
747 void setRaw(const RawComment *RC) {
751 const Decl *getOriginalDecl() const LLVM_READONLY {
755 void setOriginalDecl(const Decl *Orig) {
760 llvm::PointerIntPair<const RawComment *, 2, Kind> Data;
761 const Decl *OriginalDecl;
764 /// \brief Mapping from declarations to comments attached to any
767 /// Raw comments are owned by Comments list. This mapping is populated
769 mutable llvm::DenseMap<const Decl *, RawCommentAndCacheFlags> RedeclComments;
771 /// \brief Mapping from declarations to parsed comments attached to any
773 mutable llvm::DenseMap<const Decl *, comments::FullComment *> ParsedComments;
775 /// \brief Return the documentation comment attached to a given declaration,
776 /// without looking into cache.
777 RawComment *getRawCommentForDeclNoCache(const Decl *D) const;
780 RawCommentList &getRawCommentList() {
784 void addComment(const RawComment &RC) {
785 assert(LangOpts.RetainCommentsFromSystemHeaders ||
786 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
787 Comments.addComment(RC, BumpAlloc);
790 /// \brief Return the documentation comment attached to a given declaration.
791 /// Returns nullptr if no comment is attached.
793 /// \param OriginalDecl if not nullptr, is set to declaration AST node that
794 /// had the comment, if the comment we found comes from a redeclaration.
796 getRawCommentForAnyRedecl(const Decl *D,
797 const Decl **OriginalDecl = nullptr) const;
799 /// Return parsed documentation comment attached to a given declaration.
800 /// Returns nullptr if no comment is attached.
802 /// \param PP the Preprocessor used with this TU. Could be nullptr if
803 /// preprocessor is not available.
804 comments::FullComment *getCommentForDecl(const Decl *D,
805 const Preprocessor *PP) const;
807 /// Return parsed documentation comment attached to a given declaration.
808 /// Returns nullptr if no comment is attached. Does not look at any
809 /// redeclarations of the declaration.
810 comments::FullComment *getLocalCommentForDeclUncached(const Decl *D) const;
812 comments::FullComment *cloneFullComment(comments::FullComment *FC,
813 const Decl *D) const;
816 mutable comments::CommandTraits CommentCommandTraits;
818 /// \brief Iterator that visits import declarations.
819 class import_iterator {
820 ImportDecl *Import = nullptr;
823 using value_type = ImportDecl *;
824 using reference = ImportDecl *;
825 using pointer = ImportDecl *;
826 using difference_type = int;
827 using iterator_category = std::forward_iterator_tag;
829 import_iterator() = default;
830 explicit import_iterator(ImportDecl *Import) : Import(Import) {}
832 reference operator*() const { return Import; }
833 pointer operator->() const { return Import; }
835 import_iterator &operator++() {
836 Import = ASTContext::getNextLocalImport(Import);
840 import_iterator operator++(int) {
841 import_iterator Other(*this);
846 friend bool operator==(import_iterator X, import_iterator Y) {
847 return X.Import == Y.Import;
850 friend bool operator!=(import_iterator X, import_iterator Y) {
851 return X.Import != Y.Import;
856 comments::CommandTraits &getCommentCommandTraits() const {
857 return CommentCommandTraits;
860 /// \brief Retrieve the attributes for the given declaration.
861 AttrVec& getDeclAttrs(const Decl *D);
863 /// \brief Erase the attributes corresponding to the given declaration.
864 void eraseDeclAttrs(const Decl *D);
866 /// \brief If this variable is an instantiated static data member of a
867 /// class template specialization, returns the templated static data member
868 /// from which it was instantiated.
870 MemberSpecializationInfo *getInstantiatedFromStaticDataMember(
873 TemplateOrSpecializationInfo
874 getTemplateOrSpecializationInfo(const VarDecl *Var);
876 FunctionDecl *getClassScopeSpecializationPattern(const FunctionDecl *FD);
878 void setClassScopeSpecializationPattern(FunctionDecl *FD,
879 FunctionDecl *Pattern);
881 /// \brief Note that the static data member \p Inst is an instantiation of
882 /// the static data member template \p Tmpl of a class template.
883 void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
884 TemplateSpecializationKind TSK,
885 SourceLocation PointOfInstantiation = SourceLocation());
887 void setTemplateOrSpecializationInfo(VarDecl *Inst,
888 TemplateOrSpecializationInfo TSI);
890 /// \brief If the given using decl \p Inst is an instantiation of a
891 /// (possibly unresolved) using decl from a template instantiation,
893 NamedDecl *getInstantiatedFromUsingDecl(NamedDecl *Inst);
895 /// \brief Remember that the using decl \p Inst is an instantiation
896 /// of the using decl \p Pattern of a class template.
897 void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern);
899 void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
900 UsingShadowDecl *Pattern);
901 UsingShadowDecl *getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst);
903 FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field);
905 void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl);
907 // Access to the set of methods overridden by the given C++ method.
908 using overridden_cxx_method_iterator = CXXMethodVector::const_iterator;
909 overridden_cxx_method_iterator
910 overridden_methods_begin(const CXXMethodDecl *Method) const;
912 overridden_cxx_method_iterator
913 overridden_methods_end(const CXXMethodDecl *Method) const;
915 unsigned overridden_methods_size(const CXXMethodDecl *Method) const;
917 using overridden_method_range =
918 llvm::iterator_range<overridden_cxx_method_iterator>;
920 overridden_method_range overridden_methods(const CXXMethodDecl *Method) const;
922 /// \brief Note that the given C++ \p Method overrides the given \p
923 /// Overridden method.
924 void addOverriddenMethod(const CXXMethodDecl *Method,
925 const CXXMethodDecl *Overridden);
927 /// \brief Return C++ or ObjC overridden methods for the given \p Method.
929 /// An ObjC method is considered to override any method in the class's
930 /// base classes, its protocols, or its categories' protocols, that has
931 /// the same selector and is of the same kind (class or instance).
932 /// A method in an implementation is not considered as overriding the same
933 /// method in the interface or its categories.
934 void getOverriddenMethods(
935 const NamedDecl *Method,
936 SmallVectorImpl<const NamedDecl *> &Overridden) const;
938 /// \brief Notify the AST context that a new import declaration has been
939 /// parsed or implicitly created within this translation unit.
940 void addedLocalImportDecl(ImportDecl *Import);
942 static ImportDecl *getNextLocalImport(ImportDecl *Import) {
943 return Import->NextLocalImport;
946 using import_range = llvm::iterator_range<import_iterator>;
948 import_range local_imports() const {
949 return import_range(import_iterator(FirstLocalImport), import_iterator());
952 Decl *getPrimaryMergedDecl(Decl *D) {
953 Decl *Result = MergedDecls.lookup(D);
954 return Result ? Result : D;
956 void setPrimaryMergedDecl(Decl *D, Decl *Primary) {
957 MergedDecls[D] = Primary;
960 /// \brief Note that the definition \p ND has been merged into module \p M,
961 /// and should be visible whenever \p M is visible.
962 void mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
963 bool NotifyListeners = true);
965 /// \brief Clean up the merged definition list. Call this if you might have
966 /// added duplicates into the list.
967 void deduplicateMergedDefinitonsFor(NamedDecl *ND);
969 /// \brief Get the additional modules in which the definition \p Def has
971 ArrayRef<Module*> getModulesWithMergedDefinition(const NamedDecl *Def) {
972 auto MergedIt = MergedDefModules.find(Def);
973 if (MergedIt == MergedDefModules.end())
975 return MergedIt->second;
978 /// Add a declaration to the list of declarations that are initialized
979 /// for a module. This will typically be a global variable (with internal
980 /// linkage) that runs module initializers, such as the iostream initializer,
981 /// or an ImportDecl nominating another module that has initializers.
982 void addModuleInitializer(Module *M, Decl *Init);
984 void addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs);
986 /// Get the initializations to perform when importing a module, if any.
987 ArrayRef<Decl*> getModuleInitializers(Module *M);
989 TranslationUnitDecl *getTranslationUnitDecl() const { return TUDecl; }
991 ExternCContextDecl *getExternCContextDecl() const;
992 BuiltinTemplateDecl *getMakeIntegerSeqDecl() const;
993 BuiltinTemplateDecl *getTypePackElementDecl() const;
999 CanQualType WCharTy; // [C++ 3.9.1p5].
1000 CanQualType WideCharTy; // Same as WCharTy in C++, integer type in C99.
1001 CanQualType WIntTy; // [C99 7.24.1], integer type unchanged by default promotions.
1002 CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99.
1003 CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99.
1004 CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty;
1005 CanQualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy;
1006 CanQualType UnsignedLongLongTy, UnsignedInt128Ty;
1007 CanQualType FloatTy, DoubleTy, LongDoubleTy, Float128Ty;
1008 CanQualType HalfTy; // [OpenCL 6.1.1.1], ARM NEON
1009 CanQualType Float16Ty; // C11 extension ISO/IEC TS 18661-3
1010 CanQualType FloatComplexTy, DoubleComplexTy, LongDoubleComplexTy;
1011 CanQualType Float128ComplexTy;
1012 CanQualType VoidPtrTy, NullPtrTy;
1013 CanQualType DependentTy, OverloadTy, BoundMemberTy, UnknownAnyTy;
1014 CanQualType BuiltinFnTy;
1015 CanQualType PseudoObjectTy, ARCUnbridgedCastTy;
1016 CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy;
1017 CanQualType ObjCBuiltinBoolTy;
1018 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1019 CanQualType SingletonId;
1020 #include "clang/Basic/OpenCLImageTypes.def"
1021 CanQualType OCLSamplerTy, OCLEventTy, OCLClkEventTy;
1022 CanQualType OCLQueueTy, OCLReserveIDTy;
1023 CanQualType OMPArraySectionTy;
1025 // Types for deductions in C++0x [stmt.ranged]'s desugaring. Built on demand.
1026 mutable QualType AutoDeductTy; // Deduction against 'auto'.
1027 mutable QualType AutoRRefDeductTy; // Deduction against 'auto &&'.
1029 // Decl used to help define __builtin_va_list for some targets.
1030 // The decl is built when constructing 'BuiltinVaListDecl'.
1031 mutable Decl *VaListTagDecl;
1033 ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents,
1034 SelectorTable &sels, Builtin::Context &builtins);
1035 ASTContext(const ASTContext &) = delete;
1036 ASTContext &operator=(const ASTContext &) = delete;
1039 /// \brief Attach an external AST source to the AST context.
1041 /// The external AST source provides the ability to load parts of
1042 /// the abstract syntax tree as needed from some external storage,
1043 /// e.g., a precompiled header.
1044 void setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source);
1046 /// \brief Retrieve a pointer to the external AST source associated
1047 /// with this AST context, if any.
1048 ExternalASTSource *getExternalSource() const {
1049 return ExternalSource.get();
1052 /// \brief Attach an AST mutation listener to the AST context.
1054 /// The AST mutation listener provides the ability to track modifications to
1055 /// the abstract syntax tree entities committed after they were initially
1057 void setASTMutationListener(ASTMutationListener *Listener) {
1058 this->Listener = Listener;
1061 /// \brief Retrieve a pointer to the AST mutation listener associated
1062 /// with this AST context, if any.
1063 ASTMutationListener *getASTMutationListener() const { return Listener; }
1065 void PrintStats() const;
1066 const SmallVectorImpl<Type *>& getTypes() const { return Types; }
1068 BuiltinTemplateDecl *buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1069 const IdentifierInfo *II) const;
1071 /// \brief Create a new implicit TU-level CXXRecordDecl or RecordDecl
1073 RecordDecl *buildImplicitRecord(StringRef Name,
1074 RecordDecl::TagKind TK = TTK_Struct) const;
1076 /// \brief Create a new implicit TU-level typedef declaration.
1077 TypedefDecl *buildImplicitTypedef(QualType T, StringRef Name) const;
1079 /// \brief Retrieve the declaration for the 128-bit signed integer type.
1080 TypedefDecl *getInt128Decl() const;
1082 /// \brief Retrieve the declaration for the 128-bit unsigned integer type.
1083 TypedefDecl *getUInt128Decl() const;
1085 //===--------------------------------------------------------------------===//
1086 // Type Constructors
1087 //===--------------------------------------------------------------------===//
1090 /// \brief Return a type with extended qualifiers.
1091 QualType getExtQualType(const Type *Base, Qualifiers Quals) const;
1093 QualType getTypeDeclTypeSlow(const TypeDecl *Decl) const;
1095 QualType getPipeType(QualType T, bool ReadOnly) const;
1098 /// \brief Return the uniqued reference to the type for an address space
1099 /// qualified type with the specified type and address space.
1101 /// The resulting type has a union of the qualifiers from T and the address
1102 /// space. If T already has an address space specifier, it is silently
1104 QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const;
1106 /// \brief Remove any existing address space on the type and returns the type
1107 /// with qualifiers intact (or that's the idea anyway)
1109 /// The return type should be T with all prior qualifiers minus the address
1111 QualType removeAddrSpaceQualType(QualType T) const;
1113 /// \brief Apply Objective-C protocol qualifiers to the given type.
1114 /// \param allowOnPointerType specifies if we can apply protocol
1115 /// qualifiers on ObjCObjectPointerType. It can be set to true when
1116 /// contructing the canonical type of a Objective-C type parameter.
1117 QualType applyObjCProtocolQualifiers(QualType type,
1118 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
1119 bool allowOnPointerType = false) const;
1121 /// \brief Return the uniqued reference to the type for an Objective-C
1122 /// gc-qualified type.
1124 /// The retulting type has a union of the qualifiers from T and the gc
1126 QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const;
1128 /// \brief Return the uniqued reference to the type for a \c restrict
1131 /// The resulting type has a union of the qualifiers from \p T and
1133 QualType getRestrictType(QualType T) const {
1134 return T.withFastQualifiers(Qualifiers::Restrict);
1137 /// \brief Return the uniqued reference to the type for a \c volatile
1140 /// The resulting type has a union of the qualifiers from \p T and
1142 QualType getVolatileType(QualType T) const {
1143 return T.withFastQualifiers(Qualifiers::Volatile);
1146 /// \brief Return the uniqued reference to the type for a \c const
1149 /// The resulting type has a union of the qualifiers from \p T and \c const.
1151 /// It can be reasonably expected that this will always be equivalent to
1152 /// calling T.withConst().
1153 QualType getConstType(QualType T) const { return T.withConst(); }
1155 /// \brief Change the ExtInfo on a function type.
1156 const FunctionType *adjustFunctionType(const FunctionType *Fn,
1157 FunctionType::ExtInfo EInfo);
1159 /// Adjust the given function result type.
1160 CanQualType getCanonicalFunctionResultType(QualType ResultType) const;
1162 /// \brief Change the result type of a function type once it is deduced.
1163 void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType);
1165 /// \brief Determine whether two function types are the same, ignoring
1166 /// exception specifications in cases where they're part of the type.
1167 bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U);
1169 /// \brief Change the exception specification on a function once it is
1170 /// delay-parsed, instantiated, or computed.
1171 void adjustExceptionSpec(FunctionDecl *FD,
1172 const FunctionProtoType::ExceptionSpecInfo &ESI,
1173 bool AsWritten = false);
1175 /// \brief Return the uniqued reference to the type for a complex
1176 /// number with the specified element type.
1177 QualType getComplexType(QualType T) const;
1178 CanQualType getComplexType(CanQualType T) const {
1179 return CanQualType::CreateUnsafe(getComplexType((QualType) T));
1182 /// \brief Return the uniqued reference to the type for a pointer to
1183 /// the specified type.
1184 QualType getPointerType(QualType T) const;
1185 CanQualType getPointerType(CanQualType T) const {
1186 return CanQualType::CreateUnsafe(getPointerType((QualType) T));
1189 /// \brief Return the uniqued reference to a type adjusted from the original
1190 /// type to a new type.
1191 QualType getAdjustedType(QualType Orig, QualType New) const;
1192 CanQualType getAdjustedType(CanQualType Orig, CanQualType New) const {
1193 return CanQualType::CreateUnsafe(
1194 getAdjustedType((QualType)Orig, (QualType)New));
1197 /// \brief Return the uniqued reference to the decayed version of the given
1198 /// type. Can only be called on array and function types which decay to
1200 QualType getDecayedType(QualType T) const;
1201 CanQualType getDecayedType(CanQualType T) const {
1202 return CanQualType::CreateUnsafe(getDecayedType((QualType) T));
1205 /// \brief Return the uniqued reference to the atomic type for the specified
1207 QualType getAtomicType(QualType T) const;
1209 /// \brief Return the uniqued reference to the type for a block of the
1211 QualType getBlockPointerType(QualType T) const;
1213 /// Gets the struct used to keep track of the descriptor for pointer to
1215 QualType getBlockDescriptorType() const;
1217 /// \brief Return a read_only pipe type for the specified type.
1218 QualType getReadPipeType(QualType T) const;
1220 /// \brief Return a write_only pipe type for the specified type.
1221 QualType getWritePipeType(QualType T) const;
1223 /// Gets the struct used to keep track of the extended descriptor for
1224 /// pointer to blocks.
1225 QualType getBlockDescriptorExtendedType() const;
1227 /// Map an AST Type to an OpenCLTypeKind enum value.
1228 TargetInfo::OpenCLTypeKind getOpenCLTypeKind(const Type *T) const;
1230 /// Get address space for OpenCL type.
1231 LangAS getOpenCLTypeAddrSpace(const Type *T) const;
1233 void setcudaConfigureCallDecl(FunctionDecl *FD) {
1234 cudaConfigureCallDecl = FD;
1237 FunctionDecl *getcudaConfigureCallDecl() {
1238 return cudaConfigureCallDecl;
1241 /// Returns true iff we need copy/dispose helpers for the given type.
1242 bool BlockRequiresCopying(QualType Ty, const VarDecl *D);
1244 /// Returns true, if given type has a known lifetime. HasByrefExtendedLayout is set
1245 /// to false in this case. If HasByrefExtendedLayout returns true, byref variable
1246 /// has extended lifetime.
1247 bool getByrefLifetime(QualType Ty,
1248 Qualifiers::ObjCLifetime &Lifetime,
1249 bool &HasByrefExtendedLayout) const;
1251 /// \brief Return the uniqued reference to the type for an lvalue reference
1252 /// to the specified type.
1253 QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true)
1256 /// \brief Return the uniqued reference to the type for an rvalue reference
1257 /// to the specified type.
1258 QualType getRValueReferenceType(QualType T) const;
1260 /// \brief Return the uniqued reference to the type for a member pointer to
1261 /// the specified type in the specified class.
1263 /// The class \p Cls is a \c Type because it could be a dependent name.
1264 QualType getMemberPointerType(QualType T, const Type *Cls) const;
1266 /// \brief Return a non-unique reference to the type for a variable array of
1267 /// the specified element type.
1268 QualType getVariableArrayType(QualType EltTy, Expr *NumElts,
1269 ArrayType::ArraySizeModifier ASM,
1270 unsigned IndexTypeQuals,
1271 SourceRange Brackets) const;
1273 /// \brief Return a non-unique reference to the type for a dependently-sized
1274 /// array of the specified element type.
1276 /// FIXME: We will need these to be uniqued, or at least comparable, at some
1278 QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
1279 ArrayType::ArraySizeModifier ASM,
1280 unsigned IndexTypeQuals,
1281 SourceRange Brackets) const;
1283 /// \brief Return a unique reference to the type for an incomplete array of
1284 /// the specified element type.
1285 QualType getIncompleteArrayType(QualType EltTy,
1286 ArrayType::ArraySizeModifier ASM,
1287 unsigned IndexTypeQuals) const;
1289 /// \brief Return the unique reference to the type for a constant array of
1290 /// the specified element type.
1291 QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize,
1292 ArrayType::ArraySizeModifier ASM,
1293 unsigned IndexTypeQuals) const;
1295 /// \brief Returns a vla type where known sizes are replaced with [*].
1296 QualType getVariableArrayDecayedType(QualType Ty) const;
1298 /// \brief Return the unique reference to a vector type of the specified
1299 /// element type and size.
1301 /// \pre \p VectorType must be a built-in type.
1302 QualType getVectorType(QualType VectorType, unsigned NumElts,
1303 VectorType::VectorKind VecKind) const;
1305 /// \brief Return the unique reference to an extended vector type
1306 /// of the specified element type and size.
1308 /// \pre \p VectorType must be a built-in type.
1309 QualType getExtVectorType(QualType VectorType, unsigned NumElts) const;
1311 /// \pre Return a non-unique reference to the type for a dependently-sized
1312 /// vector of the specified element type.
1314 /// FIXME: We will need these to be uniqued, or at least comparable, at some
1316 QualType getDependentSizedExtVectorType(QualType VectorType,
1318 SourceLocation AttrLoc) const;
1320 QualType getDependentAddressSpaceType(QualType PointeeType,
1321 Expr *AddrSpaceExpr,
1322 SourceLocation AttrLoc) const;
1324 /// \brief Return a K&R style C function type like 'int()'.
1325 QualType getFunctionNoProtoType(QualType ResultTy,
1326 const FunctionType::ExtInfo &Info) const;
1328 QualType getFunctionNoProtoType(QualType ResultTy) const {
1329 return getFunctionNoProtoType(ResultTy, FunctionType::ExtInfo());
1332 /// \brief Return a normal function type with a typed argument list.
1333 QualType getFunctionType(QualType ResultTy, ArrayRef<QualType> Args,
1334 const FunctionProtoType::ExtProtoInfo &EPI) const {
1335 return getFunctionTypeInternal(ResultTy, Args, EPI, false);
1339 /// \brief Return a normal function type with a typed argument list.
1340 QualType getFunctionTypeInternal(QualType ResultTy, ArrayRef<QualType> Args,
1341 const FunctionProtoType::ExtProtoInfo &EPI,
1342 bool OnlyWantCanonical) const;
1345 /// \brief Return the unique reference to the type for the specified type
1347 QualType getTypeDeclType(const TypeDecl *Decl,
1348 const TypeDecl *PrevDecl = nullptr) const {
1349 assert(Decl && "Passed null for Decl param");
1350 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1353 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
1354 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1355 return QualType(PrevDecl->TypeForDecl, 0);
1358 return getTypeDeclTypeSlow(Decl);
1361 /// \brief Return the unique reference to the type for the specified
1362 /// typedef-name decl.
1363 QualType getTypedefType(const TypedefNameDecl *Decl,
1364 QualType Canon = QualType()) const;
1366 QualType getRecordType(const RecordDecl *Decl) const;
1368 QualType getEnumType(const EnumDecl *Decl) const;
1370 QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const;
1372 QualType getAttributedType(AttributedType::Kind attrKind,
1373 QualType modifiedType,
1374 QualType equivalentType);
1376 QualType getSubstTemplateTypeParmType(const TemplateTypeParmType *Replaced,
1377 QualType Replacement) const;
1378 QualType getSubstTemplateTypeParmPackType(
1379 const TemplateTypeParmType *Replaced,
1380 const TemplateArgument &ArgPack);
1383 getTemplateTypeParmType(unsigned Depth, unsigned Index,
1385 TemplateTypeParmDecl *ParmDecl = nullptr) const;
1387 QualType getTemplateSpecializationType(TemplateName T,
1388 ArrayRef<TemplateArgument> Args,
1389 QualType Canon = QualType()) const;
1392 getCanonicalTemplateSpecializationType(TemplateName T,
1393 ArrayRef<TemplateArgument> Args) const;
1395 QualType getTemplateSpecializationType(TemplateName T,
1396 const TemplateArgumentListInfo &Args,
1397 QualType Canon = QualType()) const;
1400 getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc,
1401 const TemplateArgumentListInfo &Args,
1402 QualType Canon = QualType()) const;
1404 QualType getParenType(QualType NamedType) const;
1406 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1407 NestedNameSpecifier *NNS,
1408 QualType NamedType) const;
1409 QualType getDependentNameType(ElaboratedTypeKeyword Keyword,
1410 NestedNameSpecifier *NNS,
1411 const IdentifierInfo *Name,
1412 QualType Canon = QualType()) const;
1414 QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
1415 NestedNameSpecifier *NNS,
1416 const IdentifierInfo *Name,
1417 const TemplateArgumentListInfo &Args) const;
1418 QualType getDependentTemplateSpecializationType(
1419 ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
1420 const IdentifierInfo *Name, ArrayRef<TemplateArgument> Args) const;
1422 TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl);
1424 /// Get a template argument list with one argument per template parameter
1425 /// in a template parameter list, such as for the injected class name of
1426 /// a class template.
1427 void getInjectedTemplateArgs(const TemplateParameterList *Params,
1428 SmallVectorImpl<TemplateArgument> &Args);
1430 QualType getPackExpansionType(QualType Pattern,
1431 Optional<unsigned> NumExpansions);
1433 QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
1434 ObjCInterfaceDecl *PrevDecl = nullptr) const;
1436 /// Legacy interface: cannot provide type arguments or __kindof.
1437 QualType getObjCObjectType(QualType Base,
1438 ObjCProtocolDecl * const *Protocols,
1439 unsigned NumProtocols) const;
1441 QualType getObjCObjectType(QualType Base,
1442 ArrayRef<QualType> typeArgs,
1443 ArrayRef<ObjCProtocolDecl *> protocols,
1444 bool isKindOf) const;
1446 QualType getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
1447 ArrayRef<ObjCProtocolDecl *> protocols,
1448 QualType Canonical = QualType()) const;
1450 bool ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *Decl);
1452 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
1453 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
1455 bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
1456 ObjCInterfaceDecl *IDecl);
1458 /// \brief Return a ObjCObjectPointerType type for the given ObjCObjectType.
1459 QualType getObjCObjectPointerType(QualType OIT) const;
1461 /// \brief GCC extension.
1462 QualType getTypeOfExprType(Expr *e) const;
1463 QualType getTypeOfType(QualType t) const;
1465 /// \brief C++11 decltype.
1466 QualType getDecltypeType(Expr *e, QualType UnderlyingType) const;
1468 /// \brief Unary type transforms
1469 QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
1470 UnaryTransformType::UTTKind UKind) const;
1472 /// \brief C++11 deduced auto type.
1473 QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
1474 bool IsDependent) const;
1476 /// \brief C++11 deduction pattern for 'auto' type.
1477 QualType getAutoDeductType() const;
1479 /// \brief C++11 deduction pattern for 'auto &&' type.
1480 QualType getAutoRRefDeductType() const;
1482 /// \brief C++17 deduced class template specialization type.
1483 QualType getDeducedTemplateSpecializationType(TemplateName Template,
1484 QualType DeducedType,
1485 bool IsDependent) const;
1487 /// \brief Return the unique reference to the type for the specified TagDecl
1488 /// (struct/union/class/enum) decl.
1489 QualType getTagDeclType(const TagDecl *Decl) const;
1491 /// \brief Return the unique type for "size_t" (C99 7.17), defined in
1494 /// The sizeof operator requires this (C99 6.5.3.4p4).
1495 CanQualType getSizeType() const;
1497 /// \brief Return the unique signed counterpart of
1498 /// the integer type corresponding to size_t.
1499 CanQualType getSignedSizeType() const;
1501 /// \brief Return the unique type for "intmax_t" (C99 7.18.1.5), defined in
1503 CanQualType getIntMaxType() const;
1505 /// \brief Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in
1507 CanQualType getUIntMaxType() const;
1509 /// \brief Return the unique wchar_t type available in C++ (and available as
1510 /// __wchar_t as a Microsoft extension).
1511 QualType getWCharType() const { return WCharTy; }
1513 /// \brief Return the type of wide characters. In C++, this returns the
1514 /// unique wchar_t type. In C99, this returns a type compatible with the type
1515 /// defined in <stddef.h> as defined by the target.
1516 QualType getWideCharType() const { return WideCharTy; }
1518 /// \brief Return the type of "signed wchar_t".
1520 /// Used when in C++, as a GCC extension.
1521 QualType getSignedWCharType() const;
1523 /// \brief Return the type of "unsigned wchar_t".
1525 /// Used when in C++, as a GCC extension.
1526 QualType getUnsignedWCharType() const;
1528 /// \brief In C99, this returns a type compatible with the type
1529 /// defined in <stddef.h> as defined by the target.
1530 QualType getWIntType() const { return WIntTy; }
1532 /// \brief Return a type compatible with "intptr_t" (C99 7.18.1.4),
1533 /// as defined by the target.
1534 QualType getIntPtrType() const;
1536 /// \brief Return a type compatible with "uintptr_t" (C99 7.18.1.4),
1537 /// as defined by the target.
1538 QualType getUIntPtrType() const;
1540 /// \brief Return the unique type for "ptrdiff_t" (C99 7.17) defined in
1541 /// <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1542 QualType getPointerDiffType() const;
1544 /// \brief Return the unique unsigned counterpart of "ptrdiff_t"
1545 /// integer type. The standard (C11 7.21.6.1p7) refers to this type
1546 /// in the definition of %tu format specifier.
1547 QualType getUnsignedPointerDiffType() const;
1549 /// \brief Return the unique type for "pid_t" defined in
1550 /// <sys/types.h>. We need this to compute the correct type for vfork().
1551 QualType getProcessIDType() const;
1553 /// \brief Return the C structure type used to represent constant CFStrings.
1554 QualType getCFConstantStringType() const;
1556 /// \brief Returns the C struct type for objc_super
1557 QualType getObjCSuperType() const;
1558 void setObjCSuperType(QualType ST) { ObjCSuperType = ST; }
1560 /// Get the structure type used to representation CFStrings, or NULL
1561 /// if it hasn't yet been built.
1562 QualType getRawCFConstantStringType() const {
1563 if (CFConstantStringTypeDecl)
1564 return getTypedefType(CFConstantStringTypeDecl);
1567 void setCFConstantStringType(QualType T);
1568 TypedefDecl *getCFConstantStringDecl() const;
1569 RecordDecl *getCFConstantStringTagDecl() const;
1571 // This setter/getter represents the ObjC type for an NSConstantString.
1572 void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl);
1573 QualType getObjCConstantStringInterface() const {
1574 return ObjCConstantStringType;
1577 QualType getObjCNSStringType() const {
1578 return ObjCNSStringType;
1581 void setObjCNSStringType(QualType T) {
1582 ObjCNSStringType = T;
1585 /// \brief Retrieve the type that \c id has been defined to, which may be
1586 /// different from the built-in \c id if \c id has been typedef'd.
1587 QualType getObjCIdRedefinitionType() const {
1588 if (ObjCIdRedefinitionType.isNull())
1589 return getObjCIdType();
1590 return ObjCIdRedefinitionType;
1593 /// \brief Set the user-written type that redefines \c id.
1594 void setObjCIdRedefinitionType(QualType RedefType) {
1595 ObjCIdRedefinitionType = RedefType;
1598 /// \brief Retrieve the type that \c Class has been defined to, which may be
1599 /// different from the built-in \c Class if \c Class has been typedef'd.
1600 QualType getObjCClassRedefinitionType() const {
1601 if (ObjCClassRedefinitionType.isNull())
1602 return getObjCClassType();
1603 return ObjCClassRedefinitionType;
1606 /// \brief Set the user-written type that redefines 'SEL'.
1607 void setObjCClassRedefinitionType(QualType RedefType) {
1608 ObjCClassRedefinitionType = RedefType;
1611 /// \brief Retrieve the type that 'SEL' has been defined to, which may be
1612 /// different from the built-in 'SEL' if 'SEL' has been typedef'd.
1613 QualType getObjCSelRedefinitionType() const {
1614 if (ObjCSelRedefinitionType.isNull())
1615 return getObjCSelType();
1616 return ObjCSelRedefinitionType;
1619 /// \brief Set the user-written type that redefines 'SEL'.
1620 void setObjCSelRedefinitionType(QualType RedefType) {
1621 ObjCSelRedefinitionType = RedefType;
1624 /// Retrieve the identifier 'NSObject'.
1625 IdentifierInfo *getNSObjectName() {
1626 if (!NSObjectName) {
1627 NSObjectName = &Idents.get("NSObject");
1630 return NSObjectName;
1633 /// Retrieve the identifier 'NSCopying'.
1634 IdentifierInfo *getNSCopyingName() {
1635 if (!NSCopyingName) {
1636 NSCopyingName = &Idents.get("NSCopying");
1639 return NSCopyingName;
1642 CanQualType getNSUIntegerType() const {
1643 assert(Target && "Expected target to be initialized");
1644 const llvm::Triple &T = Target->getTriple();
1645 // Windows is LLP64 rather than LP64
1646 if (T.isOSWindows() && T.isArch64Bit())
1647 return UnsignedLongLongTy;
1648 return UnsignedLongTy;
1651 CanQualType getNSIntegerType() const {
1652 assert(Target && "Expected target to be initialized");
1653 const llvm::Triple &T = Target->getTriple();
1654 // Windows is LLP64 rather than LP64
1655 if (T.isOSWindows() && T.isArch64Bit())
1660 /// Retrieve the identifier 'bool'.
1661 IdentifierInfo *getBoolName() const {
1663 BoolName = &Idents.get("bool");
1667 IdentifierInfo *getMakeIntegerSeqName() const {
1668 if (!MakeIntegerSeqName)
1669 MakeIntegerSeqName = &Idents.get("__make_integer_seq");
1670 return MakeIntegerSeqName;
1673 IdentifierInfo *getTypePackElementName() const {
1674 if (!TypePackElementName)
1675 TypePackElementName = &Idents.get("__type_pack_element");
1676 return TypePackElementName;
1679 /// \brief Retrieve the Objective-C "instancetype" type, if already known;
1680 /// otherwise, returns a NULL type;
1681 QualType getObjCInstanceType() {
1682 return getTypeDeclType(getObjCInstanceTypeDecl());
1685 /// \brief Retrieve the typedef declaration corresponding to the Objective-C
1686 /// "instancetype" type.
1687 TypedefDecl *getObjCInstanceTypeDecl();
1689 /// \brief Set the type for the C FILE type.
1690 void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; }
1692 /// \brief Retrieve the C FILE type.
1693 QualType getFILEType() const {
1695 return getTypeDeclType(FILEDecl);
1699 /// \brief Set the type for the C jmp_buf type.
1700 void setjmp_bufDecl(TypeDecl *jmp_bufDecl) {
1701 this->jmp_bufDecl = jmp_bufDecl;
1704 /// \brief Retrieve the C jmp_buf type.
1705 QualType getjmp_bufType() const {
1707 return getTypeDeclType(jmp_bufDecl);
1711 /// \brief Set the type for the C sigjmp_buf type.
1712 void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) {
1713 this->sigjmp_bufDecl = sigjmp_bufDecl;
1716 /// \brief Retrieve the C sigjmp_buf type.
1717 QualType getsigjmp_bufType() const {
1719 return getTypeDeclType(sigjmp_bufDecl);
1723 /// \brief Set the type for the C ucontext_t type.
1724 void setucontext_tDecl(TypeDecl *ucontext_tDecl) {
1725 this->ucontext_tDecl = ucontext_tDecl;
1728 /// \brief Retrieve the C ucontext_t type.
1729 QualType getucontext_tType() const {
1731 return getTypeDeclType(ucontext_tDecl);
1735 /// \brief The result type of logical operations, '<', '>', '!=', etc.
1736 QualType getLogicalOperationType() const {
1737 return getLangOpts().CPlusPlus ? BoolTy : IntTy;
1740 /// \brief Emit the Objective-CC type encoding for the given type \p T into
1743 /// If \p Field is specified then record field names are also encoded.
1744 void getObjCEncodingForType(QualType T, std::string &S,
1745 const FieldDecl *Field=nullptr,
1746 QualType *NotEncodedT=nullptr) const;
1748 /// \brief Emit the Objective-C property type encoding for the given
1749 /// type \p T into \p S.
1750 void getObjCEncodingForPropertyType(QualType T, std::string &S) const;
1752 void getLegacyIntegralTypeEncoding(QualType &t) const;
1754 /// \brief Put the string version of the type qualifiers \p QT into \p S.
1755 void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
1756 std::string &S) const;
1758 /// \brief Emit the encoded type for the function \p Decl into \p S.
1760 /// This is in the same format as Objective-C method encodings.
1762 /// \returns true if an error occurred (e.g., because one of the parameter
1763 /// types is incomplete), false otherwise.
1764 std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const;
1766 /// \brief Emit the encoded type for the method declaration \p Decl into
1768 std::string getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
1769 bool Extended = false) const;
1771 /// \brief Return the encoded type for this block declaration.
1772 std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const;
1774 /// getObjCEncodingForPropertyDecl - Return the encoded type for
1775 /// this method declaration. If non-NULL, Container must be either
1776 /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
1777 /// only be NULL when getting encodings for protocol properties.
1778 std::string getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
1779 const Decl *Container) const;
1781 bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
1782 ObjCProtocolDecl *rProto) const;
1784 ObjCPropertyImplDecl *getObjCPropertyImplDeclForPropertyDecl(
1785 const ObjCPropertyDecl *PD,
1786 const Decl *Container) const;
1788 /// \brief Return the size of type \p T for Objective-C encoding purpose,
1790 CharUnits getObjCEncodingTypeSize(QualType T) const;
1792 /// \brief Retrieve the typedef corresponding to the predefined \c id type
1794 TypedefDecl *getObjCIdDecl() const;
1796 /// \brief Represents the Objective-CC \c id type.
1798 /// This is set up lazily, by Sema. \c id is always a (typedef for a)
1799 /// pointer type, a pointer to a struct.
1800 QualType getObjCIdType() const {
1801 return getTypeDeclType(getObjCIdDecl());
1804 /// \brief Retrieve the typedef corresponding to the predefined 'SEL' type
1806 TypedefDecl *getObjCSelDecl() const;
1808 /// \brief Retrieve the type that corresponds to the predefined Objective-C
1810 QualType getObjCSelType() const {
1811 return getTypeDeclType(getObjCSelDecl());
1814 /// \brief Retrieve the typedef declaration corresponding to the predefined
1815 /// Objective-C 'Class' type.
1816 TypedefDecl *getObjCClassDecl() const;
1818 /// \brief Represents the Objective-C \c Class type.
1820 /// This is set up lazily, by Sema. \c Class is always a (typedef for a)
1821 /// pointer type, a pointer to a struct.
1822 QualType getObjCClassType() const {
1823 return getTypeDeclType(getObjCClassDecl());
1826 /// \brief Retrieve the Objective-C class declaration corresponding to
1827 /// the predefined \c Protocol class.
1828 ObjCInterfaceDecl *getObjCProtocolDecl() const;
1830 /// \brief Retrieve declaration of 'BOOL' typedef
1831 TypedefDecl *getBOOLDecl() const {
1835 /// \brief Save declaration of 'BOOL' typedef
1836 void setBOOLDecl(TypedefDecl *TD) {
1840 /// \brief type of 'BOOL' type.
1841 QualType getBOOLType() const {
1842 return getTypeDeclType(getBOOLDecl());
1845 /// \brief Retrieve the type of the Objective-C \c Protocol class.
1846 QualType getObjCProtoType() const {
1847 return getObjCInterfaceType(getObjCProtocolDecl());
1850 /// \brief Retrieve the C type declaration corresponding to the predefined
1851 /// \c __builtin_va_list type.
1852 TypedefDecl *getBuiltinVaListDecl() const;
1854 /// \brief Retrieve the type of the \c __builtin_va_list type.
1855 QualType getBuiltinVaListType() const {
1856 return getTypeDeclType(getBuiltinVaListDecl());
1859 /// \brief Retrieve the C type declaration corresponding to the predefined
1860 /// \c __va_list_tag type used to help define the \c __builtin_va_list type
1861 /// for some targets.
1862 Decl *getVaListTagDecl() const;
1864 /// Retrieve the C type declaration corresponding to the predefined
1865 /// \c __builtin_ms_va_list type.
1866 TypedefDecl *getBuiltinMSVaListDecl() const;
1868 /// Retrieve the type of the \c __builtin_ms_va_list type.
1869 QualType getBuiltinMSVaListType() const {
1870 return getTypeDeclType(getBuiltinMSVaListDecl());
1873 /// \brief Return a type with additional \c const, \c volatile, or
1874 /// \c restrict qualifiers.
1875 QualType getCVRQualifiedType(QualType T, unsigned CVR) const {
1876 return getQualifiedType(T, Qualifiers::fromCVRMask(CVR));
1879 /// \brief Un-split a SplitQualType.
1880 QualType getQualifiedType(SplitQualType split) const {
1881 return getQualifiedType(split.Ty, split.Quals);
1884 /// \brief Return a type with additional qualifiers.
1885 QualType getQualifiedType(QualType T, Qualifiers Qs) const {
1886 if (!Qs.hasNonFastQualifiers())
1887 return T.withFastQualifiers(Qs.getFastQualifiers());
1888 QualifierCollector Qc(Qs);
1889 const Type *Ptr = Qc.strip(T);
1890 return getExtQualType(Ptr, Qc);
1893 /// \brief Return a type with additional qualifiers.
1894 QualType getQualifiedType(const Type *T, Qualifiers Qs) const {
1895 if (!Qs.hasNonFastQualifiers())
1896 return QualType(T, Qs.getFastQualifiers());
1897 return getExtQualType(T, Qs);
1900 /// \brief Return a type with the given lifetime qualifier.
1902 /// \pre Neither type.ObjCLifetime() nor \p lifetime may be \c OCL_None.
1903 QualType getLifetimeQualifiedType(QualType type,
1904 Qualifiers::ObjCLifetime lifetime) {
1905 assert(type.getObjCLifetime() == Qualifiers::OCL_None);
1906 assert(lifetime != Qualifiers::OCL_None);
1909 qs.addObjCLifetime(lifetime);
1910 return getQualifiedType(type, qs);
1913 /// getUnqualifiedObjCPointerType - Returns version of
1914 /// Objective-C pointer type with lifetime qualifier removed.
1915 QualType getUnqualifiedObjCPointerType(QualType type) const {
1916 if (!type.getTypePtr()->isObjCObjectPointerType() ||
1917 !type.getQualifiers().hasObjCLifetime())
1919 Qualifiers Qs = type.getQualifiers();
1920 Qs.removeObjCLifetime();
1921 return getQualifiedType(type.getUnqualifiedType(), Qs);
1924 DeclarationNameInfo getNameForTemplate(TemplateName Name,
1925 SourceLocation NameLoc) const;
1927 TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin,
1928 UnresolvedSetIterator End) const;
1930 TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
1931 bool TemplateKeyword,
1932 TemplateDecl *Template) const;
1934 TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1935 const IdentifierInfo *Name) const;
1936 TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1937 OverloadedOperatorKind Operator) const;
1938 TemplateName getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
1939 TemplateName replacement) const;
1940 TemplateName getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
1941 const TemplateArgument &ArgPack) const;
1943 enum GetBuiltinTypeError {
1947 /// Missing a type from <stdio.h>
1950 /// Missing a type from <setjmp.h>
1953 /// Missing a type from <ucontext.h>
1957 /// \brief Return the type for the specified builtin.
1959 /// If \p IntegerConstantArgs is non-null, it is filled in with a bitmask of
1960 /// arguments to the builtin that are required to be integer constant
1962 QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error,
1963 unsigned *IntegerConstantArgs = nullptr) const;
1966 CanQualType getFromTargetType(unsigned Type) const;
1967 TypeInfo getTypeInfoImpl(const Type *T) const;
1969 //===--------------------------------------------------------------------===//
1971 //===--------------------------------------------------------------------===//
1974 /// \brief Return one of the GCNone, Weak or Strong Objective-C garbage
1975 /// collection attributes.
1976 Qualifiers::GC getObjCGCAttrKind(QualType Ty) const;
1978 /// \brief Return true if the given vector types are of the same unqualified
1979 /// type or if they are equivalent to the same GCC vector type.
1981 /// \note This ignores whether they are target-specific (AltiVec or Neon)
1983 bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec);
1985 /// \brief Return true if this is an \c NSObject object with its \c NSObject
1987 static bool isObjCNSObjectType(QualType Ty) {
1988 return Ty->isObjCNSObjectType();
1991 //===--------------------------------------------------------------------===//
1992 // Type Sizing and Analysis
1993 //===--------------------------------------------------------------------===//
1995 /// \brief Return the APFloat 'semantics' for the specified scalar floating
1997 const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
1999 /// \brief Get the size and alignment of the specified complete type in bits.
2000 TypeInfo getTypeInfo(const Type *T) const;
2001 TypeInfo getTypeInfo(QualType T) const { return getTypeInfo(T.getTypePtr()); }
2003 /// \brief Get default simd alignment of the specified complete type in bits.
2004 unsigned getOpenMPDefaultSimdAlign(QualType T) const;
2006 /// \brief Return the size of the specified (complete) type \p T, in bits.
2007 uint64_t getTypeSize(QualType T) const { return getTypeInfo(T).Width; }
2008 uint64_t getTypeSize(const Type *T) const { return getTypeInfo(T).Width; }
2010 /// \brief Return the size of the character type, in bits.
2011 uint64_t getCharWidth() const {
2012 return getTypeSize(CharTy);
2015 /// \brief Convert a size in bits to a size in characters.
2016 CharUnits toCharUnitsFromBits(int64_t BitSize) const;
2018 /// \brief Convert a size in characters to a size in bits.
2019 int64_t toBits(CharUnits CharSize) const;
2021 /// \brief Return the size of the specified (complete) type \p T, in
2023 CharUnits getTypeSizeInChars(QualType T) const;
2024 CharUnits getTypeSizeInChars(const Type *T) const;
2026 /// \brief Return the ABI-specified alignment of a (complete) type \p T, in
2028 unsigned getTypeAlign(QualType T) const { return getTypeInfo(T).Align; }
2029 unsigned getTypeAlign(const Type *T) const { return getTypeInfo(T).Align; }
2031 /// \brief Return the ABI-specified alignment of a type, in bits, or 0 if
2032 /// the type is incomplete and we cannot determine the alignment (for
2033 /// example, from alignment attributes).
2034 unsigned getTypeAlignIfKnown(QualType T) const;
2036 /// \brief Return the ABI-specified alignment of a (complete) type \p T, in
2038 CharUnits getTypeAlignInChars(QualType T) const;
2039 CharUnits getTypeAlignInChars(const Type *T) const;
2041 // getTypeInfoDataSizeInChars - Return the size of a type, in chars. If the
2042 // type is a record, its data size is returned.
2043 std::pair<CharUnits, CharUnits> getTypeInfoDataSizeInChars(QualType T) const;
2045 std::pair<CharUnits, CharUnits> getTypeInfoInChars(const Type *T) const;
2046 std::pair<CharUnits, CharUnits> getTypeInfoInChars(QualType T) const;
2048 /// \brief Determine if the alignment the type has was required using an
2049 /// alignment attribute.
2050 bool isAlignmentRequired(const Type *T) const;
2051 bool isAlignmentRequired(QualType T) const;
2053 /// \brief Return the "preferred" alignment of the specified type \p T for
2054 /// the current target, in bits.
2056 /// This can be different than the ABI alignment in cases where it is
2057 /// beneficial for performance to overalign a data type.
2058 unsigned getPreferredTypeAlign(const Type *T) const;
2060 /// \brief Return the default alignment for __attribute__((aligned)) on
2061 /// this target, to be used if no alignment value is specified.
2062 unsigned getTargetDefaultAlignForAttributeAligned() const;
2064 /// \brief Return the alignment in bits that should be given to a
2065 /// global variable with type \p T.
2066 unsigned getAlignOfGlobalVar(QualType T) const;
2068 /// \brief Return the alignment in characters that should be given to a
2069 /// global variable with type \p T.
2070 CharUnits getAlignOfGlobalVarInChars(QualType T) const;
2072 /// \brief Return a conservative estimate of the alignment of the specified
2075 /// \pre \p D must not be a bitfield type, as bitfields do not have a valid
2078 /// If \p ForAlignof, references are treated like their underlying type
2079 /// and large arrays don't get any special treatment. If not \p ForAlignof
2080 /// it computes the value expected by CodeGen: references are treated like
2081 /// pointers and large arrays get extra alignment.
2082 CharUnits getDeclAlign(const Decl *D, bool ForAlignof = false) const;
2084 /// \brief Get or compute information about the layout of the specified
2085 /// record (struct/union/class) \p D, which indicates its size and field
2086 /// position information.
2087 const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D) const;
2089 /// \brief Get or compute information about the layout of the specified
2090 /// Objective-C interface.
2091 const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D)
2094 void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS,
2095 bool Simple = false) const;
2097 /// \brief Get or compute information about the layout of the specified
2098 /// Objective-C implementation.
2100 /// This may differ from the interface if synthesized ivars are present.
2101 const ASTRecordLayout &
2102 getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const;
2104 /// \brief Get our current best idea for the key function of the
2105 /// given record decl, or nullptr if there isn't one.
2107 /// The key function is, according to the Itanium C++ ABI section 5.2.3:
2108 /// ...the first non-pure virtual function that is not inline at the
2109 /// point of class definition.
2111 /// Other ABIs use the same idea. However, the ARM C++ ABI ignores
2112 /// virtual functions that are defined 'inline', which means that
2113 /// the result of this computation can change.
2114 const CXXMethodDecl *getCurrentKeyFunction(const CXXRecordDecl *RD);
2116 /// \brief Observe that the given method cannot be a key function.
2117 /// Checks the key-function cache for the method's class and clears it
2118 /// if matches the given declaration.
2120 /// This is used in ABIs where out-of-line definitions marked
2121 /// inline are not considered to be key functions.
2123 /// \param method should be the declaration from the class definition
2124 void setNonKeyFunction(const CXXMethodDecl *method);
2126 /// Loading virtual member pointers using the virtual inheritance model
2127 /// always results in an adjustment using the vbtable even if the index is
2130 /// This is usually OK because the first slot in the vbtable points
2131 /// backwards to the top of the MDC. However, the MDC might be reusing a
2132 /// vbptr from an nv-base. In this case, the first slot in the vbtable
2133 /// points to the start of the nv-base which introduced the vbptr and *not*
2134 /// the MDC. Modify the NonVirtualBaseAdjustment to account for this.
2135 CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const;
2137 /// Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
2138 uint64_t getFieldOffset(const ValueDecl *FD) const;
2140 /// Get the offset of an ObjCIvarDecl in bits.
2141 uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID,
2142 const ObjCImplementationDecl *ID,
2143 const ObjCIvarDecl *Ivar) const;
2145 bool isNearlyEmpty(const CXXRecordDecl *RD) const;
2147 VTableContextBase *getVTableContext();
2149 MangleContext *createMangleContext();
2151 void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass,
2152 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const;
2154 unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const;
2155 void CollectInheritedProtocols(const Decl *CDecl,
2156 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols);
2158 /// \brief Return true if the specified type has unique object representations
2159 /// according to (C++17 [meta.unary.prop]p9)
2160 bool hasUniqueObjectRepresentations(QualType Ty) const;
2162 //===--------------------------------------------------------------------===//
2164 //===--------------------------------------------------------------------===//
2166 /// \brief Return the canonical (structural) type corresponding to the
2167 /// specified potentially non-canonical type \p T.
2169 /// The non-canonical version of a type may have many "decorated" versions of
2170 /// types. Decorators can include typedefs, 'typeof' operators, etc. The
2171 /// returned type is guaranteed to be free of any of these, allowing two
2172 /// canonical types to be compared for exact equality with a simple pointer
2174 CanQualType getCanonicalType(QualType T) const {
2175 return CanQualType::CreateUnsafe(T.getCanonicalType());
2178 const Type *getCanonicalType(const Type *T) const {
2179 return T->getCanonicalTypeInternal().getTypePtr();
2182 /// \brief Return the canonical parameter type corresponding to the specific
2183 /// potentially non-canonical one.
2185 /// Qualifiers are stripped off, functions are turned into function
2186 /// pointers, and arrays decay one level into pointers.
2187 CanQualType getCanonicalParamType(QualType T) const;
2189 /// \brief Determine whether the given types \p T1 and \p T2 are equivalent.
2190 bool hasSameType(QualType T1, QualType T2) const {
2191 return getCanonicalType(T1) == getCanonicalType(T2);
2193 bool hasSameType(const Type *T1, const Type *T2) const {
2194 return getCanonicalType(T1) == getCanonicalType(T2);
2197 /// \brief Return this type as a completely-unqualified array type,
2198 /// capturing the qualifiers in \p Quals.
2200 /// This will remove the minimal amount of sugaring from the types, similar
2201 /// to the behavior of QualType::getUnqualifiedType().
2203 /// \param T is the qualified type, which may be an ArrayType
2205 /// \param Quals will receive the full set of qualifiers that were
2206 /// applied to the array.
2208 /// \returns if this is an array type, the completely unqualified array type
2209 /// that corresponds to it. Otherwise, returns T.getUnqualifiedType().
2210 QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals);
2212 /// \brief Determine whether the given types are equivalent after
2213 /// cvr-qualifiers have been removed.
2214 bool hasSameUnqualifiedType(QualType T1, QualType T2) const {
2215 return getCanonicalType(T1).getTypePtr() ==
2216 getCanonicalType(T2).getTypePtr();
2219 bool hasSameNullabilityTypeQualifier(QualType SubT, QualType SuperT,
2220 bool IsParam) const {
2221 auto SubTnullability = SubT->getNullability(*this);
2222 auto SuperTnullability = SuperT->getNullability(*this);
2223 if (SubTnullability.hasValue() == SuperTnullability.hasValue()) {
2224 // Neither has nullability; return true
2225 if (!SubTnullability)
2227 // Both have nullability qualifier.
2228 if (*SubTnullability == *SuperTnullability ||
2229 *SubTnullability == NullabilityKind::Unspecified ||
2230 *SuperTnullability == NullabilityKind::Unspecified)
2234 // Ok for the superclass method parameter to be "nonnull" and the subclass
2235 // method parameter to be "nullable"
2236 return (*SuperTnullability == NullabilityKind::NonNull &&
2237 *SubTnullability == NullabilityKind::Nullable);
2240 // For the return type, it's okay for the superclass method to specify
2241 // "nullable" and the subclass method specify "nonnull"
2242 return (*SuperTnullability == NullabilityKind::Nullable &&
2243 *SubTnullability == NullabilityKind::NonNull);
2249 bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
2250 const ObjCMethodDecl *MethodImp);
2252 bool UnwrapSimilarPointerTypes(QualType &T1, QualType &T2);
2254 /// \brief Retrieves the "canonical" nested name specifier for a
2255 /// given nested name specifier.
2257 /// The canonical nested name specifier is a nested name specifier
2258 /// that uniquely identifies a type or namespace within the type
2259 /// system. For example, given:
2264 /// template<typename T> struct X { typename T* type; };
2268 /// template<typename T> struct Y {
2269 /// typename N::S::X<T>::type member;
2273 /// Here, the nested-name-specifier for N::S::X<T>:: will be
2274 /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined
2275 /// by declarations in the type system and the canonical type for
2276 /// the template type parameter 'T' is template-param-0-0.
2277 NestedNameSpecifier *
2278 getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const;
2280 /// \brief Retrieves the default calling convention for the current target.
2281 CallingConv getDefaultCallingConvention(bool IsVariadic,
2282 bool IsCXXMethod) const;
2284 /// \brief Retrieves the "canonical" template name that refers to a
2287 /// The canonical template name is the simplest expression that can
2288 /// be used to refer to a given template. For most templates, this
2289 /// expression is just the template declaration itself. For example,
2290 /// the template std::vector can be referred to via a variety of
2291 /// names---std::vector, \::std::vector, vector (if vector is in
2292 /// scope), etc.---but all of these names map down to the same
2293 /// TemplateDecl, which is used to form the canonical template name.
2295 /// Dependent template names are more interesting. Here, the
2296 /// template name could be something like T::template apply or
2297 /// std::allocator<T>::template rebind, where the nested name
2298 /// specifier itself is dependent. In this case, the canonical
2299 /// template name uses the shortest form of the dependent
2300 /// nested-name-specifier, which itself contains all canonical
2301 /// types, values, and templates.
2302 TemplateName getCanonicalTemplateName(TemplateName Name) const;
2304 /// \brief Determine whether the given template names refer to the same
2306 bool hasSameTemplateName(TemplateName X, TemplateName Y);
2308 /// \brief Retrieve the "canonical" template argument.
2310 /// The canonical template argument is the simplest template argument
2311 /// (which may be a type, value, expression, or declaration) that
2312 /// expresses the value of the argument.
2313 TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg)
2316 /// Type Query functions. If the type is an instance of the specified class,
2317 /// return the Type pointer for the underlying maximally pretty type. This
2318 /// is a member of ASTContext because this may need to do some amount of
2319 /// canonicalization, e.g. to move type qualifiers into the element type.
2320 const ArrayType *getAsArrayType(QualType T) const;
2321 const ConstantArrayType *getAsConstantArrayType(QualType T) const {
2322 return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T));
2324 const VariableArrayType *getAsVariableArrayType(QualType T) const {
2325 return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T));
2327 const IncompleteArrayType *getAsIncompleteArrayType(QualType T) const {
2328 return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
2330 const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T)
2332 return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T));
2335 /// \brief Return the innermost element type of an array type.
2337 /// For example, will return "int" for int[m][n]
2338 QualType getBaseElementType(const ArrayType *VAT) const;
2340 /// \brief Return the innermost element type of a type (which needn't
2341 /// actually be an array type).
2342 QualType getBaseElementType(QualType QT) const;
2344 /// \brief Return number of constant array elements.
2345 uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const;
2347 /// \brief Perform adjustment on the parameter type of a function.
2349 /// This routine adjusts the given parameter type @p T to the actual
2350 /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
2351 /// C++ [dcl.fct]p3). The adjusted parameter type is returned.
2352 QualType getAdjustedParameterType(QualType T) const;
2354 /// \brief Retrieve the parameter type as adjusted for use in the signature
2355 /// of a function, decaying array and function types and removing top-level
2357 QualType getSignatureParameterType(QualType T) const;
2359 QualType getExceptionObjectType(QualType T) const;
2361 /// \brief Return the properly qualified result of decaying the specified
2362 /// array type to a pointer.
2364 /// This operation is non-trivial when handling typedefs etc. The canonical
2365 /// type of \p T must be an array type, this returns a pointer to a properly
2366 /// qualified element of the array.
2368 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2369 QualType getArrayDecayedType(QualType T) const;
2371 /// \brief Return the type that \p PromotableType will promote to: C99
2372 /// 6.3.1.1p2, assuming that \p PromotableType is a promotable integer type.
2373 QualType getPromotedIntegerType(QualType PromotableType) const;
2375 /// \brief Recurses in pointer/array types until it finds an Objective-C
2376 /// retainable type and returns its ownership.
2377 Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const;
2379 /// \brief Whether this is a promotable bitfield reference according
2380 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2382 /// \returns the type this bit-field will promote to, or NULL if no
2383 /// promotion occurs.
2384 QualType isPromotableBitField(Expr *E) const;
2386 /// \brief Return the highest ranked integer type, see C99 6.3.1.8p1.
2388 /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
2389 /// \p LHS < \p RHS, return -1.
2390 int getIntegerTypeOrder(QualType LHS, QualType RHS) const;
2392 /// \brief Compare the rank of the two specified floating point types,
2393 /// ignoring the domain of the type (i.e. 'double' == '_Complex double').
2395 /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
2396 /// \p LHS < \p RHS, return -1.
2397 int getFloatingTypeOrder(QualType LHS, QualType RHS) const;
2399 /// \brief Return a real floating point or a complex type (based on
2400 /// \p typeDomain/\p typeSize).
2402 /// \param typeDomain a real floating point or complex type.
2403 /// \param typeSize a real floating point or complex type.
2404 QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
2405 QualType typeDomain) const;
2407 unsigned getTargetAddressSpace(QualType T) const {
2408 return getTargetAddressSpace(T.getQualifiers());
2411 unsigned getTargetAddressSpace(Qualifiers Q) const {
2412 return getTargetAddressSpace(Q.getAddressSpace());
2415 unsigned getTargetAddressSpace(LangAS AS) const;
2417 /// Get target-dependent integer value for null pointer which is used for
2418 /// constant folding.
2419 uint64_t getTargetNullPointerValue(QualType QT) const;
2421 bool addressSpaceMapManglingFor(LangAS AS) const {
2422 return AddrSpaceMapMangling || isTargetAddressSpace(AS);
2426 // Helper for integer ordering
2427 unsigned getIntegerRank(const Type *T) const;
2430 //===--------------------------------------------------------------------===//
2431 // Type Compatibility Predicates
2432 //===--------------------------------------------------------------------===//
2434 /// Compatibility predicates used to check assignment expressions.
2435 bool typesAreCompatible(QualType T1, QualType T2,
2436 bool CompareUnqualified = false); // C99 6.2.7p1
2438 bool propertyTypesAreCompatible(QualType, QualType);
2439 bool typesAreBlockPointerCompatible(QualType, QualType);
2441 bool isObjCIdType(QualType T) const {
2442 return T == getObjCIdType();
2445 bool isObjCClassType(QualType T) const {
2446 return T == getObjCClassType();
2449 bool isObjCSelType(QualType T) const {
2450 return T == getObjCSelType();
2453 bool ObjCQualifiedIdTypesAreCompatible(QualType LHS, QualType RHS,
2456 bool ObjCQualifiedClassTypesAreCompatible(QualType LHS, QualType RHS);
2458 // Check the safety of assignment from LHS to RHS
2459 bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
2460 const ObjCObjectPointerType *RHSOPT);
2461 bool canAssignObjCInterfaces(const ObjCObjectType *LHS,
2462 const ObjCObjectType *RHS);
2463 bool canAssignObjCInterfacesInBlockPointer(
2464 const ObjCObjectPointerType *LHSOPT,
2465 const ObjCObjectPointerType *RHSOPT,
2466 bool BlockReturnType);
2467 bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
2468 QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT,
2469 const ObjCObjectPointerType *RHSOPT);
2470 bool canBindObjCObjectType(QualType To, QualType From);
2472 // Functions for calculating composite types
2473 QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false,
2474 bool Unqualified = false, bool BlockReturnType = false);
2475 QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false,
2476 bool Unqualified = false);
2477 QualType mergeFunctionParameterTypes(QualType, QualType,
2478 bool OfBlockPointer = false,
2479 bool Unqualified = false);
2480 QualType mergeTransparentUnionType(QualType, QualType,
2481 bool OfBlockPointer=false,
2482 bool Unqualified = false);
2484 QualType mergeObjCGCQualifiers(QualType, QualType);
2486 /// This function merges the ExtParameterInfo lists of two functions. It
2487 /// returns true if the lists are compatible. The merged list is returned in
2490 /// \param FirstFnType The type of the first function.
2492 /// \param SecondFnType The type of the second function.
2494 /// \param CanUseFirst This flag is set to true if the first function's
2495 /// ExtParameterInfo list can be used as the composite list of
2496 /// ExtParameterInfo.
2498 /// \param CanUseSecond This flag is set to true if the second function's
2499 /// ExtParameterInfo list can be used as the composite list of
2500 /// ExtParameterInfo.
2502 /// \param NewParamInfos The composite list of ExtParameterInfo. The list is
2503 /// empty if none of the flags are set.
2505 bool mergeExtParameterInfo(
2506 const FunctionProtoType *FirstFnType,
2507 const FunctionProtoType *SecondFnType,
2508 bool &CanUseFirst, bool &CanUseSecond,
2509 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos);
2511 void ResetObjCLayout(const ObjCContainerDecl *CD);
2513 //===--------------------------------------------------------------------===//
2514 // Integer Predicates
2515 //===--------------------------------------------------------------------===//
2517 // The width of an integer, as defined in C99 6.2.6.2. This is the number
2518 // of bits in an integer type excluding any padding bits.
2519 unsigned getIntWidth(QualType T) const;
2521 // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
2522 // unsigned integer type. This method takes a signed type, and returns the
2523 // corresponding unsigned integer type.
2524 QualType getCorrespondingUnsignedType(QualType T) const;
2526 //===--------------------------------------------------------------------===//
2528 //===--------------------------------------------------------------------===//
2530 /// \brief Make an APSInt of the appropriate width and signedness for the
2531 /// given \p Value and integer \p Type.
2532 llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const {
2533 // If Type is a signed integer type larger than 64 bits, we need to be sure
2534 // to sign extend Res appropriately.
2535 llvm::APSInt Res(64, !Type->isSignedIntegerOrEnumerationType());
2537 unsigned Width = getIntWidth(Type);
2538 if (Width != Res.getBitWidth())
2539 return Res.extOrTrunc(Width);
2543 bool isSentinelNullExpr(const Expr *E);
2545 /// \brief Get the implementation of the ObjCInterfaceDecl \p D, or nullptr if
2547 ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D);
2549 /// \brief Get the implementation of the ObjCCategoryDecl \p D, or nullptr if
2551 ObjCCategoryImplDecl *getObjCImplementation(ObjCCategoryDecl *D);
2553 /// \brief Return true if there is at least one \@implementation in the TU.
2554 bool AnyObjCImplementation() {
2555 return !ObjCImpls.empty();
2558 /// \brief Set the implementation of ObjCInterfaceDecl.
2559 void setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2560 ObjCImplementationDecl *ImplD);
2562 /// \brief Set the implementation of ObjCCategoryDecl.
2563 void setObjCImplementation(ObjCCategoryDecl *CatD,
2564 ObjCCategoryImplDecl *ImplD);
2566 /// \brief Get the duplicate declaration of a ObjCMethod in the same
2567 /// interface, or null if none exists.
2568 const ObjCMethodDecl *
2569 getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const;
2571 void setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2572 const ObjCMethodDecl *Redecl);
2574 /// \brief Returns the Objective-C interface that \p ND belongs to if it is
2575 /// an Objective-C method/property/ivar etc. that is part of an interface,
2576 /// otherwise returns null.
2577 const ObjCInterfaceDecl *getObjContainingInterface(const NamedDecl *ND) const;
2579 /// \brief Set the copy inialization expression of a block var decl.
2580 void setBlockVarCopyInits(VarDecl*VD, Expr* Init);
2582 /// \brief Get the copy initialization expression of the VarDecl \p VD, or
2583 /// nullptr if none exists.
2584 Expr *getBlockVarCopyInits(const VarDecl* VD);
2586 /// \brief Allocate an uninitialized TypeSourceInfo.
2588 /// The caller should initialize the memory held by TypeSourceInfo using
2589 /// the TypeLoc wrappers.
2591 /// \param T the type that will be the basis for type source info. This type
2592 /// should refer to how the declarator was written in source code, not to
2593 /// what type semantic analysis resolved the declarator to.
2595 /// \param Size the size of the type info to create, or 0 if the size
2596 /// should be calculated based on the type.
2597 TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0) const;
2599 /// \brief Allocate a TypeSourceInfo where all locations have been
2600 /// initialized to a given location, which defaults to the empty
2603 getTrivialTypeSourceInfo(QualType T,
2604 SourceLocation Loc = SourceLocation()) const;
2606 /// \brief Add a deallocation callback that will be invoked when the
2607 /// ASTContext is destroyed.
2609 /// \param Callback A callback function that will be invoked on destruction.
2611 /// \param Data Pointer data that will be provided to the callback function
2612 /// when it is called.
2613 void AddDeallocation(void (*Callback)(void*), void *Data);
2615 /// If T isn't trivially destructible, calls AddDeallocation to register it
2616 /// for destruction.
2617 template <typename T>
2618 void addDestruction(T *Ptr) {
2619 if (!std::is_trivially_destructible<T>::value) {
2620 auto DestroyPtr = [](void *V) { static_cast<T *>(V)->~T(); };
2621 AddDeallocation(DestroyPtr, Ptr);
2625 GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const;
2626 GVALinkage GetGVALinkageForVariable(const VarDecl *VD);
2628 /// \brief Determines if the decl can be CodeGen'ed or deserialized from PCH
2629 /// lazily, only when used; this is only relevant for function or file scoped
2630 /// var definitions.
2632 /// \returns true if the function/var must be CodeGen'ed/deserialized even if
2634 bool DeclMustBeEmitted(const Decl *D);
2636 const CXXConstructorDecl *
2637 getCopyConstructorForExceptionObject(CXXRecordDecl *RD);
2639 void addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
2640 CXXConstructorDecl *CD);
2642 void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND);
2644 TypedefNameDecl *getTypedefNameForUnnamedTagDecl(const TagDecl *TD);
2646 void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD);
2648 DeclaratorDecl *getDeclaratorForUnnamedTagDecl(const TagDecl *TD);
2650 void setManglingNumber(const NamedDecl *ND, unsigned Number);
2651 unsigned getManglingNumber(const NamedDecl *ND) const;
2653 void setStaticLocalNumber(const VarDecl *VD, unsigned Number);
2654 unsigned getStaticLocalNumber(const VarDecl *VD) const;
2656 /// \brief Retrieve the context for computing mangling numbers in the given
2658 MangleNumberingContext &getManglingNumberContext(const DeclContext *DC);
2660 std::unique_ptr<MangleNumberingContext> createMangleNumberingContext() const;
2662 /// \brief Used by ParmVarDecl to store on the side the
2663 /// index of the parameter when it exceeds the size of the normal bitfield.
2664 void setParameterIndex(const ParmVarDecl *D, unsigned index);
2666 /// \brief Used by ParmVarDecl to retrieve on the side the
2667 /// index of the parameter when it exceeds the size of the normal bitfield.
2668 unsigned getParameterIndex(const ParmVarDecl *D) const;
2670 /// \brief Get the storage for the constant value of a materialized temporary
2671 /// of static storage duration.
2672 APValue *getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
2675 //===--------------------------------------------------------------------===//
2677 //===--------------------------------------------------------------------===//
2679 /// \brief The number of implicitly-declared default constructors.
2680 static unsigned NumImplicitDefaultConstructors;
2682 /// \brief The number of implicitly-declared default constructors for
2683 /// which declarations were built.
2684 static unsigned NumImplicitDefaultConstructorsDeclared;
2686 /// \brief The number of implicitly-declared copy constructors.
2687 static unsigned NumImplicitCopyConstructors;
2689 /// \brief The number of implicitly-declared copy constructors for
2690 /// which declarations were built.
2691 static unsigned NumImplicitCopyConstructorsDeclared;
2693 /// \brief The number of implicitly-declared move constructors.
2694 static unsigned NumImplicitMoveConstructors;
2696 /// \brief The number of implicitly-declared move constructors for
2697 /// which declarations were built.
2698 static unsigned NumImplicitMoveConstructorsDeclared;
2700 /// \brief The number of implicitly-declared copy assignment operators.
2701 static unsigned NumImplicitCopyAssignmentOperators;
2703 /// \brief The number of implicitly-declared copy assignment operators for
2704 /// which declarations were built.
2705 static unsigned NumImplicitCopyAssignmentOperatorsDeclared;
2707 /// \brief The number of implicitly-declared move assignment operators.
2708 static unsigned NumImplicitMoveAssignmentOperators;
2710 /// \brief The number of implicitly-declared move assignment operators for
2711 /// which declarations were built.
2712 static unsigned NumImplicitMoveAssignmentOperatorsDeclared;
2714 /// \brief The number of implicitly-declared destructors.
2715 static unsigned NumImplicitDestructors;
2717 /// \brief The number of implicitly-declared destructors for which
2718 /// declarations were built.
2719 static unsigned NumImplicitDestructorsDeclared;
2722 /// \brief Initialize built-in types.
2724 /// This routine may only be invoked once for a given ASTContext object.
2725 /// It is normally invoked after ASTContext construction.
2727 /// \param Target The target
2728 void InitBuiltinTypes(const TargetInfo &Target,
2729 const TargetInfo *AuxTarget = nullptr);
2732 void InitBuiltinType(CanQualType &R, BuiltinType::Kind K);
2734 // Return the Objective-C type encoding for a given type.
2735 void getObjCEncodingForTypeImpl(QualType t, std::string &S,
2736 bool ExpandPointedToStructures,
2737 bool ExpandStructures,
2738 const FieldDecl *Field,
2739 bool OutermostType = false,
2740 bool EncodingProperty = false,
2741 bool StructField = false,
2742 bool EncodeBlockParameters = false,
2743 bool EncodeClassNames = false,
2744 bool EncodePointerToObjCTypedef = false,
2745 QualType *NotEncodedT=nullptr) const;
2747 // Adds the encoding of the structure's members.
2748 void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S,
2749 const FieldDecl *Field,
2750 bool includeVBases = true,
2751 QualType *NotEncodedT=nullptr) const;
2754 // Adds the encoding of a method parameter or return type.
2755 void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
2756 QualType T, std::string& S,
2757 bool Extended) const;
2759 /// \brief Returns true if this is an inline-initialized static data member
2760 /// which is treated as a definition for MSVC compatibility.
2761 bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const;
2763 enum class InlineVariableDefinitionKind {
2764 /// Not an inline variable.
2767 /// Weak definition of inline variable.
2770 /// Weak for now, might become strong later in this TU.
2773 /// Strong definition.
2777 /// \brief Determine whether a definition of this inline variable should
2778 /// be treated as a weak or strong definition. For compatibility with
2779 /// C++14 and before, for a constexpr static data member, if there is an
2780 /// out-of-line declaration of the member, we may promote it from weak to
2782 InlineVariableDefinitionKind
2783 getInlineVariableDefinitionKind(const VarDecl *VD) const;
2786 friend class DeclarationNameTable;
2787 friend class DeclContext;
2789 const ASTRecordLayout &
2790 getObjCLayout(const ObjCInterfaceDecl *D,
2791 const ObjCImplementationDecl *Impl) const;
2793 /// \brief A set of deallocations that should be performed when the
2794 /// ASTContext is destroyed.
2795 // FIXME: We really should have a better mechanism in the ASTContext to
2796 // manage running destructors for types which do variable sized allocation
2797 // within the AST. In some places we thread the AST bump pointer allocator
2798 // into the datastructures which avoids this mess during deallocation but is
2799 // wasteful of memory, and here we require a lot of error prone book keeping
2800 // in order to track and run destructors while we're tearing things down.
2801 using DeallocationFunctionsAndArguments =
2802 llvm::SmallVector<std::pair<void (*)(void *), void *>, 16>;
2803 DeallocationFunctionsAndArguments Deallocations;
2805 // FIXME: This currently contains the set of StoredDeclMaps used
2806 // by DeclContext objects. This probably should not be in ASTContext,
2807 // but we include it here so that ASTContext can quickly deallocate them.
2808 llvm::PointerIntPair<StoredDeclsMap *, 1> LastSDM;
2810 std::unique_ptr<ParentMapPointers> PointerParents;
2811 std::unique_ptr<ParentMapOtherNodes> OtherParents;
2813 std::unique_ptr<VTableContextBase> VTContext;
2815 void ReleaseDeclContextMaps();
2816 void ReleaseParentMapEntries();
2819 enum PragmaSectionFlag : unsigned {
2825 PSF_Invalid = 0x80000000U,
2828 struct SectionInfo {
2829 DeclaratorDecl *Decl;
2830 SourceLocation PragmaSectionLocation;
2833 SectionInfo() = default;
2834 SectionInfo(DeclaratorDecl *Decl,
2835 SourceLocation PragmaSectionLocation,
2837 : Decl(Decl), PragmaSectionLocation(PragmaSectionLocation),
2838 SectionFlags(SectionFlags) {}
2841 llvm::StringMap<SectionInfo> SectionInfos;
2844 /// \brief Utility function for constructing a nullary selector.
2845 inline Selector GetNullarySelector(StringRef name, ASTContext &Ctx) {
2846 IdentifierInfo* II = &Ctx.Idents.get(name);
2847 return Ctx.Selectors.getSelector(0, &II);
2850 /// \brief Utility function for constructing an unary selector.
2851 inline Selector GetUnarySelector(StringRef name, ASTContext &Ctx) {
2852 IdentifierInfo* II = &Ctx.Idents.get(name);
2853 return Ctx.Selectors.getSelector(1, &II);
2856 } // namespace clang
2858 // operator new and delete aren't allowed inside namespaces.
2860 /// @brief Placement new for using the ASTContext's allocator.
2862 /// This placement form of operator new uses the ASTContext's allocator for
2863 /// obtaining memory.
2865 /// IMPORTANT: These are also declared in clang/AST/AttrIterator.h! Any changes
2866 /// here need to also be made there.
2868 /// We intentionally avoid using a nothrow specification here so that the calls
2869 /// to this operator will not perform a null check on the result -- the
2870 /// underlying allocator never returns null pointers.
2872 /// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
2874 /// // Default alignment (8)
2875 /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
2876 /// // Specific alignment
2877 /// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
2879 /// Memory allocated through this placement new operator does not need to be
2880 /// explicitly freed, as ASTContext will free all of this memory when it gets
2881 /// destroyed. Please note that you cannot use delete on the pointer.
2883 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
2884 /// @param C The ASTContext that provides the allocator.
2885 /// @param Alignment The alignment of the allocated memory (if the underlying
2886 /// allocator supports it).
2887 /// @return The allocated memory. Could be nullptr.
2888 inline void *operator new(size_t Bytes, const clang::ASTContext &C,
2890 return C.Allocate(Bytes, Alignment);
2893 /// @brief Placement delete companion to the new above.
2895 /// This operator is just a companion to the new above. There is no way of
2896 /// invoking it directly; see the new operator for more details. This operator
2897 /// is called implicitly by the compiler if a placement new expression using
2898 /// the ASTContext throws in the object constructor.
2899 inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t) {
2903 /// This placement form of operator new[] uses the ASTContext's allocator for
2904 /// obtaining memory.
2906 /// We intentionally avoid using a nothrow specification here so that the calls
2907 /// to this operator will not perform a null check on the result -- the
2908 /// underlying allocator never returns null pointers.
2910 /// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
2912 /// // Default alignment (8)
2913 /// char *data = new (Context) char[10];
2914 /// // Specific alignment
2915 /// char *data = new (Context, 4) char[10];
2917 /// Memory allocated through this placement new[] operator does not need to be
2918 /// explicitly freed, as ASTContext will free all of this memory when it gets
2919 /// destroyed. Please note that you cannot use delete on the pointer.
2921 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
2922 /// @param C The ASTContext that provides the allocator.
2923 /// @param Alignment The alignment of the allocated memory (if the underlying
2924 /// allocator supports it).
2925 /// @return The allocated memory. Could be nullptr.
2926 inline void *operator new[](size_t Bytes, const clang::ASTContext& C,
2927 size_t Alignment = 8) {
2928 return C.Allocate(Bytes, Alignment);
2931 /// @brief Placement delete[] companion to the new[] above.
2933 /// This operator is just a companion to the new[] above. There is no way of
2934 /// invoking it directly; see the new[] operator for more details. This operator
2935 /// is called implicitly by the compiler if a placement new[] expression using
2936 /// the ASTContext throws in the object constructor.
2937 inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_t) {
2941 /// \brief Create the representation of a LazyGenerationalUpdatePtr.
2942 template <typename Owner, typename T,
2943 void (clang::ExternalASTSource::*Update)(Owner)>
2944 typename clang::LazyGenerationalUpdatePtr<Owner, T, Update>::ValueType
2945 clang::LazyGenerationalUpdatePtr<Owner, T, Update>::makeValue(
2946 const clang::ASTContext &Ctx, T Value) {
2947 // Note, this is implemented here so that ExternalASTSource.h doesn't need to
2948 // include ASTContext.h. We explicitly instantiate it for all relevant types
2949 // in ASTContext.cpp.
2950 if (auto *Source = Ctx.getExternalSource())
2951 return new (Ctx) LazyData(Source, Value);
2955 #endif // LLVM_CLANG_AST_ASTCONTEXT_H