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