1//===- ASTContext.h - Context to hold long-lived AST nodes ------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// Defines the clang::ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_ASTCONTEXT_H
15#define LLVM_CLANG_AST_ASTCONTEXT_H
16
17#include "clang/AST/ASTFwd.h"
18#include "clang/AST/CanonicalType.h"
19#include "clang/AST/CommentCommandTraits.h"
20#include "clang/AST/ComparisonCategories.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclarationName.h"
23#include "clang/AST/ExternalASTSource.h"
24#include "clang/AST/PrettyPrinter.h"
25#include "clang/AST/RawCommentList.h"
26#include "clang/AST/TemplateName.h"
27#include "clang/Basic/LLVM.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "clang/Basic/SourceLocation.h"
30#include "llvm/ADT/DenseMap.h"
31#include "llvm/ADT/DenseSet.h"
32#include "llvm/ADT/FoldingSet.h"
33#include "llvm/ADT/IntrusiveRefCntPtr.h"
34#include "llvm/ADT/MapVector.h"
35#include "llvm/ADT/PointerIntPair.h"
36#include "llvm/ADT/PointerUnion.h"
37#include "llvm/ADT/SmallVector.h"
38#include "llvm/ADT/StringMap.h"
39#include "llvm/ADT/StringRef.h"
40#include "llvm/ADT/TinyPtrVector.h"
41#include "llvm/Support/TypeSize.h"
42#include <optional>
43
44namespace llvm {
45
46class APFixedPoint;
47class FixedPointSemantics;
48struct fltSemantics;
49template <typename T, unsigned N> class SmallPtrSet;
50
51} // namespace llvm
52
53namespace clang {
54
55class APValue;
56class ASTMutationListener;
57class ASTRecordLayout;
58class AtomicExpr;
59class BlockExpr;
60struct BlockVarCopyInit;
61class BuiltinTemplateDecl;
62class CharUnits;
63class ConceptDecl;
64class CXXABI;
65class CXXConstructorDecl;
66class CXXMethodDecl;
67class CXXRecordDecl;
68class DiagnosticsEngine;
69class DynTypedNodeList;
70class Expr;
71enum class FloatModeKind;
72class GlobalDecl;
73class IdentifierTable;
74class LangOptions;
75class MangleContext;
76class MangleNumberingContext;
77class MemberSpecializationInfo;
78class Module;
79struct MSGuidDeclParts;
80class NestedNameSpecifier;
81class NoSanitizeList;
82class ObjCCategoryDecl;
83class ObjCCategoryImplDecl;
84class ObjCContainerDecl;
85class ObjCImplDecl;
86class ObjCImplementationDecl;
87class ObjCInterfaceDecl;
88class ObjCIvarDecl;
89class ObjCMethodDecl;
90class ObjCPropertyDecl;
91class ObjCPropertyImplDecl;
92class ObjCProtocolDecl;
93class ObjCTypeParamDecl;
94class OMPTraitInfo;
95class ParentMapContext;
96struct ParsedTargetAttr;
97class Preprocessor;
98class ProfileList;
99class StoredDeclsMap;
100class TargetAttr;
101class TargetInfo;
102class TemplateDecl;
103class TemplateParameterList;
104class TemplateTemplateParmDecl;
105class TemplateTypeParmDecl;
106class TypeConstraint;
107class UnresolvedSetIterator;
108class UsingShadowDecl;
109class VarTemplateDecl;
110class VTableContextBase;
111class XRayFunctionFilter;
112
113namespace Builtin {
114
115class Context;
116
117} // namespace Builtin
118
119enum BuiltinTemplateKind : int;
120enum OpenCLTypeKind : uint8_t;
121
122namespace comments {
123
124class FullComment;
125
126} // namespace comments
127
128namespace interp {
129
130class Context;
131
132} // namespace interp
133
134namespace serialization {
135template <class> class AbstractTypeReader;
136} // namespace serialization
137
138enum class AlignRequirementKind {
139 /// The alignment was not explicit in code.
140 None,
141
142 /// The alignment comes from an alignment attribute on a typedef.
143 RequiredByTypedef,
144
145 /// The alignment comes from an alignment attribute on a record type.
146 RequiredByRecord,
147
148 /// The alignment comes from an alignment attribute on a enum type.
149 RequiredByEnum,
150};
151
152struct TypeInfo {
153 uint64_t Width = 0;
154 unsigned Align = 0;
155 AlignRequirementKind AlignRequirement;
156
157 TypeInfo() : AlignRequirement(AlignRequirementKind::None) {}
158 TypeInfo(uint64_t Width, unsigned Align,
159 AlignRequirementKind AlignRequirement)
160 : Width(Width), Align(Align), AlignRequirement(AlignRequirement) {}
161 bool isAlignRequired() {
162 return AlignRequirement != AlignRequirementKind::None;
163 }
164};
165
166struct TypeInfoChars {
167 CharUnits Width;
168 CharUnits Align;
169 AlignRequirementKind AlignRequirement;
170
171 TypeInfoChars() : AlignRequirement(AlignRequirementKind::None) {}
172 TypeInfoChars(CharUnits Width, CharUnits Align,
173 AlignRequirementKind AlignRequirement)
174 : Width(Width), Align(Align), AlignRequirement(AlignRequirement) {}
175 bool isAlignRequired() {
176 return AlignRequirement != AlignRequirementKind::None;
177 }
178};
179
180/// Holds long-lived AST nodes (such as types and decls) that can be
181/// referred to throughout the semantic analysis of a file.
182class ASTContext : public RefCountedBase<ASTContext> {
183 friend class NestedNameSpecifier;
184
185 mutable SmallVector<Type *, 0> Types;
186 mutable llvm::FoldingSet<ExtQuals> ExtQualNodes;
187 mutable llvm::FoldingSet<ComplexType> ComplexTypes;
188 mutable llvm::FoldingSet<PointerType> PointerTypes{GeneralTypesLog2InitSize};
189 mutable llvm::FoldingSet<AdjustedType> AdjustedTypes;
190 mutable llvm::FoldingSet<BlockPointerType> BlockPointerTypes;
191 mutable llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes;
192 mutable llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes;
193 mutable llvm::FoldingSet<MemberPointerType> MemberPointerTypes;
194 mutable llvm::ContextualFoldingSet<ConstantArrayType, ASTContext &>
195 ConstantArrayTypes;
196 mutable llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
197 mutable std::vector<VariableArrayType*> VariableArrayTypes;
198 mutable llvm::ContextualFoldingSet<DependentSizedArrayType, ASTContext &>
199 DependentSizedArrayTypes;
200 mutable llvm::ContextualFoldingSet<DependentSizedExtVectorType, ASTContext &>
201 DependentSizedExtVectorTypes;
202 mutable llvm::ContextualFoldingSet<DependentAddressSpaceType, ASTContext &>
203 DependentAddressSpaceTypes;
204 mutable llvm::FoldingSet<VectorType> VectorTypes;
205 mutable llvm::ContextualFoldingSet<DependentVectorType, ASTContext &>
206 DependentVectorTypes;
207 mutable llvm::FoldingSet<ConstantMatrixType> MatrixTypes;
208 mutable llvm::ContextualFoldingSet<DependentSizedMatrixType, ASTContext &>
209 DependentSizedMatrixTypes;
210 mutable llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes;
211 mutable llvm::ContextualFoldingSet<FunctionProtoType, ASTContext&>
212 FunctionProtoTypes;
213 mutable llvm::ContextualFoldingSet<DependentTypeOfExprType, ASTContext &>
214 DependentTypeOfExprTypes;
215 mutable llvm::ContextualFoldingSet<DependentDecltypeType, ASTContext &>
216 DependentDecltypeTypes;
217
218 mutable llvm::FoldingSet<PackIndexingType> DependentPackIndexingTypes;
219
220 mutable llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes;
221 mutable llvm::FoldingSet<ObjCTypeParamType> ObjCTypeParamTypes;
222 mutable llvm::FoldingSet<SubstTemplateTypeParmType>
223 SubstTemplateTypeParmTypes;
224 mutable llvm::FoldingSet<SubstTemplateTypeParmPackType>
225 SubstTemplateTypeParmPackTypes;
226 mutable llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&>
227 TemplateSpecializationTypes;
228 mutable llvm::FoldingSet<ParenType> ParenTypes{GeneralTypesLog2InitSize};
229 mutable llvm::FoldingSet<UsingType> UsingTypes;
230 mutable llvm::FoldingSet<TypedefType> TypedefTypes;
231 mutable llvm::FoldingSet<ElaboratedType> ElaboratedTypes{
232 GeneralTypesLog2InitSize};
233 mutable llvm::FoldingSet<DependentNameType> DependentNameTypes;
234 mutable llvm::ContextualFoldingSet<DependentTemplateSpecializationType,
235 ASTContext&>
236 DependentTemplateSpecializationTypes;
237 llvm::FoldingSet<PackExpansionType> PackExpansionTypes;
238 mutable llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes;
239 mutable llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes;
240 mutable llvm::FoldingSet<DependentUnaryTransformType>
241 DependentUnaryTransformTypes;
242 mutable llvm::ContextualFoldingSet<AutoType, ASTContext&> AutoTypes;
243 mutable llvm::FoldingSet<DeducedTemplateSpecializationType>
244 DeducedTemplateSpecializationTypes;
245 mutable llvm::FoldingSet<AtomicType> AtomicTypes;
246 mutable llvm::FoldingSet<AttributedType> AttributedTypes;
247 mutable llvm::FoldingSet<PipeType> PipeTypes;
248 mutable llvm::FoldingSet<BitIntType> BitIntTypes;
249 mutable llvm::ContextualFoldingSet<DependentBitIntType, ASTContext &>
250 DependentBitIntTypes;
251 llvm::FoldingSet<BTFTagAttributedType> BTFTagAttributedTypes;
252
253 mutable llvm::FoldingSet<CountAttributedType> CountAttributedTypes;
254
255 mutable llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames;
256 mutable llvm::FoldingSet<DependentTemplateName> DependentTemplateNames;
257 mutable llvm::FoldingSet<SubstTemplateTemplateParmStorage>
258 SubstTemplateTemplateParms;
259 mutable llvm::ContextualFoldingSet<SubstTemplateTemplateParmPackStorage,
260 ASTContext&>
261 SubstTemplateTemplateParmPacks;
262
263 mutable llvm::ContextualFoldingSet<ArrayParameterType, ASTContext &>
264 ArrayParameterTypes;
265
266 /// The set of nested name specifiers.
267 ///
268 /// This set is managed by the NestedNameSpecifier class.
269 mutable llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers;
270 mutable NestedNameSpecifier *GlobalNestedNameSpecifier = nullptr;
271
272 /// A cache mapping from RecordDecls to ASTRecordLayouts.
273 ///
274 /// This is lazily created. This is intentionally not serialized.
275 mutable llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>
276 ASTRecordLayouts;
277 mutable llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>
278 ObjCLayouts;
279
280 /// A cache from types to size and alignment information.
281 using TypeInfoMap = llvm::DenseMap<const Type *, struct TypeInfo>;
282 mutable TypeInfoMap MemoizedTypeInfo;
283
284 /// A cache from types to unadjusted alignment information. Only ARM and
285 /// AArch64 targets need this information, keeping it separate prevents
286 /// imposing overhead on TypeInfo size.
287 using UnadjustedAlignMap = llvm::DenseMap<const Type *, unsigned>;
288 mutable UnadjustedAlignMap MemoizedUnadjustedAlign;
289
290 /// A cache mapping from CXXRecordDecls to key functions.
291 llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr> KeyFunctions;
292
293 /// Mapping from ObjCContainers to their ObjCImplementations.
294 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls;
295
296 /// Mapping from ObjCMethod to its duplicate declaration in the same
297 /// interface.
298 llvm::DenseMap<const ObjCMethodDecl*,const ObjCMethodDecl*> ObjCMethodRedecls;
299
300 /// Mapping from __block VarDecls to BlockVarCopyInit.
301 llvm::DenseMap<const VarDecl *, BlockVarCopyInit> BlockVarCopyInits;
302
303 /// Mapping from GUIDs to the corresponding MSGuidDecl.
304 mutable llvm::FoldingSet<MSGuidDecl> MSGuidDecls;
305
306 /// Mapping from APValues to the corresponding UnnamedGlobalConstantDecl.
307 mutable llvm::FoldingSet<UnnamedGlobalConstantDecl>
308 UnnamedGlobalConstantDecls;
309
310 /// Mapping from APValues to the corresponding TemplateParamObjects.
311 mutable llvm::FoldingSet<TemplateParamObjectDecl> TemplateParamObjectDecls;
312
313 /// A cache mapping a string value to a StringLiteral object with the same
314 /// value.
315 ///
316 /// This is lazily created. This is intentionally not serialized.
317 mutable llvm::StringMap<StringLiteral *> StringLiteralCache;
318
319 /// MD5 hash of CUID. It is calculated when first used and cached by this
320 /// data member.
321 mutable std::string CUIDHash;
322
323 /// Representation of a "canonical" template template parameter that
324 /// is used in canonical template names.
325 class CanonicalTemplateTemplateParm : public llvm::FoldingSetNode {
326 TemplateTemplateParmDecl *Parm;
327
328 public:
329 CanonicalTemplateTemplateParm(TemplateTemplateParmDecl *Parm)
330 : Parm(Parm) {}
331
332 TemplateTemplateParmDecl *getParam() const { return Parm; }
333
334 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &C) {
335 Profile(ID, C, Parm);
336 }
337
338 static void Profile(llvm::FoldingSetNodeID &ID,
339 const ASTContext &C,
340 TemplateTemplateParmDecl *Parm);
341 };
342 mutable llvm::ContextualFoldingSet<CanonicalTemplateTemplateParm,
343 const ASTContext&>
344 CanonTemplateTemplateParms;
345
346 TemplateTemplateParmDecl *
347 getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const;
348
349 /// The typedef for the __int128_t type.
350 mutable TypedefDecl *Int128Decl = nullptr;
351
352 /// The typedef for the __uint128_t type.
353 mutable TypedefDecl *UInt128Decl = nullptr;
354
355 /// The typedef for the target specific predefined
356 /// __builtin_va_list type.
357 mutable TypedefDecl *BuiltinVaListDecl = nullptr;
358
359 /// The typedef for the predefined \c __builtin_ms_va_list type.
360 mutable TypedefDecl *BuiltinMSVaListDecl = nullptr;
361
362 /// The typedef for the predefined \c id type.
363 mutable TypedefDecl *ObjCIdDecl = nullptr;
364
365 /// The typedef for the predefined \c SEL type.
366 mutable TypedefDecl *ObjCSelDecl = nullptr;
367
368 /// The typedef for the predefined \c Class type.
369 mutable TypedefDecl *ObjCClassDecl = nullptr;
370
371 /// The typedef for the predefined \c Protocol class in Objective-C.
372 mutable ObjCInterfaceDecl *ObjCProtocolClassDecl = nullptr;
373
374 /// The typedef for the predefined 'BOOL' type.
375 mutable TypedefDecl *BOOLDecl = nullptr;
376
377 // Typedefs which may be provided defining the structure of Objective-C
378 // pseudo-builtins
379 QualType ObjCIdRedefinitionType;
380 QualType ObjCClassRedefinitionType;
381 QualType ObjCSelRedefinitionType;
382
383 /// The identifier 'bool'.
384 mutable IdentifierInfo *BoolName = nullptr;
385
386 /// The identifier 'NSObject'.
387 mutable IdentifierInfo *NSObjectName = nullptr;
388
389 /// The identifier 'NSCopying'.
390 IdentifierInfo *NSCopyingName = nullptr;
391
392 /// The identifier '__make_integer_seq'.
393 mutable IdentifierInfo *MakeIntegerSeqName = nullptr;
394
395 /// The identifier '__type_pack_element'.
396 mutable IdentifierInfo *TypePackElementName = nullptr;
397
398 QualType ObjCConstantStringType;
399 mutable RecordDecl *CFConstantStringTagDecl = nullptr;
400 mutable TypedefDecl *CFConstantStringTypeDecl = nullptr;
401
402 mutable QualType ObjCSuperType;
403
404 QualType ObjCNSStringType;
405
406 /// The typedef declaration for the Objective-C "instancetype" type.
407 TypedefDecl *ObjCInstanceTypeDecl = nullptr;
408
409 /// The type for the C FILE type.
410 TypeDecl *FILEDecl = nullptr;
411
412 /// The type for the C jmp_buf type.
413 TypeDecl *jmp_bufDecl = nullptr;
414
415 /// The type for the C sigjmp_buf type.
416 TypeDecl *sigjmp_bufDecl = nullptr;
417
418 /// The type for the C ucontext_t type.
419 TypeDecl *ucontext_tDecl = nullptr;
420
421 /// Type for the Block descriptor for Blocks CodeGen.
422 ///
423 /// Since this is only used for generation of debug info, it is not
424 /// serialized.
425 mutable RecordDecl *BlockDescriptorType = nullptr;
426
427 /// Type for the Block descriptor for Blocks CodeGen.
428 ///
429 /// Since this is only used for generation of debug info, it is not
430 /// serialized.
431 mutable RecordDecl *BlockDescriptorExtendedType = nullptr;
432
433 /// Declaration for the CUDA cudaConfigureCall function.
434 FunctionDecl *cudaConfigureCallDecl = nullptr;
435
436 /// Keeps track of all declaration attributes.
437 ///
438 /// Since so few decls have attrs, we keep them in a hash map instead of
439 /// wasting space in the Decl class.
440 llvm::DenseMap<const Decl*, AttrVec*> DeclAttrs;
441
442 /// A mapping from non-redeclarable declarations in modules that were
443 /// merged with other declarations to the canonical declaration that they were
444 /// merged into.
445 llvm::DenseMap<Decl*, Decl*> MergedDecls;
446
447 /// A mapping from a defining declaration to a list of modules (other
448 /// than the owning module of the declaration) that contain merged
449 /// definitions of that entity.
450 llvm::DenseMap<NamedDecl*, llvm::TinyPtrVector<Module*>> MergedDefModules;
451
452 /// Initializers for a module, in order. Each Decl will be either
453 /// something that has a semantic effect on startup (such as a variable with
454 /// a non-constant initializer), or an ImportDecl (which recursively triggers
455 /// initialization of another module).
456 struct PerModuleInitializers {
457 llvm::SmallVector<Decl*, 4> Initializers;
458 llvm::SmallVector<Decl::DeclID, 4> LazyInitializers;
459
460 void resolve(ASTContext &Ctx);
461 };
462 llvm::DenseMap<Module*, PerModuleInitializers*> ModuleInitializers;
463
464 /// This is the top-level (C++20) Named module we are building.
465 Module *CurrentCXXNamedModule = nullptr;
466
467 static constexpr unsigned ConstantArrayTypesLog2InitSize = 8;
468 static constexpr unsigned GeneralTypesLog2InitSize = 9;
469 static constexpr unsigned FunctionProtoTypesLog2InitSize = 12;
470
471 ASTContext &this_() { return *this; }
472
473public:
474 /// A type synonym for the TemplateOrInstantiation mapping.
475 using TemplateOrSpecializationInfo =
476 llvm::PointerUnion<VarTemplateDecl *, MemberSpecializationInfo *>;
477
478private:
479 friend class ASTDeclReader;
480 friend class ASTReader;
481 friend class ASTWriter;
482 template <class> friend class serialization::AbstractTypeReader;
483 friend class CXXRecordDecl;
484 friend class IncrementalParser;
485
486 /// A mapping to contain the template or declaration that
487 /// a variable declaration describes or was instantiated from,
488 /// respectively.
489 ///
490 /// For non-templates, this value will be NULL. For variable
491 /// declarations that describe a variable template, this will be a
492 /// pointer to a VarTemplateDecl. For static data members
493 /// of class template specializations, this will be the
494 /// MemberSpecializationInfo referring to the member variable that was
495 /// instantiated or specialized. Thus, the mapping will keep track of
496 /// the static data member templates from which static data members of
497 /// class template specializations were instantiated.
498 ///
499 /// Given the following example:
500 ///
501 /// \code
502 /// template<typename T>
503 /// struct X {
504 /// static T value;
505 /// };
506 ///
507 /// template<typename T>
508 /// T X<T>::value = T(17);
509 ///
510 /// int *x = &X<int>::value;
511 /// \endcode
512 ///
513 /// This mapping will contain an entry that maps from the VarDecl for
514 /// X<int>::value to the corresponding VarDecl for X<T>::value (within the
515 /// class template X) and will be marked TSK_ImplicitInstantiation.
516 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>
517 TemplateOrInstantiation;
518
519 /// Keeps track of the declaration from which a using declaration was
520 /// created during instantiation.
521 ///
522 /// The source and target declarations are always a UsingDecl, an
523 /// UnresolvedUsingValueDecl, or an UnresolvedUsingTypenameDecl.
524 ///
525 /// For example:
526 /// \code
527 /// template<typename T>
528 /// struct A {
529 /// void f();
530 /// };
531 ///
532 /// template<typename T>
533 /// struct B : A<T> {
534 /// using A<T>::f;
535 /// };
536 ///
537 /// template struct B<int>;
538 /// \endcode
539 ///
540 /// This mapping will contain an entry that maps from the UsingDecl in
541 /// B<int> to the UnresolvedUsingDecl in B<T>.
542 llvm::DenseMap<NamedDecl *, NamedDecl *> InstantiatedFromUsingDecl;
543
544 /// Like InstantiatedFromUsingDecl, but for using-enum-declarations. Maps
545 /// from the instantiated using-enum to the templated decl from whence it
546 /// came.
547 /// Note that using-enum-declarations cannot be dependent and
548 /// thus will never be instantiated from an "unresolved"
549 /// version thereof (as with using-declarations), so each mapping is from
550 /// a (resolved) UsingEnumDecl to a (resolved) UsingEnumDecl.
551 llvm::DenseMap<UsingEnumDecl *, UsingEnumDecl *>
552 InstantiatedFromUsingEnumDecl;
553
554 /// Simlarly maps instantiated UsingShadowDecls to their origin.
555 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>
556 InstantiatedFromUsingShadowDecl;
557
558 llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl;
559
560 /// Mapping that stores the methods overridden by a given C++
561 /// member function.
562 ///
563 /// Since most C++ member functions aren't virtual and therefore
564 /// don't override anything, we store the overridden functions in
565 /// this map on the side rather than within the CXXMethodDecl structure.
566 using CXXMethodVector = llvm::TinyPtrVector<const CXXMethodDecl *>;
567 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector> OverriddenMethods;
568
569 /// Mapping from each declaration context to its corresponding
570 /// mangling numbering context (used for constructs like lambdas which
571 /// need to be consistently numbered for the mangler).
572 llvm::DenseMap<const DeclContext *, std::unique_ptr<MangleNumberingContext>>
573 MangleNumberingContexts;
574 llvm::DenseMap<const Decl *, std::unique_ptr<MangleNumberingContext>>
575 ExtraMangleNumberingContexts;
576
577 /// Side-table of mangling numbers for declarations which rarely
578 /// need them (like static local vars).
579 llvm::MapVector<const NamedDecl *, unsigned> MangleNumbers;
580 llvm::MapVector<const VarDecl *, unsigned> StaticLocalNumbers;
581 /// Mapping the associated device lambda mangling number if present.
582 mutable llvm::DenseMap<const CXXRecordDecl *, unsigned>
583 DeviceLambdaManglingNumbers;
584
585 /// Mapping that stores parameterIndex values for ParmVarDecls when
586 /// that value exceeds the bitfield size of ParmVarDeclBits.ParameterIndex.
587 using ParameterIndexTable = llvm::DenseMap<const VarDecl *, unsigned>;
588 ParameterIndexTable ParamIndices;
589
590 ImportDecl *FirstLocalImport = nullptr;
591 ImportDecl *LastLocalImport = nullptr;
592
593 TranslationUnitDecl *TUDecl = nullptr;
594 mutable ExternCContextDecl *ExternCContext = nullptr;
595 mutable BuiltinTemplateDecl *MakeIntegerSeqDecl = nullptr;
596 mutable BuiltinTemplateDecl *TypePackElementDecl = nullptr;
597
598 /// The associated SourceManager object.
599 SourceManager &SourceMgr;
600
601 /// The language options used to create the AST associated with
602 /// this ASTContext object.
603 LangOptions &LangOpts;
604
605 /// NoSanitizeList object that is used by sanitizers to decide which
606 /// entities should not be instrumented.
607 std::unique_ptr<NoSanitizeList> NoSanitizeL;
608
609 /// Function filtering mechanism to determine whether a given function
610 /// should be imbued with the XRay "always" or "never" attributes.
611 std::unique_ptr<XRayFunctionFilter> XRayFilter;
612
613 /// ProfileList object that is used by the profile instrumentation
614 /// to decide which entities should be instrumented.
615 std::unique_ptr<ProfileList> ProfList;
616
617 /// The allocator used to create AST objects.
618 ///
619 /// AST objects are never destructed; rather, all memory associated with the
620 /// AST objects will be released when the ASTContext itself is destroyed.
621 mutable llvm::BumpPtrAllocator BumpAlloc;
622
623 /// Allocator for partial diagnostics.
624 PartialDiagnostic::DiagStorageAllocator DiagAllocator;
625
626 /// The current C++ ABI.
627 std::unique_ptr<CXXABI> ABI;
628 CXXABI *createCXXABI(const TargetInfo &T);
629
630 /// Address space map mangling must be used with language specific
631 /// address spaces (e.g. OpenCL/CUDA)
632 bool AddrSpaceMapMangling;
633
634 const TargetInfo *Target = nullptr;
635 const TargetInfo *AuxTarget = nullptr;
636 clang::PrintingPolicy PrintingPolicy;
637 std::unique_ptr<interp::Context> InterpContext;
638 std::unique_ptr<ParentMapContext> ParentMapCtx;
639
640 /// Keeps track of the deallocated DeclListNodes for future reuse.
641 DeclListNode *ListNodeFreeList = nullptr;
642
643public:
644 IdentifierTable &Idents;
645 SelectorTable &Selectors;
646 Builtin::Context &BuiltinInfo;
647 const TranslationUnitKind TUKind;
648 mutable DeclarationNameTable DeclarationNames;
649 IntrusiveRefCntPtr<ExternalASTSource> ExternalSource;
650 ASTMutationListener *Listener = nullptr;
651
652 /// Returns the clang bytecode interpreter context.
653 interp::Context &getInterpContext();
654
655 struct CUDAConstantEvalContext {
656 /// Do not allow wrong-sided variables in constant expressions.
657 bool NoWrongSidedVars = false;
658 } CUDAConstantEvalCtx;
659 struct CUDAConstantEvalContextRAII {
660 ASTContext &Ctx;
661 CUDAConstantEvalContext SavedCtx;
662 CUDAConstantEvalContextRAII(ASTContext &Ctx_, bool NoWrongSidedVars)
663 : Ctx(Ctx_), SavedCtx(Ctx_.CUDAConstantEvalCtx) {
664 Ctx_.CUDAConstantEvalCtx.NoWrongSidedVars = NoWrongSidedVars;
665 }
666 ~CUDAConstantEvalContextRAII() { Ctx.CUDAConstantEvalCtx = SavedCtx; }
667 };
668
669 /// Returns the dynamic AST node parent map context.
670 ParentMapContext &getParentMapContext();
671
672 // A traversal scope limits the parts of the AST visible to certain analyses.
673 // RecursiveASTVisitor only visits specified children of TranslationUnitDecl.
674 // getParents() will only observe reachable parent edges.
675 //
676 // The scope is defined by a set of "top-level" declarations which will be
677 // visible under the TranslationUnitDecl.
678 // Initially, it is the entire TU, represented by {getTranslationUnitDecl()}.
679 //
680 // After setTraversalScope({foo, bar}), the exposed AST looks like:
681 // TranslationUnitDecl
682 // - foo
683 // - ...
684 // - bar
685 // - ...
686 // All other siblings of foo and bar are pruned from the tree.
687 // (However they are still accessible via TranslationUnitDecl->decls())
688 //
689 // Changing the scope clears the parent cache, which is expensive to rebuild.
690 std::vector<Decl *> getTraversalScope() const { return TraversalScope; }
691 void setTraversalScope(const std::vector<Decl *> &);
692
693 /// Forwards to get node parents from the ParentMapContext. New callers should
694 /// use ParentMapContext::getParents() directly.
695 template <typename NodeT> DynTypedNodeList getParents(const NodeT &Node);
696
697 const clang::PrintingPolicy &getPrintingPolicy() const {
698 return PrintingPolicy;
699 }
700
701 void setPrintingPolicy(const clang::PrintingPolicy &Policy) {
702 PrintingPolicy = Policy;
703 }
704
705 SourceManager& getSourceManager() { return SourceMgr; }
706 const SourceManager& getSourceManager() const { return SourceMgr; }
707
708 // Cleans up some of the data structures. This allows us to do cleanup
709 // normally done in the destructor earlier. Renders much of the ASTContext
710 // unusable, mostly the actual AST nodes, so should be called when we no
711 // longer need access to the AST.
712 void cleanup();
713
714 llvm::BumpPtrAllocator &getAllocator() const {
715 return BumpAlloc;
716 }
717
718 void *Allocate(size_t Size, unsigned Align = 8) const {
719 return BumpAlloc.Allocate(Size, Alignment: Align);
720 }
721 template <typename T> T *Allocate(size_t Num = 1) const {
722 return static_cast<T *>(Allocate(Size: Num * sizeof(T), Align: alignof(T)));
723 }
724 void Deallocate(void *Ptr) const {}
725
726 /// Allocates a \c DeclListNode or returns one from the \c ListNodeFreeList
727 /// pool.
728 DeclListNode *AllocateDeclListNode(clang::NamedDecl *ND) {
729 if (DeclListNode *Alloc = ListNodeFreeList) {
730 ListNodeFreeList = Alloc->Rest.dyn_cast<DeclListNode*>();
731 Alloc->D = ND;
732 Alloc->Rest = nullptr;
733 return Alloc;
734 }
735 return new (*this) DeclListNode(ND);
736 }
737 /// Deallcates a \c DeclListNode by returning it to the \c ListNodeFreeList
738 /// pool.
739 void DeallocateDeclListNode(DeclListNode *N) {
740 N->Rest = ListNodeFreeList;
741 ListNodeFreeList = N;
742 }
743
744 /// Return the total amount of physical memory allocated for representing
745 /// AST nodes and type information.
746 size_t getASTAllocatedMemory() const {
747 return BumpAlloc.getTotalMemory();
748 }
749
750 /// Return the total memory used for various side tables.
751 size_t getSideTableAllocatedMemory() const;
752
753 PartialDiagnostic::DiagStorageAllocator &getDiagAllocator() {
754 return DiagAllocator;
755 }
756
757 const TargetInfo &getTargetInfo() const { return *Target; }
758 const TargetInfo *getAuxTargetInfo() const { return AuxTarget; }
759
760 /// getIntTypeForBitwidth -
761 /// sets integer QualTy according to specified details:
762 /// bitwidth, signed/unsigned.
763 /// Returns empty type if there is no appropriate target types.
764 QualType getIntTypeForBitwidth(unsigned DestWidth,
765 unsigned Signed) const;
766
767 /// getRealTypeForBitwidth -
768 /// sets floating point QualTy according to specified bitwidth.
769 /// Returns empty type if there is no appropriate target types.
770 QualType getRealTypeForBitwidth(unsigned DestWidth,
771 FloatModeKind ExplicitType) const;
772
773 bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const;
774
775 const LangOptions& getLangOpts() const { return LangOpts; }
776
777 // If this condition is false, typo correction must be performed eagerly
778 // rather than delayed in many places, as it makes use of dependent types.
779 // the condition is false for clang's C-only codepath, as it doesn't support
780 // dependent types yet.
781 bool isDependenceAllowed() const {
782 return LangOpts.CPlusPlus || LangOpts.RecoveryAST;
783 }
784
785 const NoSanitizeList &getNoSanitizeList() const { return *NoSanitizeL; }
786
787 const XRayFunctionFilter &getXRayFilter() const {
788 return *XRayFilter;
789 }
790
791 const ProfileList &getProfileList() const { return *ProfList; }
792
793 DiagnosticsEngine &getDiagnostics() const;
794
795 FullSourceLoc getFullLoc(SourceLocation Loc) const {
796 return FullSourceLoc(Loc,SourceMgr);
797 }
798
799 /// Return the C++ ABI kind that should be used. The C++ ABI can be overriden
800 /// at compile time with `-fc++-abi=`. If this is not provided, we instead use
801 /// the default ABI set by the target.
802 TargetCXXABI::Kind getCXXABIKind() const;
803
804 /// All comments in this translation unit.
805 RawCommentList Comments;
806
807 /// True if comments are already loaded from ExternalASTSource.
808 mutable bool CommentsLoaded = false;
809
810 /// Mapping from declaration to directly attached comment.
811 ///
812 /// Raw comments are owned by Comments list. This mapping is populated
813 /// lazily.
814 mutable llvm::DenseMap<const Decl *, const RawComment *> DeclRawComments;
815
816 /// Mapping from canonical declaration to the first redeclaration in chain
817 /// that has a comment attached.
818 ///
819 /// Raw comments are owned by Comments list. This mapping is populated
820 /// lazily.
821 mutable llvm::DenseMap<const Decl *, const Decl *> RedeclChainComments;
822
823 /// Keeps track of redeclaration chains that don't have any comment attached.
824 /// Mapping from canonical declaration to redeclaration chain that has no
825 /// comments attached to any redeclaration. Specifically it's mapping to
826 /// the last redeclaration we've checked.
827 ///
828 /// Shall not contain declarations that have comments attached to any
829 /// redeclaration in their chain.
830 mutable llvm::DenseMap<const Decl *, const Decl *> CommentlessRedeclChains;
831
832 /// Mapping from declarations to parsed comments attached to any
833 /// redeclaration.
834 mutable llvm::DenseMap<const Decl *, comments::FullComment *> ParsedComments;
835
836 /// Attaches \p Comment to \p OriginalD and to its redeclaration chain
837 /// and removes the redeclaration chain from the set of commentless chains.
838 ///
839 /// Don't do anything if a comment has already been attached to \p OriginalD
840 /// or its redeclaration chain.
841 void cacheRawCommentForDecl(const Decl &OriginalD,
842 const RawComment &Comment) const;
843
844 /// \returns searches \p CommentsInFile for doc comment for \p D.
845 ///
846 /// \p RepresentativeLocForDecl is used as a location for searching doc
847 /// comments. \p CommentsInFile is a mapping offset -> comment of files in the
848 /// same file where \p RepresentativeLocForDecl is.
849 RawComment *getRawCommentForDeclNoCacheImpl(
850 const Decl *D, const SourceLocation RepresentativeLocForDecl,
851 const std::map<unsigned, RawComment *> &CommentsInFile) const;
852
853 /// Return the documentation comment attached to a given declaration,
854 /// without looking into cache.
855 RawComment *getRawCommentForDeclNoCache(const Decl *D) const;
856
857public:
858 void addComment(const RawComment &RC);
859
860 /// Return the documentation comment attached to a given declaration.
861 /// Returns nullptr if no comment is attached.
862 ///
863 /// \param OriginalDecl if not nullptr, is set to declaration AST node that
864 /// had the comment, if the comment we found comes from a redeclaration.
865 const RawComment *
866 getRawCommentForAnyRedecl(const Decl *D,
867 const Decl **OriginalDecl = nullptr) const;
868
869 /// Searches existing comments for doc comments that should be attached to \p
870 /// Decls. If any doc comment is found, it is parsed.
871 ///
872 /// Requirement: All \p Decls are in the same file.
873 ///
874 /// If the last comment in the file is already attached we assume
875 /// there are not comments left to be attached to \p Decls.
876 void attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls,
877 const Preprocessor *PP);
878
879 /// Return parsed documentation comment attached to a given declaration.
880 /// Returns nullptr if no comment is attached.
881 ///
882 /// \param PP the Preprocessor used with this TU. Could be nullptr if
883 /// preprocessor is not available.
884 comments::FullComment *getCommentForDecl(const Decl *D,
885 const Preprocessor *PP) const;
886
887 /// Return parsed documentation comment attached to a given declaration.
888 /// Returns nullptr if no comment is attached. Does not look at any
889 /// redeclarations of the declaration.
890 comments::FullComment *getLocalCommentForDeclUncached(const Decl *D) const;
891
892 comments::FullComment *cloneFullComment(comments::FullComment *FC,
893 const Decl *D) const;
894
895private:
896 mutable comments::CommandTraits CommentCommandTraits;
897
898 /// Iterator that visits import declarations.
899 class import_iterator {
900 ImportDecl *Import = nullptr;
901
902 public:
903 using value_type = ImportDecl *;
904 using reference = ImportDecl *;
905 using pointer = ImportDecl *;
906 using difference_type = int;
907 using iterator_category = std::forward_iterator_tag;
908
909 import_iterator() = default;
910 explicit import_iterator(ImportDecl *Import) : Import(Import) {}
911
912 reference operator*() const { return Import; }
913 pointer operator->() const { return Import; }
914
915 import_iterator &operator++() {
916 Import = ASTContext::getNextLocalImport(Import);
917 return *this;
918 }
919
920 import_iterator operator++(int) {
921 import_iterator Other(*this);
922 ++(*this);
923 return Other;
924 }
925
926 friend bool operator==(import_iterator X, import_iterator Y) {
927 return X.Import == Y.Import;
928 }
929
930 friend bool operator!=(import_iterator X, import_iterator Y) {
931 return X.Import != Y.Import;
932 }
933 };
934
935public:
936 comments::CommandTraits &getCommentCommandTraits() const {
937 return CommentCommandTraits;
938 }
939
940 /// Retrieve the attributes for the given declaration.
941 AttrVec& getDeclAttrs(const Decl *D);
942
943 /// Erase the attributes corresponding to the given declaration.
944 void eraseDeclAttrs(const Decl *D);
945
946 /// If this variable is an instantiated static data member of a
947 /// class template specialization, returns the templated static data member
948 /// from which it was instantiated.
949 // FIXME: Remove ?
950 MemberSpecializationInfo *getInstantiatedFromStaticDataMember(
951 const VarDecl *Var);
952
953 /// Note that the static data member \p Inst is an instantiation of
954 /// the static data member template \p Tmpl of a class template.
955 void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
956 TemplateSpecializationKind TSK,
957 SourceLocation PointOfInstantiation = SourceLocation());
958
959 TemplateOrSpecializationInfo
960 getTemplateOrSpecializationInfo(const VarDecl *Var);
961
962 void setTemplateOrSpecializationInfo(VarDecl *Inst,
963 TemplateOrSpecializationInfo TSI);
964
965 /// If the given using decl \p Inst is an instantiation of
966 /// another (possibly unresolved) using decl, return it.
967 NamedDecl *getInstantiatedFromUsingDecl(NamedDecl *Inst);
968
969 /// Remember that the using decl \p Inst is an instantiation
970 /// of the using decl \p Pattern of a class template.
971 void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern);
972
973 /// If the given using-enum decl \p Inst is an instantiation of
974 /// another using-enum decl, return it.
975 UsingEnumDecl *getInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst);
976
977 /// Remember that the using enum decl \p Inst is an instantiation
978 /// of the using enum decl \p Pattern of a class template.
979 void setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst,
980 UsingEnumDecl *Pattern);
981
982 UsingShadowDecl *getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst);
983 void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
984 UsingShadowDecl *Pattern);
985
986 FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field);
987
988 void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl);
989
990 // Access to the set of methods overridden by the given C++ method.
991 using overridden_cxx_method_iterator = CXXMethodVector::const_iterator;
992 overridden_cxx_method_iterator
993 overridden_methods_begin(const CXXMethodDecl *Method) const;
994
995 overridden_cxx_method_iterator
996 overridden_methods_end(const CXXMethodDecl *Method) const;
997
998 unsigned overridden_methods_size(const CXXMethodDecl *Method) const;
999
1000 using overridden_method_range =
1001 llvm::iterator_range<overridden_cxx_method_iterator>;
1002
1003 overridden_method_range overridden_methods(const CXXMethodDecl *Method) const;
1004
1005 /// Note that the given C++ \p Method overrides the given \p
1006 /// Overridden method.
1007 void addOverriddenMethod(const CXXMethodDecl *Method,
1008 const CXXMethodDecl *Overridden);
1009
1010 /// Return C++ or ObjC overridden methods for the given \p Method.
1011 ///
1012 /// An ObjC method is considered to override any method in the class's
1013 /// base classes, its protocols, or its categories' protocols, that has
1014 /// the same selector and is of the same kind (class or instance).
1015 /// A method in an implementation is not considered as overriding the same
1016 /// method in the interface or its categories.
1017 void getOverriddenMethods(
1018 const NamedDecl *Method,
1019 SmallVectorImpl<const NamedDecl *> &Overridden) const;
1020
1021 /// Notify the AST context that a new import declaration has been
1022 /// parsed or implicitly created within this translation unit.
1023 void addedLocalImportDecl(ImportDecl *Import);
1024
1025 static ImportDecl *getNextLocalImport(ImportDecl *Import) {
1026 return Import->getNextLocalImport();
1027 }
1028
1029 using import_range = llvm::iterator_range<import_iterator>;
1030
1031 import_range local_imports() const {
1032 return import_range(import_iterator(FirstLocalImport), import_iterator());
1033 }
1034
1035 Decl *getPrimaryMergedDecl(Decl *D) {
1036 Decl *Result = MergedDecls.lookup(Val: D);
1037 return Result ? Result : D;
1038 }
1039 void setPrimaryMergedDecl(Decl *D, Decl *Primary) {
1040 MergedDecls[D] = Primary;
1041 }
1042
1043 /// Note that the definition \p ND has been merged into module \p M,
1044 /// and should be visible whenever \p M is visible.
1045 void mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
1046 bool NotifyListeners = true);
1047
1048 /// Clean up the merged definition list. Call this if you might have
1049 /// added duplicates into the list.
1050 void deduplicateMergedDefinitonsFor(NamedDecl *ND);
1051
1052 /// Get the additional modules in which the definition \p Def has
1053 /// been merged.
1054 ArrayRef<Module*> getModulesWithMergedDefinition(const NamedDecl *Def);
1055
1056 /// Add a declaration to the list of declarations that are initialized
1057 /// for a module. This will typically be a global variable (with internal
1058 /// linkage) that runs module initializers, such as the iostream initializer,
1059 /// or an ImportDecl nominating another module that has initializers.
1060 void addModuleInitializer(Module *M, Decl *Init);
1061
1062 void addLazyModuleInitializers(Module *M, ArrayRef<Decl::DeclID> IDs);
1063
1064 /// Get the initializations to perform when importing a module, if any.
1065 ArrayRef<Decl*> getModuleInitializers(Module *M);
1066
1067 /// Set the (C++20) module we are building.
1068 void setCurrentNamedModule(Module *M);
1069
1070 /// Get module under construction, nullptr if this is not a C++20 module.
1071 Module *getCurrentNamedModule() const { return CurrentCXXNamedModule; }
1072
1073 TranslationUnitDecl *getTranslationUnitDecl() const {
1074 return TUDecl->getMostRecentDecl();
1075 }
1076 void addTranslationUnitDecl() {
1077 assert(!TUDecl || TUKind == TU_Incremental);
1078 TranslationUnitDecl *NewTUDecl = TranslationUnitDecl::Create(C&: *this);
1079 if (TraversalScope.empty() || TraversalScope.back() == TUDecl)
1080 TraversalScope = {NewTUDecl};
1081 if (TUDecl)
1082 NewTUDecl->setPreviousDecl(TUDecl);
1083 TUDecl = NewTUDecl;
1084 }
1085
1086 ExternCContextDecl *getExternCContextDecl() const;
1087 BuiltinTemplateDecl *getMakeIntegerSeqDecl() const;
1088 BuiltinTemplateDecl *getTypePackElementDecl() const;
1089
1090 // Builtin Types.
1091 CanQualType VoidTy;
1092 CanQualType BoolTy;
1093 CanQualType CharTy;
1094 CanQualType WCharTy; // [C++ 3.9.1p5].
1095 CanQualType WideCharTy; // Same as WCharTy in C++, integer type in C99.
1096 CanQualType WIntTy; // [C99 7.24.1], integer type unchanged by default promotions.
1097 CanQualType Char8Ty; // [C++20 proposal]
1098 CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99.
1099 CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99.
1100 CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty;
1101 CanQualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy;
1102 CanQualType UnsignedLongLongTy, UnsignedInt128Ty;
1103 CanQualType FloatTy, DoubleTy, LongDoubleTy, Float128Ty, Ibm128Ty;
1104 CanQualType ShortAccumTy, AccumTy,
1105 LongAccumTy; // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1106 CanQualType UnsignedShortAccumTy, UnsignedAccumTy, UnsignedLongAccumTy;
1107 CanQualType ShortFractTy, FractTy, LongFractTy;
1108 CanQualType UnsignedShortFractTy, UnsignedFractTy, UnsignedLongFractTy;
1109 CanQualType SatShortAccumTy, SatAccumTy, SatLongAccumTy;
1110 CanQualType SatUnsignedShortAccumTy, SatUnsignedAccumTy,
1111 SatUnsignedLongAccumTy;
1112 CanQualType SatShortFractTy, SatFractTy, SatLongFractTy;
1113 CanQualType SatUnsignedShortFractTy, SatUnsignedFractTy,
1114 SatUnsignedLongFractTy;
1115 CanQualType HalfTy; // [OpenCL 6.1.1.1], ARM NEON
1116 CanQualType BFloat16Ty;
1117 CanQualType Float16Ty; // C11 extension ISO/IEC TS 18661-3
1118 CanQualType VoidPtrTy, NullPtrTy;
1119 CanQualType DependentTy, OverloadTy, BoundMemberTy, UnknownAnyTy;
1120 CanQualType BuiltinFnTy;
1121 CanQualType PseudoObjectTy, ARCUnbridgedCastTy;
1122 CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy;
1123 CanQualType ObjCBuiltinBoolTy;
1124#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1125 CanQualType SingletonId;
1126#include "clang/Basic/OpenCLImageTypes.def"
1127 CanQualType OCLSamplerTy, OCLEventTy, OCLClkEventTy;
1128 CanQualType OCLQueueTy, OCLReserveIDTy;
1129 CanQualType IncompleteMatrixIdxTy;
1130 CanQualType OMPArraySectionTy, OMPArrayShapingTy, OMPIteratorTy;
1131#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1132 CanQualType Id##Ty;
1133#include "clang/Basic/OpenCLExtensionTypes.def"
1134#define SVE_TYPE(Name, Id, SingletonId) \
1135 CanQualType SingletonId;
1136#include "clang/Basic/AArch64SVEACLETypes.def"
1137#define PPC_VECTOR_TYPE(Name, Id, Size) \
1138 CanQualType Id##Ty;
1139#include "clang/Basic/PPCTypes.def"
1140#define RVV_TYPE(Name, Id, SingletonId) \
1141 CanQualType SingletonId;
1142#include "clang/Basic/RISCVVTypes.def"
1143#define WASM_TYPE(Name, Id, SingletonId) CanQualType SingletonId;
1144#include "clang/Basic/WebAssemblyReferenceTypes.def"
1145
1146 // Types for deductions in C++0x [stmt.ranged]'s desugaring. Built on demand.
1147 mutable QualType AutoDeductTy; // Deduction against 'auto'.
1148 mutable QualType AutoRRefDeductTy; // Deduction against 'auto &&'.
1149
1150 // Decl used to help define __builtin_va_list for some targets.
1151 // The decl is built when constructing 'BuiltinVaListDecl'.
1152 mutable Decl *VaListTagDecl = nullptr;
1153
1154 // Implicitly-declared type 'struct _GUID'.
1155 mutable TagDecl *MSGuidTagDecl = nullptr;
1156
1157 /// Keep track of CUDA/HIP device-side variables ODR-used by host code.
1158 /// This does not include extern shared variables used by device host
1159 /// functions as addresses of shared variables are per warp, therefore
1160 /// cannot be accessed by host code.
1161 llvm::DenseSet<const VarDecl *> CUDADeviceVarODRUsedByHost;
1162
1163 /// Keep track of CUDA/HIP external kernels or device variables ODR-used by
1164 /// host code.
1165 llvm::DenseSet<const ValueDecl *> CUDAExternalDeviceDeclODRUsedByHost;
1166
1167 /// Keep track of CUDA/HIP implicit host device functions used on device side
1168 /// in device compilation.
1169 llvm::DenseSet<const FunctionDecl *> CUDAImplicitHostDeviceFunUsedByDevice;
1170
1171 ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents,
1172 SelectorTable &sels, Builtin::Context &builtins,
1173 TranslationUnitKind TUKind);
1174 ASTContext(const ASTContext &) = delete;
1175 ASTContext &operator=(const ASTContext &) = delete;
1176 ~ASTContext();
1177
1178 /// Attach an external AST source to the AST context.
1179 ///
1180 /// The external AST source provides the ability to load parts of
1181 /// the abstract syntax tree as needed from some external storage,
1182 /// e.g., a precompiled header.
1183 void setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source);
1184
1185 /// Retrieve a pointer to the external AST source associated
1186 /// with this AST context, if any.
1187 ExternalASTSource *getExternalSource() const {
1188 return ExternalSource.get();
1189 }
1190
1191 /// Attach an AST mutation listener to the AST context.
1192 ///
1193 /// The AST mutation listener provides the ability to track modifications to
1194 /// the abstract syntax tree entities committed after they were initially
1195 /// created.
1196 void setASTMutationListener(ASTMutationListener *Listener) {
1197 this->Listener = Listener;
1198 }
1199
1200 /// Retrieve a pointer to the AST mutation listener associated
1201 /// with this AST context, if any.
1202 ASTMutationListener *getASTMutationListener() const { return Listener; }
1203
1204 void PrintStats() const;
1205 const SmallVectorImpl<Type *>& getTypes() const { return Types; }
1206
1207 BuiltinTemplateDecl *buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1208 const IdentifierInfo *II) const;
1209
1210 /// Create a new implicit TU-level CXXRecordDecl or RecordDecl
1211 /// declaration.
1212 RecordDecl *buildImplicitRecord(
1213 StringRef Name,
1214 RecordDecl::TagKind TK = RecordDecl::TagKind::Struct) const;
1215
1216 /// Create a new implicit TU-level typedef declaration.
1217 TypedefDecl *buildImplicitTypedef(QualType T, StringRef Name) const;
1218
1219 /// Retrieve the declaration for the 128-bit signed integer type.
1220 TypedefDecl *getInt128Decl() const;
1221
1222 /// Retrieve the declaration for the 128-bit unsigned integer type.
1223 TypedefDecl *getUInt128Decl() const;
1224
1225 //===--------------------------------------------------------------------===//
1226 // Type Constructors
1227 //===--------------------------------------------------------------------===//
1228
1229private:
1230 /// Return a type with extended qualifiers.
1231 QualType getExtQualType(const Type *Base, Qualifiers Quals) const;
1232
1233 QualType getTypeDeclTypeSlow(const TypeDecl *Decl) const;
1234
1235 QualType getPipeType(QualType T, bool ReadOnly) const;
1236
1237public:
1238 /// Return the uniqued reference to the type for an address space
1239 /// qualified type with the specified type and address space.
1240 ///
1241 /// The resulting type has a union of the qualifiers from T and the address
1242 /// space. If T already has an address space specifier, it is silently
1243 /// replaced.
1244 QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const;
1245
1246 /// Remove any existing address space on the type and returns the type
1247 /// with qualifiers intact (or that's the idea anyway)
1248 ///
1249 /// The return type should be T with all prior qualifiers minus the address
1250 /// space.
1251 QualType removeAddrSpaceQualType(QualType T) const;
1252
1253 /// Apply Objective-C protocol qualifiers to the given type.
1254 /// \param allowOnPointerType specifies if we can apply protocol
1255 /// qualifiers on ObjCObjectPointerType. It can be set to true when
1256 /// constructing the canonical type of a Objective-C type parameter.
1257 QualType applyObjCProtocolQualifiers(QualType type,
1258 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
1259 bool allowOnPointerType = false) const;
1260
1261 /// Return the uniqued reference to the type for an Objective-C
1262 /// gc-qualified type.
1263 ///
1264 /// The resulting type has a union of the qualifiers from T and the gc
1265 /// attribute.
1266 QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const;
1267
1268 /// Remove the existing address space on the type if it is a pointer size
1269 /// address space and return the type with qualifiers intact.
1270 QualType removePtrSizeAddrSpace(QualType T) const;
1271
1272 /// Return the uniqued reference to the type for a \c restrict
1273 /// qualified type.
1274 ///
1275 /// The resulting type has a union of the qualifiers from \p T and
1276 /// \c restrict.
1277 QualType getRestrictType(QualType T) const {
1278 return T.withFastQualifiers(TQs: Qualifiers::Restrict);
1279 }
1280
1281 /// Return the uniqued reference to the type for a \c volatile
1282 /// qualified type.
1283 ///
1284 /// The resulting type has a union of the qualifiers from \p T and
1285 /// \c volatile.
1286 QualType getVolatileType(QualType T) const {
1287 return T.withFastQualifiers(TQs: Qualifiers::Volatile);
1288 }
1289
1290 /// Return the uniqued reference to the type for a \c const
1291 /// qualified type.
1292 ///
1293 /// The resulting type has a union of the qualifiers from \p T and \c const.
1294 ///
1295 /// It can be reasonably expected that this will always be equivalent to
1296 /// calling T.withConst().
1297 QualType getConstType(QualType T) const { return T.withConst(); }
1298
1299 /// Change the ExtInfo on a function type.
1300 const FunctionType *adjustFunctionType(const FunctionType *Fn,
1301 FunctionType::ExtInfo EInfo);
1302
1303 /// Adjust the given function result type.
1304 CanQualType getCanonicalFunctionResultType(QualType ResultType) const;
1305
1306 /// Change the result type of a function type once it is deduced.
1307 void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType);
1308
1309 /// Get a function type and produce the equivalent function type with the
1310 /// specified exception specification. Type sugar that can be present on a
1311 /// declaration of a function with an exception specification is permitted
1312 /// and preserved. Other type sugar (for instance, typedefs) is not.
1313 QualType getFunctionTypeWithExceptionSpec(
1314 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const;
1315
1316 /// Determine whether two function types are the same, ignoring
1317 /// exception specifications in cases where they're part of the type.
1318 bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U) const;
1319
1320 /// Change the exception specification on a function once it is
1321 /// delay-parsed, instantiated, or computed.
1322 void adjustExceptionSpec(FunctionDecl *FD,
1323 const FunctionProtoType::ExceptionSpecInfo &ESI,
1324 bool AsWritten = false);
1325
1326 /// Get a function type and produce the equivalent function type where
1327 /// pointer size address spaces in the return type and parameter tyeps are
1328 /// replaced with the default address space.
1329 QualType getFunctionTypeWithoutPtrSizes(QualType T);
1330
1331 /// Determine whether two function types are the same, ignoring pointer sizes
1332 /// in the return type and parameter types.
1333 bool hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U);
1334
1335 /// Return the uniqued reference to the type for a complex
1336 /// number with the specified element type.
1337 QualType getComplexType(QualType T) const;
1338 CanQualType getComplexType(CanQualType T) const {
1339 return CanQualType::CreateUnsafe(Other: getComplexType(T: (QualType) T));
1340 }
1341
1342 /// Return the uniqued reference to the type for a pointer to
1343 /// the specified type.
1344 QualType getPointerType(QualType T) const;
1345 CanQualType getPointerType(CanQualType T) const {
1346 return CanQualType::CreateUnsafe(Other: getPointerType(T: (QualType) T));
1347 }
1348
1349 QualType
1350 getCountAttributedType(QualType T, Expr *CountExpr, bool CountInBytes,
1351 bool OrNull,
1352 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const;
1353
1354 /// Return the uniqued reference to a type adjusted from the original
1355 /// type to a new type.
1356 QualType getAdjustedType(QualType Orig, QualType New) const;
1357 CanQualType getAdjustedType(CanQualType Orig, CanQualType New) const {
1358 return CanQualType::CreateUnsafe(
1359 Other: getAdjustedType(Orig: (QualType)Orig, New: (QualType)New));
1360 }
1361
1362 /// Return the uniqued reference to the decayed version of the given
1363 /// type. Can only be called on array and function types which decay to
1364 /// pointer types.
1365 QualType getDecayedType(QualType T) const;
1366 CanQualType getDecayedType(CanQualType T) const {
1367 return CanQualType::CreateUnsafe(Other: getDecayedType(T: (QualType) T));
1368 }
1369 /// Return the uniqued reference to a specified decay from the original
1370 /// type to the decayed type.
1371 QualType getDecayedType(QualType Orig, QualType Decayed) const;
1372
1373 /// Return the uniqued reference to a specified array parameter type from the
1374 /// original array type.
1375 QualType getArrayParameterType(QualType Ty) const;
1376
1377 /// Return the uniqued reference to the atomic type for the specified
1378 /// type.
1379 QualType getAtomicType(QualType T) const;
1380
1381 /// Return the uniqued reference to the type for a block of the
1382 /// specified type.
1383 QualType getBlockPointerType(QualType T) const;
1384
1385 /// Gets the struct used to keep track of the descriptor for pointer to
1386 /// blocks.
1387 QualType getBlockDescriptorType() const;
1388
1389 /// Return a read_only pipe type for the specified type.
1390 QualType getReadPipeType(QualType T) const;
1391
1392 /// Return a write_only pipe type for the specified type.
1393 QualType getWritePipeType(QualType T) const;
1394
1395 /// Return a bit-precise integer type with the specified signedness and bit
1396 /// count.
1397 QualType getBitIntType(bool Unsigned, unsigned NumBits) const;
1398
1399 /// Return a dependent bit-precise integer type with the specified signedness
1400 /// and bit count.
1401 QualType getDependentBitIntType(bool Unsigned, Expr *BitsExpr) const;
1402
1403 /// Gets the struct used to keep track of the extended descriptor for
1404 /// pointer to blocks.
1405 QualType getBlockDescriptorExtendedType() const;
1406
1407 /// Map an AST Type to an OpenCLTypeKind enum value.
1408 OpenCLTypeKind getOpenCLTypeKind(const Type *T) const;
1409
1410 /// Get address space for OpenCL type.
1411 LangAS getOpenCLTypeAddrSpace(const Type *T) const;
1412
1413 /// Returns default address space based on OpenCL version and enabled features
1414 inline LangAS getDefaultOpenCLPointeeAddrSpace() {
1415 return LangOpts.OpenCLGenericAddressSpace ? LangAS::opencl_generic
1416 : LangAS::opencl_private;
1417 }
1418
1419 void setcudaConfigureCallDecl(FunctionDecl *FD) {
1420 cudaConfigureCallDecl = FD;
1421 }
1422
1423 FunctionDecl *getcudaConfigureCallDecl() {
1424 return cudaConfigureCallDecl;
1425 }
1426
1427 /// Returns true iff we need copy/dispose helpers for the given type.
1428 bool BlockRequiresCopying(QualType Ty, const VarDecl *D);
1429
1430 /// Returns true, if given type has a known lifetime. HasByrefExtendedLayout
1431 /// is set to false in this case. If HasByrefExtendedLayout returns true,
1432 /// byref variable has extended lifetime.
1433 bool getByrefLifetime(QualType Ty,
1434 Qualifiers::ObjCLifetime &Lifetime,
1435 bool &HasByrefExtendedLayout) const;
1436
1437 /// Return the uniqued reference to the type for an lvalue reference
1438 /// to the specified type.
1439 QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true)
1440 const;
1441
1442 /// Return the uniqued reference to the type for an rvalue reference
1443 /// to the specified type.
1444 QualType getRValueReferenceType(QualType T) const;
1445
1446 /// Return the uniqued reference to the type for a member pointer to
1447 /// the specified type in the specified class.
1448 ///
1449 /// The class \p Cls is a \c Type because it could be a dependent name.
1450 QualType getMemberPointerType(QualType T, const Type *Cls) const;
1451
1452 /// Return a non-unique reference to the type for a variable array of
1453 /// the specified element type.
1454 QualType getVariableArrayType(QualType EltTy, Expr *NumElts,
1455 ArraySizeModifier ASM, unsigned IndexTypeQuals,
1456 SourceRange Brackets) const;
1457
1458 /// Return a non-unique reference to the type for a dependently-sized
1459 /// array of the specified element type.
1460 ///
1461 /// FIXME: We will need these to be uniqued, or at least comparable, at some
1462 /// point.
1463 QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
1464 ArraySizeModifier ASM,
1465 unsigned IndexTypeQuals,
1466 SourceRange Brackets) const;
1467
1468 /// Return a unique reference to the type for an incomplete array of
1469 /// the specified element type.
1470 QualType getIncompleteArrayType(QualType EltTy, ArraySizeModifier ASM,
1471 unsigned IndexTypeQuals) const;
1472
1473 /// Return the unique reference to the type for a constant array of
1474 /// the specified element type.
1475 QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize,
1476 const Expr *SizeExpr, ArraySizeModifier ASM,
1477 unsigned IndexTypeQuals) const;
1478
1479 /// Return a type for a constant array for a string literal of the
1480 /// specified element type and length.
1481 QualType getStringLiteralArrayType(QualType EltTy, unsigned Length) const;
1482
1483 /// Returns a vla type where known sizes are replaced with [*].
1484 QualType getVariableArrayDecayedType(QualType Ty) const;
1485
1486 // Convenience struct to return information about a builtin vector type.
1487 struct BuiltinVectorTypeInfo {
1488 QualType ElementType;
1489 llvm::ElementCount EC;
1490 unsigned NumVectors;
1491 BuiltinVectorTypeInfo(QualType ElementType, llvm::ElementCount EC,
1492 unsigned NumVectors)
1493 : ElementType(ElementType), EC(EC), NumVectors(NumVectors) {}
1494 };
1495
1496 /// Returns the element type, element count and number of vectors
1497 /// (in case of tuple) for a builtin vector type.
1498 BuiltinVectorTypeInfo
1499 getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const;
1500
1501 /// Return the unique reference to a scalable vector type of the specified
1502 /// element type and scalable number of elements.
1503 /// For RISC-V, number of fields is also provided when it fetching for
1504 /// tuple type.
1505 ///
1506 /// \pre \p EltTy must be a built-in type.
1507 QualType getScalableVectorType(QualType EltTy, unsigned NumElts,
1508 unsigned NumFields = 1) const;
1509
1510 /// Return a WebAssembly externref type.
1511 QualType getWebAssemblyExternrefType() const;
1512
1513 /// Return the unique reference to a vector type of the specified
1514 /// element type and size.
1515 ///
1516 /// \pre \p VectorType must be a built-in type.
1517 QualType getVectorType(QualType VectorType, unsigned NumElts,
1518 VectorKind VecKind) const;
1519 /// Return the unique reference to the type for a dependently sized vector of
1520 /// the specified element type.
1521 QualType getDependentVectorType(QualType VectorType, Expr *SizeExpr,
1522 SourceLocation AttrLoc,
1523 VectorKind VecKind) const;
1524
1525 /// Return the unique reference to an extended vector type
1526 /// of the specified element type and size.
1527 ///
1528 /// \pre \p VectorType must be a built-in type.
1529 QualType getExtVectorType(QualType VectorType, unsigned NumElts) const;
1530
1531 /// \pre Return a non-unique reference to the type for a dependently-sized
1532 /// vector of the specified element type.
1533 ///
1534 /// FIXME: We will need these to be uniqued, or at least comparable, at some
1535 /// point.
1536 QualType getDependentSizedExtVectorType(QualType VectorType,
1537 Expr *SizeExpr,
1538 SourceLocation AttrLoc) const;
1539
1540 /// Return the unique reference to the matrix type of the specified element
1541 /// type and size
1542 ///
1543 /// \pre \p ElementType must be a valid matrix element type (see
1544 /// MatrixType::isValidElementType).
1545 QualType getConstantMatrixType(QualType ElementType, unsigned NumRows,
1546 unsigned NumColumns) const;
1547
1548 /// Return the unique reference to the matrix type of the specified element
1549 /// type and size
1550 QualType getDependentSizedMatrixType(QualType ElementType, Expr *RowExpr,
1551 Expr *ColumnExpr,
1552 SourceLocation AttrLoc) const;
1553
1554 QualType getDependentAddressSpaceType(QualType PointeeType,
1555 Expr *AddrSpaceExpr,
1556 SourceLocation AttrLoc) const;
1557
1558 /// Return a K&R style C function type like 'int()'.
1559 QualType getFunctionNoProtoType(QualType ResultTy,
1560 const FunctionType::ExtInfo &Info) const;
1561
1562 QualType getFunctionNoProtoType(QualType ResultTy) const {
1563 return getFunctionNoProtoType(ResultTy, Info: FunctionType::ExtInfo());
1564 }
1565
1566 /// Return a normal function type with a typed argument list.
1567 QualType getFunctionType(QualType ResultTy, ArrayRef<QualType> Args,
1568 const FunctionProtoType::ExtProtoInfo &EPI) const {
1569 return getFunctionTypeInternal(ResultTy, Args, EPI, OnlyWantCanonical: false);
1570 }
1571
1572 QualType adjustStringLiteralBaseType(QualType StrLTy) const;
1573
1574private:
1575 /// Return a normal function type with a typed argument list.
1576 QualType getFunctionTypeInternal(QualType ResultTy, ArrayRef<QualType> Args,
1577 const FunctionProtoType::ExtProtoInfo &EPI,
1578 bool OnlyWantCanonical) const;
1579 QualType
1580 getAutoTypeInternal(QualType DeducedType, AutoTypeKeyword Keyword,
1581 bool IsDependent, bool IsPack = false,
1582 ConceptDecl *TypeConstraintConcept = nullptr,
1583 ArrayRef<TemplateArgument> TypeConstraintArgs = {},
1584 bool IsCanon = false) const;
1585
1586public:
1587 /// Return the unique reference to the type for the specified type
1588 /// declaration.
1589 QualType getTypeDeclType(const TypeDecl *Decl,
1590 const TypeDecl *PrevDecl = nullptr) const {
1591 assert(Decl && "Passed null for Decl param");
1592 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1593
1594 if (PrevDecl) {
1595 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
1596 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1597 return QualType(PrevDecl->TypeForDecl, 0);
1598 }
1599
1600 return getTypeDeclTypeSlow(Decl);
1601 }
1602
1603 QualType getUsingType(const UsingShadowDecl *Found,
1604 QualType Underlying) const;
1605
1606 /// Return the unique reference to the type for the specified
1607 /// typedef-name decl.
1608 QualType getTypedefType(const TypedefNameDecl *Decl,
1609 QualType Underlying = QualType()) const;
1610
1611 QualType getRecordType(const RecordDecl *Decl) const;
1612
1613 QualType getEnumType(const EnumDecl *Decl) const;
1614
1615 QualType
1616 getUnresolvedUsingType(const UnresolvedUsingTypenameDecl *Decl) const;
1617
1618 QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const;
1619
1620 QualType getAttributedType(attr::Kind attrKind, QualType modifiedType,
1621 QualType equivalentType) const;
1622
1623 QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
1624 QualType Wrapped);
1625
1626 QualType
1627 getSubstTemplateTypeParmType(QualType Replacement, Decl *AssociatedDecl,
1628 unsigned Index,
1629 std::optional<unsigned> PackIndex) const;
1630 QualType getSubstTemplateTypeParmPackType(Decl *AssociatedDecl,
1631 unsigned Index, bool Final,
1632 const TemplateArgument &ArgPack);
1633
1634 QualType
1635 getTemplateTypeParmType(unsigned Depth, unsigned Index,
1636 bool ParameterPack,
1637 TemplateTypeParmDecl *ParmDecl = nullptr) const;
1638
1639 QualType getTemplateSpecializationType(TemplateName T,
1640 ArrayRef<TemplateArgument> Args,
1641 QualType Canon = QualType()) const;
1642
1643 QualType
1644 getCanonicalTemplateSpecializationType(TemplateName T,
1645 ArrayRef<TemplateArgument> Args) const;
1646
1647 QualType getTemplateSpecializationType(TemplateName T,
1648 ArrayRef<TemplateArgumentLoc> Args,
1649 QualType Canon = QualType()) const;
1650
1651 TypeSourceInfo *
1652 getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc,
1653 const TemplateArgumentListInfo &Args,
1654 QualType Canon = QualType()) const;
1655
1656 QualType getParenType(QualType NamedType) const;
1657
1658 QualType getMacroQualifiedType(QualType UnderlyingTy,
1659 const IdentifierInfo *MacroII) const;
1660
1661 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1662 NestedNameSpecifier *NNS, QualType NamedType,
1663 TagDecl *OwnedTagDecl = nullptr) const;
1664 QualType getDependentNameType(ElaboratedTypeKeyword Keyword,
1665 NestedNameSpecifier *NNS,
1666 const IdentifierInfo *Name,
1667 QualType Canon = QualType()) const;
1668
1669 QualType getDependentTemplateSpecializationType(
1670 ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
1671 const IdentifierInfo *Name, ArrayRef<TemplateArgumentLoc> Args) const;
1672 QualType getDependentTemplateSpecializationType(
1673 ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
1674 const IdentifierInfo *Name, ArrayRef<TemplateArgument> Args) const;
1675
1676 TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl);
1677
1678 /// Get a template argument list with one argument per template parameter
1679 /// in a template parameter list, such as for the injected class name of
1680 /// a class template.
1681 void getInjectedTemplateArgs(const TemplateParameterList *Params,
1682 SmallVectorImpl<TemplateArgument> &Args);
1683
1684 /// Form a pack expansion type with the given pattern.
1685 /// \param NumExpansions The number of expansions for the pack, if known.
1686 /// \param ExpectPackInType If \c false, we should not expect \p Pattern to
1687 /// contain an unexpanded pack. This only makes sense if the pack
1688 /// expansion is used in a context where the arity is inferred from
1689 /// elsewhere, such as if the pattern contains a placeholder type or
1690 /// if this is the canonical type of another pack expansion type.
1691 QualType getPackExpansionType(QualType Pattern,
1692 std::optional<unsigned> NumExpansions,
1693 bool ExpectPackInType = true);
1694
1695 QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
1696 ObjCInterfaceDecl *PrevDecl = nullptr) const;
1697
1698 /// Legacy interface: cannot provide type arguments or __kindof.
1699 QualType getObjCObjectType(QualType Base,
1700 ObjCProtocolDecl * const *Protocols,
1701 unsigned NumProtocols) const;
1702
1703 QualType getObjCObjectType(QualType Base,
1704 ArrayRef<QualType> typeArgs,
1705 ArrayRef<ObjCProtocolDecl *> protocols,
1706 bool isKindOf) const;
1707
1708 QualType getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
1709 ArrayRef<ObjCProtocolDecl *> protocols) const;
1710 void adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig,
1711 ObjCTypeParamDecl *New) const;
1712
1713 bool ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *Decl);
1714
1715 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
1716 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
1717 /// of protocols.
1718 bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
1719 ObjCInterfaceDecl *IDecl);
1720
1721 /// Return a ObjCObjectPointerType type for the given ObjCObjectType.
1722 QualType getObjCObjectPointerType(QualType OIT) const;
1723
1724 /// C23 feature and GCC extension.
1725 QualType getTypeOfExprType(Expr *E, TypeOfKind Kind) const;
1726 QualType getTypeOfType(QualType QT, TypeOfKind Kind) const;
1727
1728 QualType getReferenceQualifiedType(const Expr *e) const;
1729
1730 /// C++11 decltype.
1731 QualType getDecltypeType(Expr *e, QualType UnderlyingType) const;
1732
1733 QualType getPackIndexingType(QualType Pattern, Expr *IndexExpr,
1734 bool FullySubstituted = false,
1735 ArrayRef<QualType> Expansions = {},
1736 int Index = -1) const;
1737
1738 /// Unary type transforms
1739 QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
1740 UnaryTransformType::UTTKind UKind) const;
1741
1742 /// C++11 deduced auto type.
1743 QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
1744 bool IsDependent, bool IsPack = false,
1745 ConceptDecl *TypeConstraintConcept = nullptr,
1746 ArrayRef<TemplateArgument> TypeConstraintArgs ={}) const;
1747
1748 /// C++11 deduction pattern for 'auto' type.
1749 QualType getAutoDeductType() const;
1750
1751 /// C++11 deduction pattern for 'auto &&' type.
1752 QualType getAutoRRefDeductType() const;
1753
1754 /// Remove any type constraints from a template parameter type, for
1755 /// equivalence comparison of template parameters.
1756 QualType getUnconstrainedType(QualType T) const;
1757
1758 /// C++17 deduced class template specialization type.
1759 QualType getDeducedTemplateSpecializationType(TemplateName Template,
1760 QualType DeducedType,
1761 bool IsDependent) const;
1762
1763 /// Return the unique reference to the type for the specified TagDecl
1764 /// (struct/union/class/enum) decl.
1765 QualType getTagDeclType(const TagDecl *Decl) const;
1766
1767 /// Return the unique type for "size_t" (C99 7.17), defined in
1768 /// <stddef.h>.
1769 ///
1770 /// The sizeof operator requires this (C99 6.5.3.4p4).
1771 CanQualType getSizeType() const;
1772
1773 /// Return the unique signed counterpart of
1774 /// the integer type corresponding to size_t.
1775 CanQualType getSignedSizeType() const;
1776
1777 /// Return the unique type for "intmax_t" (C99 7.18.1.5), defined in
1778 /// <stdint.h>.
1779 CanQualType getIntMaxType() const;
1780
1781 /// Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in
1782 /// <stdint.h>.
1783 CanQualType getUIntMaxType() const;
1784
1785 /// Return the unique wchar_t type available in C++ (and available as
1786 /// __wchar_t as a Microsoft extension).
1787 QualType getWCharType() const { return WCharTy; }
1788
1789 /// Return the type of wide characters. In C++, this returns the
1790 /// unique wchar_t type. In C99, this returns a type compatible with the type
1791 /// defined in <stddef.h> as defined by the target.
1792 QualType getWideCharType() const { return WideCharTy; }
1793
1794 /// Return the type of "signed wchar_t".
1795 ///
1796 /// Used when in C++, as a GCC extension.
1797 QualType getSignedWCharType() const;
1798
1799 /// Return the type of "unsigned wchar_t".
1800 ///
1801 /// Used when in C++, as a GCC extension.
1802 QualType getUnsignedWCharType() const;
1803
1804 /// In C99, this returns a type compatible with the type
1805 /// defined in <stddef.h> as defined by the target.
1806 QualType getWIntType() const { return WIntTy; }
1807
1808 /// Return a type compatible with "intptr_t" (C99 7.18.1.4),
1809 /// as defined by the target.
1810 QualType getIntPtrType() const;
1811
1812 /// Return a type compatible with "uintptr_t" (C99 7.18.1.4),
1813 /// as defined by the target.
1814 QualType getUIntPtrType() const;
1815
1816 /// Return the unique type for "ptrdiff_t" (C99 7.17) defined in
1817 /// <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1818 QualType getPointerDiffType() const;
1819
1820 /// Return the unique unsigned counterpart of "ptrdiff_t"
1821 /// integer type. The standard (C11 7.21.6.1p7) refers to this type
1822 /// in the definition of %tu format specifier.
1823 QualType getUnsignedPointerDiffType() const;
1824
1825 /// Return the unique type for "pid_t" defined in
1826 /// <sys/types.h>. We need this to compute the correct type for vfork().
1827 QualType getProcessIDType() const;
1828
1829 /// Return the C structure type used to represent constant CFStrings.
1830 QualType getCFConstantStringType() const;
1831
1832 /// Returns the C struct type for objc_super
1833 QualType getObjCSuperType() const;
1834 void setObjCSuperType(QualType ST) { ObjCSuperType = ST; }
1835
1836 /// Get the structure type used to representation CFStrings, or NULL
1837 /// if it hasn't yet been built.
1838 QualType getRawCFConstantStringType() const {
1839 if (CFConstantStringTypeDecl)
1840 return getTypedefType(CFConstantStringTypeDecl);
1841 return QualType();
1842 }
1843 void setCFConstantStringType(QualType T);
1844 TypedefDecl *getCFConstantStringDecl() const;
1845 RecordDecl *getCFConstantStringTagDecl() const;
1846
1847 // This setter/getter represents the ObjC type for an NSConstantString.
1848 void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl);
1849 QualType getObjCConstantStringInterface() const {
1850 return ObjCConstantStringType;
1851 }
1852
1853 QualType getObjCNSStringType() const {
1854 return ObjCNSStringType;
1855 }
1856
1857 void setObjCNSStringType(QualType T) {
1858 ObjCNSStringType = T;
1859 }
1860
1861 /// Retrieve the type that \c id has been defined to, which may be
1862 /// different from the built-in \c id if \c id has been typedef'd.
1863 QualType getObjCIdRedefinitionType() const {
1864 if (ObjCIdRedefinitionType.isNull())
1865 return getObjCIdType();
1866 return ObjCIdRedefinitionType;
1867 }
1868
1869 /// Set the user-written type that redefines \c id.
1870 void setObjCIdRedefinitionType(QualType RedefType) {
1871 ObjCIdRedefinitionType = RedefType;
1872 }
1873
1874 /// Retrieve the type that \c Class has been defined to, which may be
1875 /// different from the built-in \c Class if \c Class has been typedef'd.
1876 QualType getObjCClassRedefinitionType() const {
1877 if (ObjCClassRedefinitionType.isNull())
1878 return getObjCClassType();
1879 return ObjCClassRedefinitionType;
1880 }
1881
1882 /// Set the user-written type that redefines 'SEL'.
1883 void setObjCClassRedefinitionType(QualType RedefType) {
1884 ObjCClassRedefinitionType = RedefType;
1885 }
1886
1887 /// Retrieve the type that 'SEL' has been defined to, which may be
1888 /// different from the built-in 'SEL' if 'SEL' has been typedef'd.
1889 QualType getObjCSelRedefinitionType() const {
1890 if (ObjCSelRedefinitionType.isNull())
1891 return getObjCSelType();
1892 return ObjCSelRedefinitionType;
1893 }
1894
1895 /// Set the user-written type that redefines 'SEL'.
1896 void setObjCSelRedefinitionType(QualType RedefType) {
1897 ObjCSelRedefinitionType = RedefType;
1898 }
1899
1900 /// Retrieve the identifier 'NSObject'.
1901 IdentifierInfo *getNSObjectName() const {
1902 if (!NSObjectName) {
1903 NSObjectName = &Idents.get(Name: "NSObject");
1904 }
1905
1906 return NSObjectName;
1907 }
1908
1909 /// Retrieve the identifier 'NSCopying'.
1910 IdentifierInfo *getNSCopyingName() {
1911 if (!NSCopyingName) {
1912 NSCopyingName = &Idents.get(Name: "NSCopying");
1913 }
1914
1915 return NSCopyingName;
1916 }
1917
1918 CanQualType getNSUIntegerType() const;
1919
1920 CanQualType getNSIntegerType() const;
1921
1922 /// Retrieve the identifier 'bool'.
1923 IdentifierInfo *getBoolName() const {
1924 if (!BoolName)
1925 BoolName = &Idents.get(Name: "bool");
1926 return BoolName;
1927 }
1928
1929 IdentifierInfo *getMakeIntegerSeqName() const {
1930 if (!MakeIntegerSeqName)
1931 MakeIntegerSeqName = &Idents.get(Name: "__make_integer_seq");
1932 return MakeIntegerSeqName;
1933 }
1934
1935 IdentifierInfo *getTypePackElementName() const {
1936 if (!TypePackElementName)
1937 TypePackElementName = &Idents.get(Name: "__type_pack_element");
1938 return TypePackElementName;
1939 }
1940
1941 /// Retrieve the Objective-C "instancetype" type, if already known;
1942 /// otherwise, returns a NULL type;
1943 QualType getObjCInstanceType() {
1944 return getTypeDeclType(getObjCInstanceTypeDecl());
1945 }
1946
1947 /// Retrieve the typedef declaration corresponding to the Objective-C
1948 /// "instancetype" type.
1949 TypedefDecl *getObjCInstanceTypeDecl();
1950
1951 /// Set the type for the C FILE type.
1952 void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; }
1953
1954 /// Retrieve the C FILE type.
1955 QualType getFILEType() const {
1956 if (FILEDecl)
1957 return getTypeDeclType(Decl: FILEDecl);
1958 return QualType();
1959 }
1960
1961 /// Set the type for the C jmp_buf type.
1962 void setjmp_bufDecl(TypeDecl *jmp_bufDecl) {
1963 this->jmp_bufDecl = jmp_bufDecl;
1964 }
1965
1966 /// Retrieve the C jmp_buf type.
1967 QualType getjmp_bufType() const {
1968 if (jmp_bufDecl)
1969 return getTypeDeclType(Decl: jmp_bufDecl);
1970 return QualType();
1971 }
1972
1973 /// Set the type for the C sigjmp_buf type.
1974 void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) {
1975 this->sigjmp_bufDecl = sigjmp_bufDecl;
1976 }
1977
1978 /// Retrieve the C sigjmp_buf type.
1979 QualType getsigjmp_bufType() const {
1980 if (sigjmp_bufDecl)
1981 return getTypeDeclType(Decl: sigjmp_bufDecl);
1982 return QualType();
1983 }
1984
1985 /// Set the type for the C ucontext_t type.
1986 void setucontext_tDecl(TypeDecl *ucontext_tDecl) {
1987 this->ucontext_tDecl = ucontext_tDecl;
1988 }
1989
1990 /// Retrieve the C ucontext_t type.
1991 QualType getucontext_tType() const {
1992 if (ucontext_tDecl)
1993 return getTypeDeclType(Decl: ucontext_tDecl);
1994 return QualType();
1995 }
1996
1997 /// The result type of logical operations, '<', '>', '!=', etc.
1998 QualType getLogicalOperationType() const {
1999 return getLangOpts().CPlusPlus ? BoolTy : IntTy;
2000 }
2001
2002 /// Emit the Objective-CC type encoding for the given type \p T into
2003 /// \p S.
2004 ///
2005 /// If \p Field is specified then record field names are also encoded.
2006 void getObjCEncodingForType(QualType T, std::string &S,
2007 const FieldDecl *Field=nullptr,
2008 QualType *NotEncodedT=nullptr) const;
2009
2010 /// Emit the Objective-C property type encoding for the given
2011 /// type \p T into \p S.
2012 void getObjCEncodingForPropertyType(QualType T, std::string &S) const;
2013
2014 void getLegacyIntegralTypeEncoding(QualType &t) const;
2015
2016 /// Put the string version of the type qualifiers \p QT into \p S.
2017 void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
2018 std::string &S) const;
2019
2020 /// Emit the encoded type for the function \p Decl into \p S.
2021 ///
2022 /// This is in the same format as Objective-C method encodings.
2023 ///
2024 /// \returns true if an error occurred (e.g., because one of the parameter
2025 /// types is incomplete), false otherwise.
2026 std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const;
2027
2028 /// Emit the encoded type for the method declaration \p Decl into
2029 /// \p S.
2030 std::string getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
2031 bool Extended = false) const;
2032
2033 /// Return the encoded type for this block declaration.
2034 std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const;
2035
2036 /// getObjCEncodingForPropertyDecl - Return the encoded type for
2037 /// this method declaration. If non-NULL, Container must be either
2038 /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
2039 /// only be NULL when getting encodings for protocol properties.
2040 std::string getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
2041 const Decl *Container) const;
2042
2043 bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
2044 ObjCProtocolDecl *rProto) const;
2045
2046 ObjCPropertyImplDecl *getObjCPropertyImplDeclForPropertyDecl(
2047 const ObjCPropertyDecl *PD,
2048 const Decl *Container) const;
2049
2050 /// Return the size of type \p T for Objective-C encoding purpose,
2051 /// in characters.
2052 CharUnits getObjCEncodingTypeSize(QualType T) const;
2053
2054 /// Retrieve the typedef corresponding to the predefined \c id type
2055 /// in Objective-C.
2056 TypedefDecl *getObjCIdDecl() const;
2057
2058 /// Represents the Objective-CC \c id type.
2059 ///
2060 /// This is set up lazily, by Sema. \c id is always a (typedef for a)
2061 /// pointer type, a pointer to a struct.
2062 QualType getObjCIdType() const {
2063 return getTypeDeclType(getObjCIdDecl());
2064 }
2065
2066 /// Retrieve the typedef corresponding to the predefined 'SEL' type
2067 /// in Objective-C.
2068 TypedefDecl *getObjCSelDecl() const;
2069
2070 /// Retrieve the type that corresponds to the predefined Objective-C
2071 /// 'SEL' type.
2072 QualType getObjCSelType() const {
2073 return getTypeDeclType(getObjCSelDecl());
2074 }
2075
2076 /// Retrieve the typedef declaration corresponding to the predefined
2077 /// Objective-C 'Class' type.
2078 TypedefDecl *getObjCClassDecl() const;
2079
2080 /// Represents the Objective-C \c Class type.
2081 ///
2082 /// This is set up lazily, by Sema. \c Class is always a (typedef for a)
2083 /// pointer type, a pointer to a struct.
2084 QualType getObjCClassType() const {
2085 return getTypeDeclType(getObjCClassDecl());
2086 }
2087
2088 /// Retrieve the Objective-C class declaration corresponding to
2089 /// the predefined \c Protocol class.
2090 ObjCInterfaceDecl *getObjCProtocolDecl() const;
2091
2092 /// Retrieve declaration of 'BOOL' typedef
2093 TypedefDecl *getBOOLDecl() const {
2094 return BOOLDecl;
2095 }
2096
2097 /// Save declaration of 'BOOL' typedef
2098 void setBOOLDecl(TypedefDecl *TD) {
2099 BOOLDecl = TD;
2100 }
2101
2102 /// type of 'BOOL' type.
2103 QualType getBOOLType() const {
2104 return getTypeDeclType(getBOOLDecl());
2105 }
2106
2107 /// Retrieve the type of the Objective-C \c Protocol class.
2108 QualType getObjCProtoType() const {
2109 return getObjCInterfaceType(Decl: getObjCProtocolDecl());
2110 }
2111
2112 /// Retrieve the C type declaration corresponding to the predefined
2113 /// \c __builtin_va_list type.
2114 TypedefDecl *getBuiltinVaListDecl() const;
2115
2116 /// Retrieve the type of the \c __builtin_va_list type.
2117 QualType getBuiltinVaListType() const {
2118 return getTypeDeclType(getBuiltinVaListDecl());
2119 }
2120
2121 /// Retrieve the C type declaration corresponding to the predefined
2122 /// \c __va_list_tag type used to help define the \c __builtin_va_list type
2123 /// for some targets.
2124 Decl *getVaListTagDecl() const;
2125
2126 /// Retrieve the C type declaration corresponding to the predefined
2127 /// \c __builtin_ms_va_list type.
2128 TypedefDecl *getBuiltinMSVaListDecl() const;
2129
2130 /// Retrieve the type of the \c __builtin_ms_va_list type.
2131 QualType getBuiltinMSVaListType() const {
2132 return getTypeDeclType(getBuiltinMSVaListDecl());
2133 }
2134
2135 /// Retrieve the implicitly-predeclared 'struct _GUID' declaration.
2136 TagDecl *getMSGuidTagDecl() const { return MSGuidTagDecl; }
2137
2138 /// Retrieve the implicitly-predeclared 'struct _GUID' type.
2139 QualType getMSGuidType() const {
2140 assert(MSGuidTagDecl && "asked for GUID type but MS extensions disabled");
2141 return getTagDeclType(Decl: MSGuidTagDecl);
2142 }
2143
2144 /// Return whether a declaration to a builtin is allowed to be
2145 /// overloaded/redeclared.
2146 bool canBuiltinBeRedeclared(const FunctionDecl *) const;
2147
2148 /// Return a type with additional \c const, \c volatile, or
2149 /// \c restrict qualifiers.
2150 QualType getCVRQualifiedType(QualType T, unsigned CVR) const {
2151 return getQualifiedType(T, Qs: Qualifiers::fromCVRMask(CVR));
2152 }
2153
2154 /// Un-split a SplitQualType.
2155 QualType getQualifiedType(SplitQualType split) const {
2156 return getQualifiedType(T: split.Ty, Qs: split.Quals);
2157 }
2158
2159 /// Return a type with additional qualifiers.
2160 QualType getQualifiedType(QualType T, Qualifiers Qs) const {
2161 if (!Qs.hasNonFastQualifiers())
2162 return T.withFastQualifiers(TQs: Qs.getFastQualifiers());
2163 QualifierCollector Qc(Qs);
2164 const Type *Ptr = Qc.strip(type: T);
2165 return getExtQualType(Base: Ptr, Quals: Qc);
2166 }
2167
2168 /// Return a type with additional qualifiers.
2169 QualType getQualifiedType(const Type *T, Qualifiers Qs) const {
2170 if (!Qs.hasNonFastQualifiers())
2171 return QualType(T, Qs.getFastQualifiers());
2172 return getExtQualType(Base: T, Quals: Qs);
2173 }
2174
2175 /// Return a type with the given lifetime qualifier.
2176 ///
2177 /// \pre Neither type.ObjCLifetime() nor \p lifetime may be \c OCL_None.
2178 QualType getLifetimeQualifiedType(QualType type,
2179 Qualifiers::ObjCLifetime lifetime) {
2180 assert(type.getObjCLifetime() == Qualifiers::OCL_None);
2181 assert(lifetime != Qualifiers::OCL_None);
2182
2183 Qualifiers qs;
2184 qs.addObjCLifetime(type: lifetime);
2185 return getQualifiedType(T: type, Qs: qs);
2186 }
2187
2188 /// getUnqualifiedObjCPointerType - Returns version of
2189 /// Objective-C pointer type with lifetime qualifier removed.
2190 QualType getUnqualifiedObjCPointerType(QualType type) const {
2191 if (!type.getTypePtr()->isObjCObjectPointerType() ||
2192 !type.getQualifiers().hasObjCLifetime())
2193 return type;
2194 Qualifiers Qs = type.getQualifiers();
2195 Qs.removeObjCLifetime();
2196 return getQualifiedType(T: type.getUnqualifiedType(), Qs);
2197 }
2198
2199 unsigned char getFixedPointScale(QualType Ty) const;
2200 unsigned char getFixedPointIBits(QualType Ty) const;
2201 llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const;
2202 llvm::APFixedPoint getFixedPointMax(QualType Ty) const;
2203 llvm::APFixedPoint getFixedPointMin(QualType Ty) const;
2204
2205 DeclarationNameInfo getNameForTemplate(TemplateName Name,
2206 SourceLocation NameLoc) const;
2207
2208 TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin,
2209 UnresolvedSetIterator End) const;
2210 TemplateName getAssumedTemplateName(DeclarationName Name) const;
2211
2212 TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
2213 bool TemplateKeyword,
2214 TemplateName Template) const;
2215
2216 TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
2217 const IdentifierInfo *Name) const;
2218 TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
2219 OverloadedOperatorKind Operator) const;
2220 TemplateName
2221 getSubstTemplateTemplateParm(TemplateName replacement, Decl *AssociatedDecl,
2222 unsigned Index,
2223 std::optional<unsigned> PackIndex) const;
2224 TemplateName getSubstTemplateTemplateParmPack(const TemplateArgument &ArgPack,
2225 Decl *AssociatedDecl,
2226 unsigned Index,
2227 bool Final) const;
2228
2229 enum GetBuiltinTypeError {
2230 /// No error
2231 GE_None,
2232
2233 /// Missing a type
2234 GE_Missing_type,
2235
2236 /// Missing a type from <stdio.h>
2237 GE_Missing_stdio,
2238
2239 /// Missing a type from <setjmp.h>
2240 GE_Missing_setjmp,
2241
2242 /// Missing a type from <ucontext.h>
2243 GE_Missing_ucontext
2244 };
2245
2246 QualType DecodeTypeStr(const char *&Str, const ASTContext &Context,
2247 ASTContext::GetBuiltinTypeError &Error,
2248 bool &RequireICE, bool AllowTypeModifiers) const;
2249
2250 /// Return the type for the specified builtin.
2251 ///
2252 /// If \p IntegerConstantArgs is non-null, it is filled in with a bitmask of
2253 /// arguments to the builtin that are required to be integer constant
2254 /// expressions.
2255 QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error,
2256 unsigned *IntegerConstantArgs = nullptr) const;
2257
2258 /// Types and expressions required to build C++2a three-way comparisons
2259 /// using operator<=>, including the values return by builtin <=> operators.
2260 ComparisonCategories CompCategories;
2261
2262private:
2263 CanQualType getFromTargetType(unsigned Type) const;
2264 TypeInfo getTypeInfoImpl(const Type *T) const;
2265
2266 //===--------------------------------------------------------------------===//
2267 // Type Predicates.
2268 //===--------------------------------------------------------------------===//
2269
2270public:
2271 /// Return one of the GCNone, Weak or Strong Objective-C garbage
2272 /// collection attributes.
2273 Qualifiers::GC getObjCGCAttrKind(QualType Ty) const;
2274
2275 /// Return true if the given vector types are of the same unqualified
2276 /// type or if they are equivalent to the same GCC vector type.
2277 ///
2278 /// \note This ignores whether they are target-specific (AltiVec or Neon)
2279 /// types.
2280 bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec);
2281
2282 /// Return true if the given types are an SVE builtin and a VectorType that
2283 /// is a fixed-length representation of the SVE builtin for a specific
2284 /// vector-length.
2285 bool areCompatibleSveTypes(QualType FirstType, QualType SecondType);
2286
2287 /// Return true if the given vector types are lax-compatible SVE vector types,
2288 /// false otherwise.
2289 bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType);
2290
2291 /// Return true if the given types are an RISC-V vector builtin type and a
2292 /// VectorType that is a fixed-length representation of the RISC-V vector
2293 /// builtin type for a specific vector-length.
2294 bool areCompatibleRVVTypes(QualType FirstType, QualType SecondType);
2295
2296 /// Return true if the given vector types are lax-compatible RISC-V vector
2297 /// types as defined by -flax-vector-conversions=, which permits implicit
2298 /// conversions between vectors with different number of elements and/or
2299 /// incompatible element types, false otherwise.
2300 bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType);
2301
2302 /// Return true if the type has been explicitly qualified with ObjC ownership.
2303 /// A type may be implicitly qualified with ownership under ObjC ARC, and in
2304 /// some cases the compiler treats these differently.
2305 bool hasDirectOwnershipQualifier(QualType Ty) const;
2306
2307 /// Return true if this is an \c NSObject object with its \c NSObject
2308 /// attribute set.
2309 static bool isObjCNSObjectType(QualType Ty) {
2310 return Ty->isObjCNSObjectType();
2311 }
2312
2313 //===--------------------------------------------------------------------===//
2314 // Type Sizing and Analysis
2315 //===--------------------------------------------------------------------===//
2316
2317 /// Return the APFloat 'semantics' for the specified scalar floating
2318 /// point type.
2319 const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
2320
2321 /// Get the size and alignment of the specified complete type in bits.
2322 TypeInfo getTypeInfo(const Type *T) const;
2323 TypeInfo getTypeInfo(QualType T) const { return getTypeInfo(T: T.getTypePtr()); }
2324
2325 /// Get default simd alignment of the specified complete type in bits.
2326 unsigned getOpenMPDefaultSimdAlign(QualType T) const;
2327
2328 /// Return the size of the specified (complete) type \p T, in bits.
2329 uint64_t getTypeSize(QualType T) const { return getTypeInfo(T).Width; }
2330 uint64_t getTypeSize(const Type *T) const { return getTypeInfo(T).Width; }
2331
2332 /// Return the size of the character type, in bits.
2333 uint64_t getCharWidth() const {
2334 return getTypeSize(CharTy);
2335 }
2336
2337 /// Convert a size in bits to a size in characters.
2338 CharUnits toCharUnitsFromBits(int64_t BitSize) const;
2339
2340 /// Convert a size in characters to a size in bits.
2341 int64_t toBits(CharUnits CharSize) const;
2342
2343 /// Return the size of the specified (complete) type \p T, in
2344 /// characters.
2345 CharUnits getTypeSizeInChars(QualType T) const;
2346 CharUnits getTypeSizeInChars(const Type *T) const;
2347
2348 std::optional<CharUnits> getTypeSizeInCharsIfKnown(QualType Ty) const {
2349 if (Ty->isIncompleteType() || Ty->isDependentType())
2350 return std::nullopt;
2351 return getTypeSizeInChars(T: Ty);
2352 }
2353
2354 std::optional<CharUnits> getTypeSizeInCharsIfKnown(const Type *Ty) const {
2355 return getTypeSizeInCharsIfKnown(Ty: QualType(Ty, 0));
2356 }
2357
2358 /// Return the ABI-specified alignment of a (complete) type \p T, in
2359 /// bits.
2360 unsigned getTypeAlign(QualType T) const { return getTypeInfo(T).Align; }
2361 unsigned getTypeAlign(const Type *T) const { return getTypeInfo(T).Align; }
2362
2363 /// Return the ABI-specified natural alignment of a (complete) type \p T,
2364 /// before alignment adjustments, in bits.
2365 ///
2366 /// This alignment is curently used only by ARM and AArch64 when passing
2367 /// arguments of a composite type.
2368 unsigned getTypeUnadjustedAlign(QualType T) const {
2369 return getTypeUnadjustedAlign(T: T.getTypePtr());
2370 }
2371 unsigned getTypeUnadjustedAlign(const Type *T) const;
2372
2373 /// Return the alignment of a type, in bits, or 0 if
2374 /// the type is incomplete and we cannot determine the alignment (for
2375 /// example, from alignment attributes). The returned alignment is the
2376 /// Preferred alignment if NeedsPreferredAlignment is true, otherwise is the
2377 /// ABI alignment.
2378 unsigned getTypeAlignIfKnown(QualType T,
2379 bool NeedsPreferredAlignment = false) const;
2380
2381 /// Return the ABI-specified alignment of a (complete) type \p T, in
2382 /// characters.
2383 CharUnits getTypeAlignInChars(QualType T) const;
2384 CharUnits getTypeAlignInChars(const Type *T) const;
2385
2386 /// Return the PreferredAlignment of a (complete) type \p T, in
2387 /// characters.
2388 CharUnits getPreferredTypeAlignInChars(QualType T) const {
2389 return toCharUnitsFromBits(BitSize: getPreferredTypeAlign(T));
2390 }
2391
2392 /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a type,
2393 /// in characters, before alignment adjustments. This method does not work on
2394 /// incomplete types.
2395 CharUnits getTypeUnadjustedAlignInChars(QualType T) const;
2396 CharUnits getTypeUnadjustedAlignInChars(const Type *T) const;
2397
2398 // getTypeInfoDataSizeInChars - Return the size of a type, in chars. If the
2399 // type is a record, its data size is returned.
2400 TypeInfoChars getTypeInfoDataSizeInChars(QualType T) const;
2401
2402 TypeInfoChars getTypeInfoInChars(const Type *T) const;
2403 TypeInfoChars getTypeInfoInChars(QualType T) const;
2404
2405 /// Determine if the alignment the type has was required using an
2406 /// alignment attribute.
2407 bool isAlignmentRequired(const Type *T) const;
2408 bool isAlignmentRequired(QualType T) const;
2409
2410 /// More type predicates useful for type checking/promotion
2411 bool isPromotableIntegerType(QualType T) const; // C99 6.3.1.1p2
2412
2413 /// Return the "preferred" alignment of the specified type \p T for
2414 /// the current target, in bits.
2415 ///
2416 /// This can be different than the ABI alignment in cases where it is
2417 /// beneficial for performance or backwards compatibility preserving to
2418 /// overalign a data type. (Note: despite the name, the preferred alignment
2419 /// is ABI-impacting, and not an optimization.)
2420 unsigned getPreferredTypeAlign(QualType T) const {
2421 return getPreferredTypeAlign(T: T.getTypePtr());
2422 }
2423 unsigned getPreferredTypeAlign(const Type *T) const;
2424
2425 /// Return the default alignment for __attribute__((aligned)) on
2426 /// this target, to be used if no alignment value is specified.
2427 unsigned getTargetDefaultAlignForAttributeAligned() const;
2428
2429 /// Return the alignment in bits that should be given to a
2430 /// global variable with type \p T. If \p VD is non-null it will be
2431 /// considered specifically for the query.
2432 unsigned getAlignOfGlobalVar(QualType T, const VarDecl *VD) const;
2433
2434 /// Return the alignment in characters that should be given to a
2435 /// global variable with type \p T. If \p VD is non-null it will be
2436 /// considered specifically for the query.
2437 CharUnits getAlignOfGlobalVarInChars(QualType T, const VarDecl *VD) const;
2438
2439 /// Return the minimum alignement as specified by the target. If \p VD is
2440 /// non-null it may be used to identify external or weak variables.
2441 unsigned getMinGlobalAlignOfVar(uint64_t Size, const VarDecl *VD) const;
2442
2443 /// Return a conservative estimate of the alignment of the specified
2444 /// decl \p D.
2445 ///
2446 /// \pre \p D must not be a bitfield type, as bitfields do not have a valid
2447 /// alignment.
2448 ///
2449 /// If \p ForAlignof, references are treated like their underlying type
2450 /// and large arrays don't get any special treatment. If not \p ForAlignof
2451 /// it computes the value expected by CodeGen: references are treated like
2452 /// pointers and large arrays get extra alignment.
2453 CharUnits getDeclAlign(const Decl *D, bool ForAlignof = false) const;
2454
2455 /// Return the alignment (in bytes) of the thrown exception object. This is
2456 /// only meaningful for targets that allocate C++ exceptions in a system
2457 /// runtime, such as those using the Itanium C++ ABI.
2458 CharUnits getExnObjectAlignment() const;
2459
2460 /// Get or compute information about the layout of the specified
2461 /// record (struct/union/class) \p D, which indicates its size and field
2462 /// position information.
2463 const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D) const;
2464
2465 /// Get or compute information about the layout of the specified
2466 /// Objective-C interface.
2467 const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D)
2468 const;
2469
2470 void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS,
2471 bool Simple = false) const;
2472
2473 /// Get or compute information about the layout of the specified
2474 /// Objective-C implementation.
2475 ///
2476 /// This may differ from the interface if synthesized ivars are present.
2477 const ASTRecordLayout &
2478 getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const;
2479
2480 /// Get our current best idea for the key function of the
2481 /// given record decl, or nullptr if there isn't one.
2482 ///
2483 /// The key function is, according to the Itanium C++ ABI section 5.2.3:
2484 /// ...the first non-pure virtual function that is not inline at the
2485 /// point of class definition.
2486 ///
2487 /// Other ABIs use the same idea. However, the ARM C++ ABI ignores
2488 /// virtual functions that are defined 'inline', which means that
2489 /// the result of this computation can change.
2490 const CXXMethodDecl *getCurrentKeyFunction(const CXXRecordDecl *RD);
2491
2492 /// Observe that the given method cannot be a key function.
2493 /// Checks the key-function cache for the method's class and clears it
2494 /// if matches the given declaration.
2495 ///
2496 /// This is used in ABIs where out-of-line definitions marked
2497 /// inline are not considered to be key functions.
2498 ///
2499 /// \param method should be the declaration from the class definition
2500 void setNonKeyFunction(const CXXMethodDecl *method);
2501
2502 /// Loading virtual member pointers using the virtual inheritance model
2503 /// always results in an adjustment using the vbtable even if the index is
2504 /// zero.
2505 ///
2506 /// This is usually OK because the first slot in the vbtable points
2507 /// backwards to the top of the MDC. However, the MDC might be reusing a
2508 /// vbptr from an nv-base. In this case, the first slot in the vbtable
2509 /// points to the start of the nv-base which introduced the vbptr and *not*
2510 /// the MDC. Modify the NonVirtualBaseAdjustment to account for this.
2511 CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const;
2512
2513 /// Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
2514 uint64_t getFieldOffset(const ValueDecl *FD) const;
2515
2516 /// Get the offset of an ObjCIvarDecl in bits.
2517 uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID,
2518 const ObjCImplementationDecl *ID,
2519 const ObjCIvarDecl *Ivar) const;
2520
2521 /// Find the 'this' offset for the member path in a pointer-to-member
2522 /// APValue.
2523 CharUnits getMemberPointerPathAdjustment(const APValue &MP) const;
2524
2525 bool isNearlyEmpty(const CXXRecordDecl *RD) const;
2526
2527 VTableContextBase *getVTableContext();
2528
2529 /// If \p T is null pointer, assume the target in ASTContext.
2530 MangleContext *createMangleContext(const TargetInfo *T = nullptr);
2531
2532 /// Creates a device mangle context to correctly mangle lambdas in a mixed
2533 /// architecture compile by setting the lambda mangling number source to the
2534 /// DeviceLambdaManglingNumber. Currently this asserts that the TargetInfo
2535 /// (from the AuxTargetInfo) is a an itanium target.
2536 MangleContext *createDeviceMangleContext(const TargetInfo &T);
2537
2538 void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass,
2539 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const;
2540
2541 unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const;
2542 void CollectInheritedProtocols(const Decl *CDecl,
2543 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols);
2544
2545 /// Return true if the specified type has unique object representations
2546 /// according to (C++17 [meta.unary.prop]p9)
2547 bool
2548 hasUniqueObjectRepresentations(QualType Ty,
2549 bool CheckIfTriviallyCopyable = true) const;
2550
2551 //===--------------------------------------------------------------------===//
2552 // Type Operators
2553 //===--------------------------------------------------------------------===//
2554
2555 /// Return the canonical (structural) type corresponding to the
2556 /// specified potentially non-canonical type \p T.
2557 ///
2558 /// The non-canonical version of a type may have many "decorated" versions of
2559 /// types. Decorators can include typedefs, 'typeof' operators, etc. The
2560 /// returned type is guaranteed to be free of any of these, allowing two
2561 /// canonical types to be compared for exact equality with a simple pointer
2562 /// comparison.
2563 CanQualType getCanonicalType(QualType T) const {
2564 return CanQualType::CreateUnsafe(Other: T.getCanonicalType());
2565 }
2566
2567 const Type *getCanonicalType(const Type *T) const {
2568 return T->getCanonicalTypeInternal().getTypePtr();
2569 }
2570
2571 /// Return the canonical parameter type corresponding to the specific
2572 /// potentially non-canonical one.
2573 ///
2574 /// Qualifiers are stripped off, functions are turned into function
2575 /// pointers, and arrays decay one level into pointers.
2576 CanQualType getCanonicalParamType(QualType T) const;
2577
2578 /// Determine whether the given types \p T1 and \p T2 are equivalent.
2579 bool hasSameType(QualType T1, QualType T2) const {
2580 return getCanonicalType(T: T1) == getCanonicalType(T: T2);
2581 }
2582 bool hasSameType(const Type *T1, const Type *T2) const {
2583 return getCanonicalType(T: T1) == getCanonicalType(T: T2);
2584 }
2585
2586 /// Determine whether the given expressions \p X and \p Y are equivalent.
2587 bool hasSameExpr(const Expr *X, const Expr *Y) const;
2588
2589 /// Return this type as a completely-unqualified array type,
2590 /// capturing the qualifiers in \p Quals.
2591 ///
2592 /// This will remove the minimal amount of sugaring from the types, similar
2593 /// to the behavior of QualType::getUnqualifiedType().
2594 ///
2595 /// \param T is the qualified type, which may be an ArrayType
2596 ///
2597 /// \param Quals will receive the full set of qualifiers that were
2598 /// applied to the array.
2599 ///
2600 /// \returns if this is an array type, the completely unqualified array type
2601 /// that corresponds to it. Otherwise, returns T.getUnqualifiedType().
2602 QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals);
2603
2604 /// Determine whether the given types are equivalent after
2605 /// cvr-qualifiers have been removed.
2606 bool hasSameUnqualifiedType(QualType T1, QualType T2) const {
2607 return getCanonicalType(T: T1).getTypePtr() ==
2608 getCanonicalType(T: T2).getTypePtr();
2609 }
2610
2611 bool hasSameNullabilityTypeQualifier(QualType SubT, QualType SuperT,
2612 bool IsParam) const {
2613 auto SubTnullability = SubT->getNullability();
2614 auto SuperTnullability = SuperT->getNullability();
2615 if (SubTnullability.has_value() == SuperTnullability.has_value()) {
2616 // Neither has nullability; return true
2617 if (!SubTnullability)
2618 return true;
2619 // Both have nullability qualifier.
2620 if (*SubTnullability == *SuperTnullability ||
2621 *SubTnullability == NullabilityKind::Unspecified ||
2622 *SuperTnullability == NullabilityKind::Unspecified)
2623 return true;
2624
2625 if (IsParam) {
2626 // Ok for the superclass method parameter to be "nonnull" and the subclass
2627 // method parameter to be "nullable"
2628 return (*SuperTnullability == NullabilityKind::NonNull &&
2629 *SubTnullability == NullabilityKind::Nullable);
2630 }
2631 // For the return type, it's okay for the superclass method to specify
2632 // "nullable" and the subclass method specify "nonnull"
2633 return (*SuperTnullability == NullabilityKind::Nullable &&
2634 *SubTnullability == NullabilityKind::NonNull);
2635 }
2636 return true;
2637 }
2638
2639 bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
2640 const ObjCMethodDecl *MethodImp);
2641
2642 bool UnwrapSimilarTypes(QualType &T1, QualType &T2,
2643 bool AllowPiMismatch = true);
2644 void UnwrapSimilarArrayTypes(QualType &T1, QualType &T2,
2645 bool AllowPiMismatch = true);
2646
2647 /// Determine if two types are similar, according to the C++ rules. That is,
2648 /// determine if they are the same other than qualifiers on the initial
2649 /// sequence of pointer / pointer-to-member / array (and in Clang, object
2650 /// pointer) types and their element types.
2651 ///
2652 /// Clang offers a number of qualifiers in addition to the C++ qualifiers;
2653 /// those qualifiers are also ignored in the 'similarity' check.
2654 bool hasSimilarType(QualType T1, QualType T2);
2655
2656 /// Determine if two types are similar, ignoring only CVR qualifiers.
2657 bool hasCvrSimilarType(QualType T1, QualType T2);
2658
2659 /// Retrieves the "canonical" nested name specifier for a
2660 /// given nested name specifier.
2661 ///
2662 /// The canonical nested name specifier is a nested name specifier
2663 /// that uniquely identifies a type or namespace within the type
2664 /// system. For example, given:
2665 ///
2666 /// \code
2667 /// namespace N {
2668 /// struct S {
2669 /// template<typename T> struct X { typename T* type; };
2670 /// };
2671 /// }
2672 ///
2673 /// template<typename T> struct Y {
2674 /// typename N::S::X<T>::type member;
2675 /// };
2676 /// \endcode
2677 ///
2678 /// Here, the nested-name-specifier for N::S::X<T>:: will be
2679 /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined
2680 /// by declarations in the type system and the canonical type for
2681 /// the template type parameter 'T' is template-param-0-0.
2682 NestedNameSpecifier *
2683 getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const;
2684
2685 /// Retrieves the default calling convention for the current target.
2686 CallingConv getDefaultCallingConvention(bool IsVariadic,
2687 bool IsCXXMethod,
2688 bool IsBuiltin = false) const;
2689
2690 /// Retrieves the "canonical" template name that refers to a
2691 /// given template.
2692 ///
2693 /// The canonical template name is the simplest expression that can
2694 /// be used to refer to a given template. For most templates, this
2695 /// expression is just the template declaration itself. For example,
2696 /// the template std::vector can be referred to via a variety of
2697 /// names---std::vector, \::std::vector, vector (if vector is in
2698 /// scope), etc.---but all of these names map down to the same
2699 /// TemplateDecl, which is used to form the canonical template name.
2700 ///
2701 /// Dependent template names are more interesting. Here, the
2702 /// template name could be something like T::template apply or
2703 /// std::allocator<T>::template rebind, where the nested name
2704 /// specifier itself is dependent. In this case, the canonical
2705 /// template name uses the shortest form of the dependent
2706 /// nested-name-specifier, which itself contains all canonical
2707 /// types, values, and templates.
2708 TemplateName getCanonicalTemplateName(const TemplateName &Name) const;
2709
2710 /// Determine whether the given template names refer to the same
2711 /// template.
2712 bool hasSameTemplateName(const TemplateName &X, const TemplateName &Y) const;
2713
2714 /// Determine whether the two declarations refer to the same entity.
2715 bool isSameEntity(const NamedDecl *X, const NamedDecl *Y) const;
2716
2717 /// Determine whether two template parameter lists are similar enough
2718 /// that they may be used in declarations of the same template.
2719 bool isSameTemplateParameterList(const TemplateParameterList *X,
2720 const TemplateParameterList *Y) const;
2721
2722 /// Determine whether two template parameters are similar enough
2723 /// that they may be used in declarations of the same template.
2724 bool isSameTemplateParameter(const NamedDecl *X, const NamedDecl *Y) const;
2725
2726 /// Determine whether two 'requires' expressions are similar enough that they
2727 /// may be used in re-declarations.
2728 ///
2729 /// Use of 'requires' isn't mandatory, works with constraints expressed in
2730 /// other ways too.
2731 bool isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const;
2732
2733 /// Determine whether two type contraint are similar enough that they could
2734 /// used in declarations of the same template.
2735 bool isSameTypeConstraint(const TypeConstraint *XTC,
2736 const TypeConstraint *YTC) const;
2737
2738 /// Determine whether two default template arguments are similar enough
2739 /// that they may be used in declarations of the same template.
2740 bool isSameDefaultTemplateArgument(const NamedDecl *X,
2741 const NamedDecl *Y) const;
2742
2743 /// Retrieve the "canonical" template argument.
2744 ///
2745 /// The canonical template argument is the simplest template argument
2746 /// (which may be a type, value, expression, or declaration) that
2747 /// expresses the value of the argument.
2748 TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg)
2749 const;
2750
2751 /// Type Query functions. If the type is an instance of the specified class,
2752 /// return the Type pointer for the underlying maximally pretty type. This
2753 /// is a member of ASTContext because this may need to do some amount of
2754 /// canonicalization, e.g. to move type qualifiers into the element type.
2755 const ArrayType *getAsArrayType(QualType T) const;
2756 const ConstantArrayType *getAsConstantArrayType(QualType T) const {
2757 return dyn_cast_or_null<ConstantArrayType>(Val: getAsArrayType(T));
2758 }
2759 const VariableArrayType *getAsVariableArrayType(QualType T) const {
2760 return dyn_cast_or_null<VariableArrayType>(Val: getAsArrayType(T));
2761 }
2762 const IncompleteArrayType *getAsIncompleteArrayType(QualType T) const {
2763 return dyn_cast_or_null<IncompleteArrayType>(Val: getAsArrayType(T));
2764 }
2765 const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T)
2766 const {
2767 return dyn_cast_or_null<DependentSizedArrayType>(Val: getAsArrayType(T));
2768 }
2769
2770 /// Return the innermost element type of an array type.
2771 ///
2772 /// For example, will return "int" for int[m][n]
2773 QualType getBaseElementType(const ArrayType *VAT) const;
2774
2775 /// Return the innermost element type of a type (which needn't
2776 /// actually be an array type).
2777 QualType getBaseElementType(QualType QT) const;
2778
2779 /// Return number of constant array elements.
2780 uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const;
2781
2782 /// Return number of elements initialized in an ArrayInitLoopExpr.
2783 uint64_t
2784 getArrayInitLoopExprElementCount(const ArrayInitLoopExpr *AILE) const;
2785
2786 /// Perform adjustment on the parameter type of a function.
2787 ///
2788 /// This routine adjusts the given parameter type @p T to the actual
2789 /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
2790 /// C++ [dcl.fct]p3). The adjusted parameter type is returned.
2791 QualType getAdjustedParameterType(QualType T) const;
2792
2793 /// Retrieve the parameter type as adjusted for use in the signature
2794 /// of a function, decaying array and function types and removing top-level
2795 /// cv-qualifiers.
2796 QualType getSignatureParameterType(QualType T) const;
2797
2798 QualType getExceptionObjectType(QualType T) const;
2799
2800 /// Return the properly qualified result of decaying the specified
2801 /// array type to a pointer.
2802 ///
2803 /// This operation is non-trivial when handling typedefs etc. The canonical
2804 /// type of \p T must be an array type, this returns a pointer to a properly
2805 /// qualified element of the array.
2806 ///
2807 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2808 QualType getArrayDecayedType(QualType T) const;
2809
2810 /// Return the type that \p PromotableType will promote to: C99
2811 /// 6.3.1.1p2, assuming that \p PromotableType is a promotable integer type.
2812 QualType getPromotedIntegerType(QualType PromotableType) const;
2813
2814 /// Recurses in pointer/array types until it finds an Objective-C
2815 /// retainable type and returns its ownership.
2816 Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const;
2817
2818 /// Whether this is a promotable bitfield reference according
2819 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2820 ///
2821 /// \returns the type this bit-field will promote to, or NULL if no
2822 /// promotion occurs.
2823 QualType isPromotableBitField(Expr *E) const;
2824
2825 /// Return the highest ranked integer type, see C99 6.3.1.8p1.
2826 ///
2827 /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
2828 /// \p LHS < \p RHS, return -1.
2829 int getIntegerTypeOrder(QualType LHS, QualType RHS) const;
2830
2831 /// Compare the rank of the two specified floating point types,
2832 /// ignoring the domain of the type (i.e. 'double' == '_Complex double').
2833 ///
2834 /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
2835 /// \p LHS < \p RHS, return -1.
2836 int getFloatingTypeOrder(QualType LHS, QualType RHS) const;
2837
2838 /// Compare the rank of two floating point types as above, but compare equal
2839 /// if both types have the same floating-point semantics on the target (i.e.
2840 /// long double and double on AArch64 will return 0).
2841 int getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const;
2842
2843 unsigned getTargetAddressSpace(LangAS AS) const;
2844
2845 LangAS getLangASForBuiltinAddressSpace(unsigned AS) const;
2846
2847 /// Get target-dependent integer value for null pointer which is used for
2848 /// constant folding.
2849 uint64_t getTargetNullPointerValue(QualType QT) const;
2850
2851 bool addressSpaceMapManglingFor(LangAS AS) const {
2852 return AddrSpaceMapMangling || isTargetAddressSpace(AS);
2853 }
2854
2855 // Merges two exception specifications, such that the resulting
2856 // exception spec is the union of both. For example, if either
2857 // of them can throw something, the result can throw it as well.
2858 FunctionProtoType::ExceptionSpecInfo
2859 mergeExceptionSpecs(FunctionProtoType::ExceptionSpecInfo ESI1,
2860 FunctionProtoType::ExceptionSpecInfo ESI2,
2861 SmallVectorImpl<QualType> &ExceptionTypeStorage,
2862 bool AcceptDependent);
2863
2864 // For two "same" types, return a type which has
2865 // the common sugar between them. If Unqualified is true,
2866 // both types need only be the same unqualified type.
2867 // The result will drop the qualifiers which do not occur
2868 // in both types.
2869 QualType getCommonSugaredType(QualType X, QualType Y,
2870 bool Unqualified = false);
2871
2872private:
2873 // Helper for integer ordering
2874 unsigned getIntegerRank(const Type *T) const;
2875
2876public:
2877 //===--------------------------------------------------------------------===//
2878 // Type Compatibility Predicates
2879 //===--------------------------------------------------------------------===//
2880
2881 /// Compatibility predicates used to check assignment expressions.
2882 bool typesAreCompatible(QualType T1, QualType T2,
2883 bool CompareUnqualified = false); // C99 6.2.7p1
2884
2885 bool propertyTypesAreCompatible(QualType, QualType);
2886 bool typesAreBlockPointerCompatible(QualType, QualType);
2887
2888 bool isObjCIdType(QualType T) const {
2889 if (const auto *ET = dyn_cast<ElaboratedType>(Val&: T))
2890 T = ET->getNamedType();
2891 return T == getObjCIdType();
2892 }
2893
2894 bool isObjCClassType(QualType T) const {
2895 if (const auto *ET = dyn_cast<ElaboratedType>(Val&: T))
2896 T = ET->getNamedType();
2897 return T == getObjCClassType();
2898 }
2899
2900 bool isObjCSelType(QualType T) const {
2901 if (const auto *ET = dyn_cast<ElaboratedType>(Val&: T))
2902 T = ET->getNamedType();
2903 return T == getObjCSelType();
2904 }
2905
2906 bool ObjCQualifiedIdTypesAreCompatible(const ObjCObjectPointerType *LHS,
2907 const ObjCObjectPointerType *RHS,
2908 bool ForCompare);
2909
2910 bool ObjCQualifiedClassTypesAreCompatible(const ObjCObjectPointerType *LHS,
2911 const ObjCObjectPointerType *RHS);
2912
2913 // Check the safety of assignment from LHS to RHS
2914 bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
2915 const ObjCObjectPointerType *RHSOPT);
2916 bool canAssignObjCInterfaces(const ObjCObjectType *LHS,
2917 const ObjCObjectType *RHS);
2918 bool canAssignObjCInterfacesInBlockPointer(
2919 const ObjCObjectPointerType *LHSOPT,
2920 const ObjCObjectPointerType *RHSOPT,
2921 bool BlockReturnType);
2922 bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
2923 QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT,
2924 const ObjCObjectPointerType *RHSOPT);
2925 bool canBindObjCObjectType(QualType To, QualType From);
2926
2927 // Functions for calculating composite types
2928 QualType mergeTypes(QualType, QualType, bool OfBlockPointer = false,
2929 bool Unqualified = false, bool BlockReturnType = false,
2930 bool IsConditionalOperator = false);
2931 QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer = false,
2932 bool Unqualified = false, bool AllowCXX = false,
2933 bool IsConditionalOperator = false);
2934 QualType mergeFunctionParameterTypes(QualType, QualType,
2935 bool OfBlockPointer = false,
2936 bool Unqualified = false);
2937 QualType mergeTransparentUnionType(QualType, QualType,
2938 bool OfBlockPointer=false,
2939 bool Unqualified = false);
2940
2941 QualType mergeObjCGCQualifiers(QualType, QualType);
2942
2943 /// This function merges the ExtParameterInfo lists of two functions. It
2944 /// returns true if the lists are compatible. The merged list is returned in
2945 /// NewParamInfos.
2946 ///
2947 /// \param FirstFnType The type of the first function.
2948 ///
2949 /// \param SecondFnType The type of the second function.
2950 ///
2951 /// \param CanUseFirst This flag is set to true if the first function's
2952 /// ExtParameterInfo list can be used as the composite list of
2953 /// ExtParameterInfo.
2954 ///
2955 /// \param CanUseSecond This flag is set to true if the second function's
2956 /// ExtParameterInfo list can be used as the composite list of
2957 /// ExtParameterInfo.
2958 ///
2959 /// \param NewParamInfos The composite list of ExtParameterInfo. The list is
2960 /// empty if none of the flags are set.
2961 ///
2962 bool mergeExtParameterInfo(
2963 const FunctionProtoType *FirstFnType,
2964 const FunctionProtoType *SecondFnType,
2965 bool &CanUseFirst, bool &CanUseSecond,
2966 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos);
2967
2968 void ResetObjCLayout(const ObjCContainerDecl *CD);
2969
2970 //===--------------------------------------------------------------------===//
2971 // Integer Predicates
2972 //===--------------------------------------------------------------------===//
2973
2974 // The width of an integer, as defined in C99 6.2.6.2. This is the number
2975 // of bits in an integer type excluding any padding bits.
2976 unsigned getIntWidth(QualType T) const;
2977
2978 // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
2979 // unsigned integer type. This method takes a signed type, and returns the
2980 // corresponding unsigned integer type.
2981 // With the introduction of fixed point types in ISO N1169, this method also
2982 // accepts fixed point types and returns the corresponding unsigned type for
2983 // a given fixed point type.
2984 QualType getCorrespondingUnsignedType(QualType T) const;
2985
2986 // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
2987 // unsigned integer type. This method takes an unsigned type, and returns the
2988 // corresponding signed integer type.
2989 // With the introduction of fixed point types in ISO N1169, this method also
2990 // accepts fixed point types and returns the corresponding signed type for
2991 // a given fixed point type.
2992 QualType getCorrespondingSignedType(QualType T) const;
2993
2994 // Per ISO N1169, this method accepts fixed point types and returns the
2995 // corresponding saturated type for a given fixed point type.
2996 QualType getCorrespondingSaturatedType(QualType Ty) const;
2997
2998 // Per ISO N1169, this method accepts fixed point types and returns the
2999 // corresponding non-saturated type for a given fixed point type.
3000 QualType getCorrespondingUnsaturatedType(QualType Ty) const;
3001
3002 // This method accepts fixed point types and returns the corresponding signed
3003 // type. Unlike getCorrespondingUnsignedType(), this only accepts unsigned
3004 // fixed point types because there are unsigned integer types like bool and
3005 // char8_t that don't have signed equivalents.
3006 QualType getCorrespondingSignedFixedPointType(QualType Ty) const;
3007
3008 //===--------------------------------------------------------------------===//
3009 // Integer Values
3010 //===--------------------------------------------------------------------===//
3011
3012 /// Make an APSInt of the appropriate width and signedness for the
3013 /// given \p Value and integer \p Type.
3014 llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const {
3015 // If Type is a signed integer type larger than 64 bits, we need to be sure
3016 // to sign extend Res appropriately.
3017 llvm::APSInt Res(64, !Type->isSignedIntegerOrEnumerationType());
3018 Res = Value;
3019 unsigned Width = getIntWidth(T: Type);
3020 if (Width != Res.getBitWidth())
3021 return Res.extOrTrunc(width: Width);
3022 return Res;
3023 }
3024
3025 bool isSentinelNullExpr(const Expr *E);
3026
3027 /// Get the implementation of the ObjCInterfaceDecl \p D, or nullptr if
3028 /// none exists.
3029 ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D);
3030
3031 /// Get the implementation of the ObjCCategoryDecl \p D, or nullptr if
3032 /// none exists.
3033 ObjCCategoryImplDecl *getObjCImplementation(ObjCCategoryDecl *D);
3034
3035 /// Return true if there is at least one \@implementation in the TU.
3036 bool AnyObjCImplementation() {
3037 return !ObjCImpls.empty();
3038 }
3039
3040 /// Set the implementation of ObjCInterfaceDecl.
3041 void setObjCImplementation(ObjCInterfaceDecl *IFaceD,
3042 ObjCImplementationDecl *ImplD);
3043
3044 /// Set the implementation of ObjCCategoryDecl.
3045 void setObjCImplementation(ObjCCategoryDecl *CatD,
3046 ObjCCategoryImplDecl *ImplD);
3047
3048 /// Get the duplicate declaration of a ObjCMethod in the same
3049 /// interface, or null if none exists.
3050 const ObjCMethodDecl *
3051 getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const;
3052
3053 void setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
3054 const ObjCMethodDecl *Redecl);
3055
3056 /// Returns the Objective-C interface that \p ND belongs to if it is
3057 /// an Objective-C method/property/ivar etc. that is part of an interface,
3058 /// otherwise returns null.
3059 const ObjCInterfaceDecl *getObjContainingInterface(const NamedDecl *ND) const;
3060
3061 /// Set the copy initialization expression of a block var decl. \p CanThrow
3062 /// indicates whether the copy expression can throw or not.
3063 void setBlockVarCopyInit(const VarDecl* VD, Expr *CopyExpr, bool CanThrow);
3064
3065 /// Get the copy initialization expression of the VarDecl \p VD, or
3066 /// nullptr if none exists.
3067 BlockVarCopyInit getBlockVarCopyInit(const VarDecl* VD) const;
3068
3069 /// Allocate an uninitialized TypeSourceInfo.
3070 ///
3071 /// The caller should initialize the memory held by TypeSourceInfo using
3072 /// the TypeLoc wrappers.
3073 ///
3074 /// \param T the type that will be the basis for type source info. This type
3075 /// should refer to how the declarator was written in source code, not to
3076 /// what type semantic analysis resolved the declarator to.
3077 ///
3078 /// \param Size the size of the type info to create, or 0 if the size
3079 /// should be calculated based on the type.
3080 TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0) const;
3081
3082 /// Allocate a TypeSourceInfo where all locations have been
3083 /// initialized to a given location, which defaults to the empty
3084 /// location.
3085 TypeSourceInfo *
3086 getTrivialTypeSourceInfo(QualType T,
3087 SourceLocation Loc = SourceLocation()) const;
3088
3089 /// Add a deallocation callback that will be invoked when the
3090 /// ASTContext is destroyed.
3091 ///
3092 /// \param Callback A callback function that will be invoked on destruction.
3093 ///
3094 /// \param Data Pointer data that will be provided to the callback function
3095 /// when it is called.
3096 void AddDeallocation(void (*Callback)(void *), void *Data) const;
3097
3098 /// If T isn't trivially destructible, calls AddDeallocation to register it
3099 /// for destruction.
3100 template <typename T> void addDestruction(T *Ptr) const {
3101 if (!std::is_trivially_destructible<T>::value) {
3102 auto DestroyPtr = [](void *V) { static_cast<T *>(V)->~T(); };
3103 AddDeallocation(Callback: DestroyPtr, Data: Ptr);
3104 }
3105 }
3106
3107 GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const;
3108 GVALinkage GetGVALinkageForVariable(const VarDecl *VD) const;
3109
3110 /// Determines if the decl can be CodeGen'ed or deserialized from PCH
3111 /// lazily, only when used; this is only relevant for function or file scoped
3112 /// var definitions.
3113 ///
3114 /// \returns true if the function/var must be CodeGen'ed/deserialized even if
3115 /// it is not used.
3116 bool DeclMustBeEmitted(const Decl *D);
3117
3118 /// Visits all versions of a multiversioned function with the passed
3119 /// predicate.
3120 void forEachMultiversionedFunctionVersion(
3121 const FunctionDecl *FD,
3122 llvm::function_ref<void(FunctionDecl *)> Pred) const;
3123
3124 const CXXConstructorDecl *
3125 getCopyConstructorForExceptionObject(CXXRecordDecl *RD);
3126
3127 void addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
3128 CXXConstructorDecl *CD);
3129
3130 void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND);
3131
3132 TypedefNameDecl *getTypedefNameForUnnamedTagDecl(const TagDecl *TD);
3133
3134 void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD);
3135
3136 DeclaratorDecl *getDeclaratorForUnnamedTagDecl(const TagDecl *TD);
3137
3138 void setManglingNumber(const NamedDecl *ND, unsigned Number);
3139 unsigned getManglingNumber(const NamedDecl *ND,
3140 bool ForAuxTarget = false) const;
3141
3142 void setStaticLocalNumber(const VarDecl *VD, unsigned Number);
3143 unsigned getStaticLocalNumber(const VarDecl *VD) const;
3144
3145 /// Retrieve the context for computing mangling numbers in the given
3146 /// DeclContext.
3147 MangleNumberingContext &getManglingNumberContext(const DeclContext *DC);
3148 enum NeedExtraManglingDecl_t { NeedExtraManglingDecl };
3149 MangleNumberingContext &getManglingNumberContext(NeedExtraManglingDecl_t,
3150 const Decl *D);
3151
3152 std::unique_ptr<MangleNumberingContext> createMangleNumberingContext() const;
3153
3154 /// Used by ParmVarDecl to store on the side the
3155 /// index of the parameter when it exceeds the size of the normal bitfield.
3156 void setParameterIndex(const ParmVarDecl *D, unsigned index);
3157
3158 /// Used by ParmVarDecl to retrieve on the side the
3159 /// index of the parameter when it exceeds the size of the normal bitfield.
3160 unsigned getParameterIndex(const ParmVarDecl *D) const;
3161
3162 /// Return a string representing the human readable name for the specified
3163 /// function declaration or file name. Used by SourceLocExpr and
3164 /// PredefinedExpr to cache evaluated results.
3165 StringLiteral *getPredefinedStringLiteralFromCache(StringRef Key) const;
3166
3167 /// Return a declaration for the global GUID object representing the given
3168 /// GUID value.
3169 MSGuidDecl *getMSGuidDecl(MSGuidDeclParts Parts) const;
3170
3171 /// Return a declaration for a uniquified anonymous global constant
3172 /// corresponding to a given APValue.
3173 UnnamedGlobalConstantDecl *
3174 getUnnamedGlobalConstantDecl(QualType Ty, const APValue &Value) const;
3175
3176 /// Return the template parameter object of the given type with the given
3177 /// value.
3178 TemplateParamObjectDecl *getTemplateParamObjectDecl(QualType T,
3179 const APValue &V) const;
3180
3181 /// Parses the target attributes passed in, and returns only the ones that are
3182 /// valid feature names.
3183 ParsedTargetAttr filterFunctionTargetAttrs(const TargetAttr *TD) const;
3184
3185 std::vector<std::string>
3186 filterFunctionTargetVersionAttrs(const TargetVersionAttr *TV) const;
3187
3188 void getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
3189 const FunctionDecl *) const;
3190 void getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
3191 GlobalDecl GD) const;
3192
3193 //===--------------------------------------------------------------------===//
3194 // Statistics
3195 //===--------------------------------------------------------------------===//
3196
3197 /// The number of implicitly-declared default constructors.
3198 unsigned NumImplicitDefaultConstructors = 0;
3199
3200 /// The number of implicitly-declared default constructors for
3201 /// which declarations were built.
3202 unsigned NumImplicitDefaultConstructorsDeclared = 0;
3203
3204 /// The number of implicitly-declared copy constructors.
3205 unsigned NumImplicitCopyConstructors = 0;
3206
3207 /// The number of implicitly-declared copy constructors for
3208 /// which declarations were built.
3209 unsigned NumImplicitCopyConstructorsDeclared = 0;
3210
3211 /// The number of implicitly-declared move constructors.
3212 unsigned NumImplicitMoveConstructors = 0;
3213
3214 /// The number of implicitly-declared move constructors for
3215 /// which declarations were built.
3216 unsigned NumImplicitMoveConstructorsDeclared = 0;
3217
3218 /// The number of implicitly-declared copy assignment operators.
3219 unsigned NumImplicitCopyAssignmentOperators = 0;
3220
3221 /// The number of implicitly-declared copy assignment operators for
3222 /// which declarations were built.
3223 unsigned NumImplicitCopyAssignmentOperatorsDeclared = 0;
3224
3225 /// The number of implicitly-declared move assignment operators.
3226 unsigned NumImplicitMoveAssignmentOperators = 0;
3227
3228 /// The number of implicitly-declared move assignment operators for
3229 /// which declarations were built.
3230 unsigned NumImplicitMoveAssignmentOperatorsDeclared = 0;
3231
3232 /// The number of implicitly-declared destructors.
3233 unsigned NumImplicitDestructors = 0;
3234
3235 /// The number of implicitly-declared destructors for which
3236 /// declarations were built.
3237 unsigned NumImplicitDestructorsDeclared = 0;
3238
3239public:
3240 /// Initialize built-in types.
3241 ///
3242 /// This routine may only be invoked once for a given ASTContext object.
3243 /// It is normally invoked after ASTContext construction.
3244 ///
3245 /// \param Target The target
3246 void InitBuiltinTypes(const TargetInfo &Target,
3247 const TargetInfo *AuxTarget = nullptr);
3248
3249private:
3250 void InitBuiltinType(CanQualType &R, BuiltinType::Kind K);
3251
3252 class ObjCEncOptions {
3253 unsigned Bits;
3254
3255 ObjCEncOptions(unsigned Bits) : Bits(Bits) {}
3256
3257 public:
3258 ObjCEncOptions() : Bits(0) {}
3259
3260#define OPT_LIST(V) \
3261 V(ExpandPointedToStructures, 0) \
3262 V(ExpandStructures, 1) \
3263 V(IsOutermostType, 2) \
3264 V(EncodingProperty, 3) \
3265 V(IsStructField, 4) \
3266 V(EncodeBlockParameters, 5) \
3267 V(EncodeClassNames, 6) \
3268
3269#define V(N,I) ObjCEncOptions& set##N() { Bits |= 1 << I; return *this; }
3270OPT_LIST(V)
3271#undef V
3272
3273#define V(N,I) bool N() const { return Bits & 1 << I; }
3274OPT_LIST(V)
3275#undef V
3276
3277#undef OPT_LIST
3278
3279 [[nodiscard]] ObjCEncOptions keepingOnly(ObjCEncOptions Mask) const {
3280 return Bits & Mask.Bits;
3281 }
3282
3283 [[nodiscard]] ObjCEncOptions forComponentType() const {
3284 ObjCEncOptions Mask = ObjCEncOptions()
3285 .setIsOutermostType()
3286 .setIsStructField();
3287 return Bits & ~Mask.Bits;
3288 }
3289 };
3290
3291 // Return the Objective-C type encoding for a given type.
3292 void getObjCEncodingForTypeImpl(QualType t, std::string &S,
3293 ObjCEncOptions Options,
3294 const FieldDecl *Field,
3295 QualType *NotEncodedT = nullptr) const;
3296
3297 // Adds the encoding of the structure's members.
3298 void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S,
3299 const FieldDecl *Field,
3300 bool includeVBases = true,
3301 QualType *NotEncodedT=nullptr) const;
3302
3303public:
3304 // Adds the encoding of a method parameter or return type.
3305 void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
3306 QualType T, std::string& S,
3307 bool Extended) const;
3308
3309 /// Returns true if this is an inline-initialized static data member
3310 /// which is treated as a definition for MSVC compatibility.
3311 bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const;
3312
3313 enum class InlineVariableDefinitionKind {
3314 /// Not an inline variable.
3315 None,
3316
3317 /// Weak definition of inline variable.
3318 Weak,
3319
3320 /// Weak for now, might become strong later in this TU.
3321 WeakUnknown,
3322
3323 /// Strong definition.
3324 Strong
3325 };
3326
3327 /// Determine whether a definition of this inline variable should
3328 /// be treated as a weak or strong definition. For compatibility with
3329 /// C++14 and before, for a constexpr static data member, if there is an
3330 /// out-of-line declaration of the member, we may promote it from weak to
3331 /// strong.
3332 InlineVariableDefinitionKind
3333 getInlineVariableDefinitionKind(const VarDecl *VD) const;
3334
3335private:
3336 friend class DeclarationNameTable;
3337 friend class DeclContext;
3338
3339 const ASTRecordLayout &
3340 getObjCLayout(const ObjCInterfaceDecl *D,
3341 const ObjCImplementationDecl *Impl) const;
3342
3343 /// A set of deallocations that should be performed when the
3344 /// ASTContext is destroyed.
3345 // FIXME: We really should have a better mechanism in the ASTContext to
3346 // manage running destructors for types which do variable sized allocation
3347 // within the AST. In some places we thread the AST bump pointer allocator
3348 // into the datastructures which avoids this mess during deallocation but is
3349 // wasteful of memory, and here we require a lot of error prone book keeping
3350 // in order to track and run destructors while we're tearing things down.
3351 using DeallocationFunctionsAndArguments =
3352 llvm::SmallVector<std::pair<void (*)(void *), void *>, 16>;
3353 mutable DeallocationFunctionsAndArguments Deallocations;
3354
3355 // FIXME: This currently contains the set of StoredDeclMaps used
3356 // by DeclContext objects. This probably should not be in ASTContext,
3357 // but we include it here so that ASTContext can quickly deallocate them.
3358 llvm::PointerIntPair<StoredDeclsMap *, 1> LastSDM;
3359
3360 std::vector<Decl *> TraversalScope;
3361
3362 std::unique_ptr<VTableContextBase> VTContext;
3363
3364 void ReleaseDeclContextMaps();
3365
3366public:
3367 enum PragmaSectionFlag : unsigned {
3368 PSF_None = 0,
3369 PSF_Read = 0x1,
3370 PSF_Write = 0x2,
3371 PSF_Execute = 0x4,
3372 PSF_Implicit = 0x8,
3373 PSF_ZeroInit = 0x10,
3374 PSF_Invalid = 0x80000000U,
3375 };
3376
3377 struct SectionInfo {
3378 NamedDecl *Decl;
3379 SourceLocation PragmaSectionLocation;
3380 int SectionFlags;
3381
3382 SectionInfo() = default;
3383 SectionInfo(NamedDecl *Decl, SourceLocation PragmaSectionLocation,
3384 int SectionFlags)
3385 : Decl(Decl), PragmaSectionLocation(PragmaSectionLocation),
3386 SectionFlags(SectionFlags) {}
3387 };
3388
3389 llvm::StringMap<SectionInfo> SectionInfos;
3390
3391 /// Return a new OMPTraitInfo object owned by this context.
3392 OMPTraitInfo &getNewOMPTraitInfo();
3393
3394 /// Whether a C++ static variable or CUDA/HIP kernel may be externalized.
3395 bool mayExternalize(const Decl *D) const;
3396
3397 /// Whether a C++ static variable or CUDA/HIP kernel should be externalized.
3398 bool shouldExternalize(const Decl *D) const;
3399
3400 StringRef getCUIDHash() const;
3401
3402private:
3403 /// All OMPTraitInfo objects live in this collection, one per
3404 /// `pragma omp [begin] declare variant` directive.
3405 SmallVector<std::unique_ptr<OMPTraitInfo>, 4> OMPTraitInfoVector;
3406};
3407
3408/// Insertion operator for diagnostics.
3409const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
3410 const ASTContext::SectionInfo &Section);
3411
3412/// Utility function for constructing a nullary selector.
3413inline Selector GetNullarySelector(StringRef name, ASTContext &Ctx) {
3414 const IdentifierInfo *II = &Ctx.Idents.get(Name: name);
3415 return Ctx.Selectors.getSelector(NumArgs: 0, IIV: &II);
3416}
3417
3418/// Utility function for constructing an unary selector.
3419inline Selector GetUnarySelector(StringRef name, ASTContext &Ctx) {
3420 const IdentifierInfo *II = &Ctx.Idents.get(Name: name);
3421 return Ctx.Selectors.getSelector(NumArgs: 1, IIV: &II);
3422}
3423
3424} // namespace clang
3425
3426// operator new and delete aren't allowed inside namespaces.
3427
3428/// Placement new for using the ASTContext's allocator.
3429///
3430/// This placement form of operator new uses the ASTContext's allocator for
3431/// obtaining memory.
3432///
3433/// IMPORTANT: These are also declared in clang/AST/ASTContextAllocate.h!
3434/// Any changes here need to also be made there.
3435///
3436/// We intentionally avoid using a nothrow specification here so that the calls
3437/// to this operator will not perform a null check on the result -- the
3438/// underlying allocator never returns null pointers.
3439///
3440/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
3441/// @code
3442/// // Default alignment (8)
3443/// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
3444/// // Specific alignment
3445/// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
3446/// @endcode
3447/// Memory allocated through this placement new operator does not need to be
3448/// explicitly freed, as ASTContext will free all of this memory when it gets
3449/// destroyed. Please note that you cannot use delete on the pointer.
3450///
3451/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
3452/// @param C The ASTContext that provides the allocator.
3453/// @param Alignment The alignment of the allocated memory (if the underlying
3454/// allocator supports it).
3455/// @return The allocated memory. Could be nullptr.
3456inline void *operator new(size_t Bytes, const clang::ASTContext &C,
3457 size_t Alignment /* = 8 */) {
3458 return C.Allocate(Size: Bytes, Align: Alignment);
3459}
3460
3461/// Placement delete companion to the new above.
3462///
3463/// This operator is just a companion to the new above. There is no way of
3464/// invoking it directly; see the new operator for more details. This operator
3465/// is called implicitly by the compiler if a placement new expression using
3466/// the ASTContext throws in the object constructor.
3467inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t) {
3468 C.Deallocate(Ptr);
3469}
3470
3471/// This placement form of operator new[] uses the ASTContext's allocator for
3472/// obtaining memory.
3473///
3474/// We intentionally avoid using a nothrow specification here so that the calls
3475/// to this operator will not perform a null check on the result -- the
3476/// underlying allocator never returns null pointers.
3477///
3478/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
3479/// @code
3480/// // Default alignment (8)
3481/// char *data = new (Context) char[10];
3482/// // Specific alignment
3483/// char *data = new (Context, 4) char[10];
3484/// @endcode
3485/// Memory allocated through this placement new[] operator does not need to be
3486/// explicitly freed, as ASTContext will free all of this memory when it gets
3487/// destroyed. Please note that you cannot use delete on the pointer.
3488///
3489/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
3490/// @param C The ASTContext that provides the allocator.
3491/// @param Alignment The alignment of the allocated memory (if the underlying
3492/// allocator supports it).
3493/// @return The allocated memory. Could be nullptr.
3494inline void *operator new[](size_t Bytes, const clang::ASTContext& C,
3495 size_t Alignment /* = 8 */) {
3496 return C.Allocate(Size: Bytes, Align: Alignment);
3497}
3498
3499/// Placement delete[] companion to the new[] above.
3500///
3501/// This operator is just a companion to the new[] above. There is no way of
3502/// invoking it directly; see the new[] operator for more details. This operator
3503/// is called implicitly by the compiler if a placement new[] expression using
3504/// the ASTContext throws in the object constructor.
3505inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_t) {
3506 C.Deallocate(Ptr);
3507}
3508
3509/// Create the representation of a LazyGenerationalUpdatePtr.
3510template <typename Owner, typename T,
3511 void (clang::ExternalASTSource::*Update)(Owner)>
3512typename clang::LazyGenerationalUpdatePtr<Owner, T, Update>::ValueType
3513 clang::LazyGenerationalUpdatePtr<Owner, T, Update>::makeValue(
3514 const clang::ASTContext &Ctx, T Value) {
3515 // Note, this is implemented here so that ExternalASTSource.h doesn't need to
3516 // include ASTContext.h. We explicitly instantiate it for all relevant types
3517 // in ASTContext.cpp.
3518 if (auto *Source = Ctx.getExternalSource())
3519 return new (Ctx) LazyData(Source, Value);
3520 return Value;
3521}
3522
3523#endif // LLVM_CLANG_AST_ASTCONTEXT_H
3524

source code of clang/include/clang/AST/ASTContext.h