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