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