1 //===- ASTContext.cpp - Context to hold long-lived AST nodes --------------===// 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 // This file implements the ASTContext interface. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/ASTContext.h" 14 #include "CXXABI.h" 15 #include "Interp/Context.h" 16 #include "clang/AST/APValue.h" 17 #include "clang/AST/ASTConcept.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/ASTTypeTraits.h" 20 #include "clang/AST/Attr.h" 21 #include "clang/AST/AttrIterator.h" 22 #include "clang/AST/CharUnits.h" 23 #include "clang/AST/Comment.h" 24 #include "clang/AST/Decl.h" 25 #include "clang/AST/DeclBase.h" 26 #include "clang/AST/DeclCXX.h" 27 #include "clang/AST/DeclContextInternals.h" 28 #include "clang/AST/DeclObjC.h" 29 #include "clang/AST/DeclOpenMP.h" 30 #include "clang/AST/DeclTemplate.h" 31 #include "clang/AST/DeclarationName.h" 32 #include "clang/AST/DependenceFlags.h" 33 #include "clang/AST/Expr.h" 34 #include "clang/AST/ExprCXX.h" 35 #include "clang/AST/ExprConcepts.h" 36 #include "clang/AST/ExternalASTSource.h" 37 #include "clang/AST/Mangle.h" 38 #include "clang/AST/MangleNumberingContext.h" 39 #include "clang/AST/NestedNameSpecifier.h" 40 #include "clang/AST/ParentMapContext.h" 41 #include "clang/AST/RawCommentList.h" 42 #include "clang/AST/RecordLayout.h" 43 #include "clang/AST/Stmt.h" 44 #include "clang/AST/TemplateBase.h" 45 #include "clang/AST/TemplateName.h" 46 #include "clang/AST/Type.h" 47 #include "clang/AST/TypeLoc.h" 48 #include "clang/AST/UnresolvedSet.h" 49 #include "clang/AST/VTableBuilder.h" 50 #include "clang/Basic/AddressSpaces.h" 51 #include "clang/Basic/Builtins.h" 52 #include "clang/Basic/CommentOptions.h" 53 #include "clang/Basic/ExceptionSpecificationType.h" 54 #include "clang/Basic/IdentifierTable.h" 55 #include "clang/Basic/LLVM.h" 56 #include "clang/Basic/LangOptions.h" 57 #include "clang/Basic/Linkage.h" 58 #include "clang/Basic/Module.h" 59 #include "clang/Basic/ObjCRuntime.h" 60 #include "clang/Basic/SanitizerBlacklist.h" 61 #include "clang/Basic/SourceLocation.h" 62 #include "clang/Basic/SourceManager.h" 63 #include "clang/Basic/Specifiers.h" 64 #include "clang/Basic/TargetCXXABI.h" 65 #include "clang/Basic/TargetInfo.h" 66 #include "clang/Basic/XRayLists.h" 67 #include "llvm/ADT/APFixedPoint.h" 68 #include "llvm/ADT/APInt.h" 69 #include "llvm/ADT/APSInt.h" 70 #include "llvm/ADT/ArrayRef.h" 71 #include "llvm/ADT/DenseMap.h" 72 #include "llvm/ADT/DenseSet.h" 73 #include "llvm/ADT/FoldingSet.h" 74 #include "llvm/ADT/None.h" 75 #include "llvm/ADT/Optional.h" 76 #include "llvm/ADT/PointerUnion.h" 77 #include "llvm/ADT/STLExtras.h" 78 #include "llvm/ADT/SmallPtrSet.h" 79 #include "llvm/ADT/SmallVector.h" 80 #include "llvm/ADT/StringExtras.h" 81 #include "llvm/ADT/StringRef.h" 82 #include "llvm/ADT/Triple.h" 83 #include "llvm/Support/Capacity.h" 84 #include "llvm/Support/Casting.h" 85 #include "llvm/Support/Compiler.h" 86 #include "llvm/Support/ErrorHandling.h" 87 #include "llvm/Support/MathExtras.h" 88 #include "llvm/Support/raw_ostream.h" 89 #include <algorithm> 90 #include <cassert> 91 #include <cstddef> 92 #include <cstdint> 93 #include <cstdlib> 94 #include <map> 95 #include <memory> 96 #include <string> 97 #include <tuple> 98 #include <utility> 99 100 using namespace clang; 101 102 enum FloatingRank { 103 BFloat16Rank, Float16Rank, HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank 104 }; 105 106 /// \returns location that is relevant when searching for Doc comments related 107 /// to \p D. 108 static SourceLocation getDeclLocForCommentSearch(const Decl *D, 109 SourceManager &SourceMgr) { 110 assert(D); 111 112 // User can not attach documentation to implicit declarations. 113 if (D->isImplicit()) 114 return {}; 115 116 // User can not attach documentation to implicit instantiations. 117 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 118 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 119 return {}; 120 } 121 122 if (const auto *VD = dyn_cast<VarDecl>(D)) { 123 if (VD->isStaticDataMember() && 124 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 125 return {}; 126 } 127 128 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) { 129 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 130 return {}; 131 } 132 133 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) { 134 TemplateSpecializationKind TSK = CTSD->getSpecializationKind(); 135 if (TSK == TSK_ImplicitInstantiation || 136 TSK == TSK_Undeclared) 137 return {}; 138 } 139 140 if (const auto *ED = dyn_cast<EnumDecl>(D)) { 141 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 142 return {}; 143 } 144 if (const auto *TD = dyn_cast<TagDecl>(D)) { 145 // When tag declaration (but not definition!) is part of the 146 // decl-specifier-seq of some other declaration, it doesn't get comment 147 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition()) 148 return {}; 149 } 150 // TODO: handle comments for function parameters properly. 151 if (isa<ParmVarDecl>(D)) 152 return {}; 153 154 // TODO: we could look up template parameter documentation in the template 155 // documentation. 156 if (isa<TemplateTypeParmDecl>(D) || 157 isa<NonTypeTemplateParmDecl>(D) || 158 isa<TemplateTemplateParmDecl>(D)) 159 return {}; 160 161 // Find declaration location. 162 // For Objective-C declarations we generally don't expect to have multiple 163 // declarators, thus use declaration starting location as the "declaration 164 // location". 165 // For all other declarations multiple declarators are used quite frequently, 166 // so we use the location of the identifier as the "declaration location". 167 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) || 168 isa<ObjCPropertyDecl>(D) || 169 isa<RedeclarableTemplateDecl>(D) || 170 isa<ClassTemplateSpecializationDecl>(D) || 171 // Allow association with Y across {} in `typedef struct X {} Y`. 172 isa<TypedefDecl>(D)) 173 return D->getBeginLoc(); 174 else { 175 const SourceLocation DeclLoc = D->getLocation(); 176 if (DeclLoc.isMacroID()) { 177 if (isa<TypedefDecl>(D)) { 178 // If location of the typedef name is in a macro, it is because being 179 // declared via a macro. Try using declaration's starting location as 180 // the "declaration location". 181 return D->getBeginLoc(); 182 } else if (const auto *TD = dyn_cast<TagDecl>(D)) { 183 // If location of the tag decl is inside a macro, but the spelling of 184 // the tag name comes from a macro argument, it looks like a special 185 // macro like NS_ENUM is being used to define the tag decl. In that 186 // case, adjust the source location to the expansion loc so that we can 187 // attach the comment to the tag decl. 188 if (SourceMgr.isMacroArgExpansion(DeclLoc) && 189 TD->isCompleteDefinition()) 190 return SourceMgr.getExpansionLoc(DeclLoc); 191 } 192 } 193 return DeclLoc; 194 } 195 196 return {}; 197 } 198 199 RawComment *ASTContext::getRawCommentForDeclNoCacheImpl( 200 const Decl *D, const SourceLocation RepresentativeLocForDecl, 201 const std::map<unsigned, RawComment *> &CommentsInTheFile) const { 202 // If the declaration doesn't map directly to a location in a file, we 203 // can't find the comment. 204 if (RepresentativeLocForDecl.isInvalid() || 205 !RepresentativeLocForDecl.isFileID()) 206 return nullptr; 207 208 // If there are no comments anywhere, we won't find anything. 209 if (CommentsInTheFile.empty()) 210 return nullptr; 211 212 // Decompose the location for the declaration and find the beginning of the 213 // file buffer. 214 const std::pair<FileID, unsigned> DeclLocDecomp = 215 SourceMgr.getDecomposedLoc(RepresentativeLocForDecl); 216 217 // Slow path. 218 auto OffsetCommentBehindDecl = 219 CommentsInTheFile.lower_bound(DeclLocDecomp.second); 220 221 // First check whether we have a trailing comment. 222 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) { 223 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second; 224 if ((CommentBehindDecl->isDocumentation() || 225 LangOpts.CommentOpts.ParseAllComments) && 226 CommentBehindDecl->isTrailingComment() && 227 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) || 228 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) { 229 230 // Check that Doxygen trailing comment comes after the declaration, starts 231 // on the same line and in the same file as the declaration. 232 if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) == 233 Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first, 234 OffsetCommentBehindDecl->first)) { 235 return CommentBehindDecl; 236 } 237 } 238 } 239 240 // The comment just after the declaration was not a trailing comment. 241 // Let's look at the previous comment. 242 if (OffsetCommentBehindDecl == CommentsInTheFile.begin()) 243 return nullptr; 244 245 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl; 246 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second; 247 248 // Check that we actually have a non-member Doxygen comment. 249 if (!(CommentBeforeDecl->isDocumentation() || 250 LangOpts.CommentOpts.ParseAllComments) || 251 CommentBeforeDecl->isTrailingComment()) 252 return nullptr; 253 254 // Decompose the end of the comment. 255 const unsigned CommentEndOffset = 256 Comments.getCommentEndOffset(CommentBeforeDecl); 257 258 // Get the corresponding buffer. 259 bool Invalid = false; 260 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first, 261 &Invalid).data(); 262 if (Invalid) 263 return nullptr; 264 265 // Extract text between the comment and declaration. 266 StringRef Text(Buffer + CommentEndOffset, 267 DeclLocDecomp.second - CommentEndOffset); 268 269 // There should be no other declarations or preprocessor directives between 270 // comment and declaration. 271 if (Text.find_first_of(";{}#@") != StringRef::npos) 272 return nullptr; 273 274 return CommentBeforeDecl; 275 } 276 277 RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const { 278 const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr); 279 280 // If the declaration doesn't map directly to a location in a file, we 281 // can't find the comment. 282 if (DeclLoc.isInvalid() || !DeclLoc.isFileID()) 283 return nullptr; 284 285 if (ExternalSource && !CommentsLoaded) { 286 ExternalSource->ReadComments(); 287 CommentsLoaded = true; 288 } 289 290 if (Comments.empty()) 291 return nullptr; 292 293 const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first; 294 const auto CommentsInThisFile = Comments.getCommentsInFile(File); 295 if (!CommentsInThisFile || CommentsInThisFile->empty()) 296 return nullptr; 297 298 return getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile); 299 } 300 301 void ASTContext::addComment(const RawComment &RC) { 302 assert(LangOpts.RetainCommentsFromSystemHeaders || 303 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin())); 304 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc); 305 } 306 307 /// If we have a 'templated' declaration for a template, adjust 'D' to 308 /// refer to the actual template. 309 /// If we have an implicit instantiation, adjust 'D' to refer to template. 310 static const Decl &adjustDeclToTemplate(const Decl &D) { 311 if (const auto *FD = dyn_cast<FunctionDecl>(&D)) { 312 // Is this function declaration part of a function template? 313 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 314 return *FTD; 315 316 // Nothing to do if function is not an implicit instantiation. 317 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) 318 return D; 319 320 // Function is an implicit instantiation of a function template? 321 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate()) 322 return *FTD; 323 324 // Function is instantiated from a member definition of a class template? 325 if (const FunctionDecl *MemberDecl = 326 FD->getInstantiatedFromMemberFunction()) 327 return *MemberDecl; 328 329 return D; 330 } 331 if (const auto *VD = dyn_cast<VarDecl>(&D)) { 332 // Static data member is instantiated from a member definition of a class 333 // template? 334 if (VD->isStaticDataMember()) 335 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember()) 336 return *MemberDecl; 337 338 return D; 339 } 340 if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) { 341 // Is this class declaration part of a class template? 342 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate()) 343 return *CTD; 344 345 // Class is an implicit instantiation of a class template or partial 346 // specialization? 347 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) { 348 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation) 349 return D; 350 llvm::PointerUnion<ClassTemplateDecl *, 351 ClassTemplatePartialSpecializationDecl *> 352 PU = CTSD->getSpecializedTemplateOrPartial(); 353 return PU.is<ClassTemplateDecl *>() 354 ? *static_cast<const Decl *>(PU.get<ClassTemplateDecl *>()) 355 : *static_cast<const Decl *>( 356 PU.get<ClassTemplatePartialSpecializationDecl *>()); 357 } 358 359 // Class is instantiated from a member definition of a class template? 360 if (const MemberSpecializationInfo *Info = 361 CRD->getMemberSpecializationInfo()) 362 return *Info->getInstantiatedFrom(); 363 364 return D; 365 } 366 if (const auto *ED = dyn_cast<EnumDecl>(&D)) { 367 // Enum is instantiated from a member definition of a class template? 368 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum()) 369 return *MemberDecl; 370 371 return D; 372 } 373 // FIXME: Adjust alias templates? 374 return D; 375 } 376 377 const RawComment *ASTContext::getRawCommentForAnyRedecl( 378 const Decl *D, 379 const Decl **OriginalDecl) const { 380 if (!D) { 381 if (OriginalDecl) 382 OriginalDecl = nullptr; 383 return nullptr; 384 } 385 386 D = &adjustDeclToTemplate(*D); 387 388 // Any comment directly attached to D? 389 { 390 auto DeclComment = DeclRawComments.find(D); 391 if (DeclComment != DeclRawComments.end()) { 392 if (OriginalDecl) 393 *OriginalDecl = D; 394 return DeclComment->second; 395 } 396 } 397 398 // Any comment attached to any redeclaration of D? 399 const Decl *CanonicalD = D->getCanonicalDecl(); 400 if (!CanonicalD) 401 return nullptr; 402 403 { 404 auto RedeclComment = RedeclChainComments.find(CanonicalD); 405 if (RedeclComment != RedeclChainComments.end()) { 406 if (OriginalDecl) 407 *OriginalDecl = RedeclComment->second; 408 auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second); 409 assert(CommentAtRedecl != DeclRawComments.end() && 410 "This decl is supposed to have comment attached."); 411 return CommentAtRedecl->second; 412 } 413 } 414 415 // Any redeclarations of D that we haven't checked for comments yet? 416 // We can't use DenseMap::iterator directly since it'd get invalid. 417 auto LastCheckedRedecl = [this, CanonicalD]() -> const Decl * { 418 auto LookupRes = CommentlessRedeclChains.find(CanonicalD); 419 if (LookupRes != CommentlessRedeclChains.end()) 420 return LookupRes->second; 421 return nullptr; 422 }(); 423 424 for (const auto Redecl : D->redecls()) { 425 assert(Redecl); 426 // Skip all redeclarations that have been checked previously. 427 if (LastCheckedRedecl) { 428 if (LastCheckedRedecl == Redecl) { 429 LastCheckedRedecl = nullptr; 430 } 431 continue; 432 } 433 const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl); 434 if (RedeclComment) { 435 cacheRawCommentForDecl(*Redecl, *RedeclComment); 436 if (OriginalDecl) 437 *OriginalDecl = Redecl; 438 return RedeclComment; 439 } 440 CommentlessRedeclChains[CanonicalD] = Redecl; 441 } 442 443 if (OriginalDecl) 444 *OriginalDecl = nullptr; 445 return nullptr; 446 } 447 448 void ASTContext::cacheRawCommentForDecl(const Decl &OriginalD, 449 const RawComment &Comment) const { 450 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments); 451 DeclRawComments.try_emplace(&OriginalD, &Comment); 452 const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl(); 453 RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD); 454 CommentlessRedeclChains.erase(CanonicalDecl); 455 } 456 457 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod, 458 SmallVectorImpl<const NamedDecl *> &Redeclared) { 459 const DeclContext *DC = ObjCMethod->getDeclContext(); 460 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) { 461 const ObjCInterfaceDecl *ID = IMD->getClassInterface(); 462 if (!ID) 463 return; 464 // Add redeclared method here. 465 for (const auto *Ext : ID->known_extensions()) { 466 if (ObjCMethodDecl *RedeclaredMethod = 467 Ext->getMethod(ObjCMethod->getSelector(), 468 ObjCMethod->isInstanceMethod())) 469 Redeclared.push_back(RedeclaredMethod); 470 } 471 } 472 } 473 474 void ASTContext::attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls, 475 const Preprocessor *PP) { 476 if (Comments.empty() || Decls.empty()) 477 return; 478 479 FileID File; 480 for (Decl *D : Decls) { 481 SourceLocation Loc = D->getLocation(); 482 if (Loc.isValid()) { 483 // See if there are any new comments that are not attached to a decl. 484 // The location doesn't have to be precise - we care only about the file. 485 File = SourceMgr.getDecomposedLoc(Loc).first; 486 break; 487 } 488 } 489 490 if (File.isInvalid()) 491 return; 492 493 auto CommentsInThisFile = Comments.getCommentsInFile(File); 494 if (!CommentsInThisFile || CommentsInThisFile->empty() || 495 CommentsInThisFile->rbegin()->second->isAttached()) 496 return; 497 498 // There is at least one comment not attached to a decl. 499 // Maybe it should be attached to one of Decls? 500 // 501 // Note that this way we pick up not only comments that precede the 502 // declaration, but also comments that *follow* the declaration -- thanks to 503 // the lookahead in the lexer: we've consumed the semicolon and looked 504 // ahead through comments. 505 506 for (const Decl *D : Decls) { 507 assert(D); 508 if (D->isInvalidDecl()) 509 continue; 510 511 D = &adjustDeclToTemplate(*D); 512 513 const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr); 514 515 if (DeclLoc.isInvalid() || !DeclLoc.isFileID()) 516 continue; 517 518 if (DeclRawComments.count(D) > 0) 519 continue; 520 521 if (RawComment *const DocComment = 522 getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile)) { 523 cacheRawCommentForDecl(*D, *DocComment); 524 comments::FullComment *FC = DocComment->parse(*this, PP, D); 525 ParsedComments[D->getCanonicalDecl()] = FC; 526 } 527 } 528 } 529 530 comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC, 531 const Decl *D) const { 532 auto *ThisDeclInfo = new (*this) comments::DeclInfo; 533 ThisDeclInfo->CommentDecl = D; 534 ThisDeclInfo->IsFilled = false; 535 ThisDeclInfo->fill(); 536 ThisDeclInfo->CommentDecl = FC->getDecl(); 537 if (!ThisDeclInfo->TemplateParameters) 538 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters; 539 comments::FullComment *CFC = 540 new (*this) comments::FullComment(FC->getBlocks(), 541 ThisDeclInfo); 542 return CFC; 543 } 544 545 comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const { 546 const RawComment *RC = getRawCommentForDeclNoCache(D); 547 return RC ? RC->parse(*this, nullptr, D) : nullptr; 548 } 549 550 comments::FullComment *ASTContext::getCommentForDecl( 551 const Decl *D, 552 const Preprocessor *PP) const { 553 if (!D || D->isInvalidDecl()) 554 return nullptr; 555 D = &adjustDeclToTemplate(*D); 556 557 const Decl *Canonical = D->getCanonicalDecl(); 558 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos = 559 ParsedComments.find(Canonical); 560 561 if (Pos != ParsedComments.end()) { 562 if (Canonical != D) { 563 comments::FullComment *FC = Pos->second; 564 comments::FullComment *CFC = cloneFullComment(FC, D); 565 return CFC; 566 } 567 return Pos->second; 568 } 569 570 const Decl *OriginalDecl = nullptr; 571 572 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl); 573 if (!RC) { 574 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) { 575 SmallVector<const NamedDecl*, 8> Overridden; 576 const auto *OMD = dyn_cast<ObjCMethodDecl>(D); 577 if (OMD && OMD->isPropertyAccessor()) 578 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl()) 579 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP)) 580 return cloneFullComment(FC, D); 581 if (OMD) 582 addRedeclaredMethods(OMD, Overridden); 583 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden); 584 for (unsigned i = 0, e = Overridden.size(); i < e; i++) 585 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP)) 586 return cloneFullComment(FC, D); 587 } 588 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) { 589 // Attach any tag type's documentation to its typedef if latter 590 // does not have one of its own. 591 QualType QT = TD->getUnderlyingType(); 592 if (const auto *TT = QT->getAs<TagType>()) 593 if (const Decl *TD = TT->getDecl()) 594 if (comments::FullComment *FC = getCommentForDecl(TD, PP)) 595 return cloneFullComment(FC, D); 596 } 597 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) { 598 while (IC->getSuperClass()) { 599 IC = IC->getSuperClass(); 600 if (comments::FullComment *FC = getCommentForDecl(IC, PP)) 601 return cloneFullComment(FC, D); 602 } 603 } 604 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) { 605 if (const ObjCInterfaceDecl *IC = CD->getClassInterface()) 606 if (comments::FullComment *FC = getCommentForDecl(IC, PP)) 607 return cloneFullComment(FC, D); 608 } 609 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) { 610 if (!(RD = RD->getDefinition())) 611 return nullptr; 612 // Check non-virtual bases. 613 for (const auto &I : RD->bases()) { 614 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public)) 615 continue; 616 QualType Ty = I.getType(); 617 if (Ty.isNull()) 618 continue; 619 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) { 620 if (!(NonVirtualBase= NonVirtualBase->getDefinition())) 621 continue; 622 623 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP)) 624 return cloneFullComment(FC, D); 625 } 626 } 627 // Check virtual bases. 628 for (const auto &I : RD->vbases()) { 629 if (I.getAccessSpecifier() != AS_public) 630 continue; 631 QualType Ty = I.getType(); 632 if (Ty.isNull()) 633 continue; 634 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) { 635 if (!(VirtualBase= VirtualBase->getDefinition())) 636 continue; 637 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP)) 638 return cloneFullComment(FC, D); 639 } 640 } 641 } 642 return nullptr; 643 } 644 645 // If the RawComment was attached to other redeclaration of this Decl, we 646 // should parse the comment in context of that other Decl. This is important 647 // because comments can contain references to parameter names which can be 648 // different across redeclarations. 649 if (D != OriginalDecl && OriginalDecl) 650 return getCommentForDecl(OriginalDecl, PP); 651 652 comments::FullComment *FC = RC->parse(*this, PP, D); 653 ParsedComments[Canonical] = FC; 654 return FC; 655 } 656 657 void 658 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID, 659 const ASTContext &C, 660 TemplateTemplateParmDecl *Parm) { 661 ID.AddInteger(Parm->getDepth()); 662 ID.AddInteger(Parm->getPosition()); 663 ID.AddBoolean(Parm->isParameterPack()); 664 665 TemplateParameterList *Params = Parm->getTemplateParameters(); 666 ID.AddInteger(Params->size()); 667 for (TemplateParameterList::const_iterator P = Params->begin(), 668 PEnd = Params->end(); 669 P != PEnd; ++P) { 670 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { 671 ID.AddInteger(0); 672 ID.AddBoolean(TTP->isParameterPack()); 673 const TypeConstraint *TC = TTP->getTypeConstraint(); 674 ID.AddBoolean(TC != nullptr); 675 if (TC) 676 TC->getImmediatelyDeclaredConstraint()->Profile(ID, C, 677 /*Canonical=*/true); 678 if (TTP->isExpandedParameterPack()) { 679 ID.AddBoolean(true); 680 ID.AddInteger(TTP->getNumExpansionParameters()); 681 } else 682 ID.AddBoolean(false); 683 continue; 684 } 685 686 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 687 ID.AddInteger(1); 688 ID.AddBoolean(NTTP->isParameterPack()); 689 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr()); 690 if (NTTP->isExpandedParameterPack()) { 691 ID.AddBoolean(true); 692 ID.AddInteger(NTTP->getNumExpansionTypes()); 693 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { 694 QualType T = NTTP->getExpansionType(I); 695 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr()); 696 } 697 } else 698 ID.AddBoolean(false); 699 continue; 700 } 701 702 auto *TTP = cast<TemplateTemplateParmDecl>(*P); 703 ID.AddInteger(2); 704 Profile(ID, C, TTP); 705 } 706 Expr *RequiresClause = Parm->getTemplateParameters()->getRequiresClause(); 707 ID.AddBoolean(RequiresClause != nullptr); 708 if (RequiresClause) 709 RequiresClause->Profile(ID, C, /*Canonical=*/true); 710 } 711 712 static Expr * 713 canonicalizeImmediatelyDeclaredConstraint(const ASTContext &C, Expr *IDC, 714 QualType ConstrainedType) { 715 // This is a bit ugly - we need to form a new immediately-declared 716 // constraint that references the new parameter; this would ideally 717 // require semantic analysis (e.g. template<C T> struct S {}; - the 718 // converted arguments of C<T> could be an argument pack if C is 719 // declared as template<typename... T> concept C = ...). 720 // We don't have semantic analysis here so we dig deep into the 721 // ready-made constraint expr and change the thing manually. 722 ConceptSpecializationExpr *CSE; 723 if (const auto *Fold = dyn_cast<CXXFoldExpr>(IDC)) 724 CSE = cast<ConceptSpecializationExpr>(Fold->getLHS()); 725 else 726 CSE = cast<ConceptSpecializationExpr>(IDC); 727 ArrayRef<TemplateArgument> OldConverted = CSE->getTemplateArguments(); 728 SmallVector<TemplateArgument, 3> NewConverted; 729 NewConverted.reserve(OldConverted.size()); 730 if (OldConverted.front().getKind() == TemplateArgument::Pack) { 731 // The case: 732 // template<typename... T> concept C = true; 733 // template<C<int> T> struct S; -> constraint is C<{T, int}> 734 NewConverted.push_back(ConstrainedType); 735 for (auto &Arg : OldConverted.front().pack_elements().drop_front(1)) 736 NewConverted.push_back(Arg); 737 TemplateArgument NewPack(NewConverted); 738 739 NewConverted.clear(); 740 NewConverted.push_back(NewPack); 741 assert(OldConverted.size() == 1 && 742 "Template parameter pack should be the last parameter"); 743 } else { 744 assert(OldConverted.front().getKind() == TemplateArgument::Type && 745 "Unexpected first argument kind for immediately-declared " 746 "constraint"); 747 NewConverted.push_back(ConstrainedType); 748 for (auto &Arg : OldConverted.drop_front(1)) 749 NewConverted.push_back(Arg); 750 } 751 Expr *NewIDC = ConceptSpecializationExpr::Create( 752 C, CSE->getNamedConcept(), NewConverted, nullptr, 753 CSE->isInstantiationDependent(), CSE->containsUnexpandedParameterPack()); 754 755 if (auto *OrigFold = dyn_cast<CXXFoldExpr>(IDC)) 756 NewIDC = new (C) CXXFoldExpr( 757 OrigFold->getType(), /*Callee*/nullptr, SourceLocation(), NewIDC, 758 BinaryOperatorKind::BO_LAnd, SourceLocation(), /*RHS=*/nullptr, 759 SourceLocation(), /*NumExpansions=*/None); 760 return NewIDC; 761 } 762 763 TemplateTemplateParmDecl * 764 ASTContext::getCanonicalTemplateTemplateParmDecl( 765 TemplateTemplateParmDecl *TTP) const { 766 // Check if we already have a canonical template template parameter. 767 llvm::FoldingSetNodeID ID; 768 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP); 769 void *InsertPos = nullptr; 770 CanonicalTemplateTemplateParm *Canonical 771 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 772 if (Canonical) 773 return Canonical->getParam(); 774 775 // Build a canonical template parameter list. 776 TemplateParameterList *Params = TTP->getTemplateParameters(); 777 SmallVector<NamedDecl *, 4> CanonParams; 778 CanonParams.reserve(Params->size()); 779 for (TemplateParameterList::const_iterator P = Params->begin(), 780 PEnd = Params->end(); 781 P != PEnd; ++P) { 782 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { 783 TemplateTypeParmDecl *NewTTP = TemplateTypeParmDecl::Create(*this, 784 getTranslationUnitDecl(), SourceLocation(), SourceLocation(), 785 TTP->getDepth(), TTP->getIndex(), nullptr, false, 786 TTP->isParameterPack(), TTP->hasTypeConstraint(), 787 TTP->isExpandedParameterPack() ? 788 llvm::Optional<unsigned>(TTP->getNumExpansionParameters()) : None); 789 if (const auto *TC = TTP->getTypeConstraint()) { 790 QualType ParamAsArgument(NewTTP->getTypeForDecl(), 0); 791 Expr *NewIDC = canonicalizeImmediatelyDeclaredConstraint( 792 *this, TC->getImmediatelyDeclaredConstraint(), 793 ParamAsArgument); 794 TemplateArgumentListInfo CanonArgsAsWritten; 795 if (auto *Args = TC->getTemplateArgsAsWritten()) 796 for (const auto &ArgLoc : Args->arguments()) 797 CanonArgsAsWritten.addArgument( 798 TemplateArgumentLoc(ArgLoc.getArgument(), 799 TemplateArgumentLocInfo())); 800 NewTTP->setTypeConstraint( 801 NestedNameSpecifierLoc(), 802 DeclarationNameInfo(TC->getNamedConcept()->getDeclName(), 803 SourceLocation()), /*FoundDecl=*/nullptr, 804 // Actually canonicalizing a TemplateArgumentLoc is difficult so we 805 // simply omit the ArgsAsWritten 806 TC->getNamedConcept(), /*ArgsAsWritten=*/nullptr, NewIDC); 807 } 808 CanonParams.push_back(NewTTP); 809 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 810 QualType T = getCanonicalType(NTTP->getType()); 811 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); 812 NonTypeTemplateParmDecl *Param; 813 if (NTTP->isExpandedParameterPack()) { 814 SmallVector<QualType, 2> ExpandedTypes; 815 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos; 816 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { 817 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I))); 818 ExpandedTInfos.push_back( 819 getTrivialTypeSourceInfo(ExpandedTypes.back())); 820 } 821 822 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 823 SourceLocation(), 824 SourceLocation(), 825 NTTP->getDepth(), 826 NTTP->getPosition(), nullptr, 827 T, 828 TInfo, 829 ExpandedTypes, 830 ExpandedTInfos); 831 } else { 832 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 833 SourceLocation(), 834 SourceLocation(), 835 NTTP->getDepth(), 836 NTTP->getPosition(), nullptr, 837 T, 838 NTTP->isParameterPack(), 839 TInfo); 840 } 841 if (AutoType *AT = T->getContainedAutoType()) { 842 if (AT->isConstrained()) { 843 Param->setPlaceholderTypeConstraint( 844 canonicalizeImmediatelyDeclaredConstraint( 845 *this, NTTP->getPlaceholderTypeConstraint(), T)); 846 } 847 } 848 CanonParams.push_back(Param); 849 850 } else 851 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl( 852 cast<TemplateTemplateParmDecl>(*P))); 853 } 854 855 Expr *CanonRequiresClause = nullptr; 856 if (Expr *RequiresClause = TTP->getTemplateParameters()->getRequiresClause()) 857 CanonRequiresClause = RequiresClause; 858 859 TemplateTemplateParmDecl *CanonTTP 860 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 861 SourceLocation(), TTP->getDepth(), 862 TTP->getPosition(), 863 TTP->isParameterPack(), 864 nullptr, 865 TemplateParameterList::Create(*this, SourceLocation(), 866 SourceLocation(), 867 CanonParams, 868 SourceLocation(), 869 CanonRequiresClause)); 870 871 // Get the new insert position for the node we care about. 872 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 873 assert(!Canonical && "Shouldn't be in the map!"); 874 (void)Canonical; 875 876 // Create the canonical template template parameter entry. 877 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP); 878 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos); 879 return CanonTTP; 880 } 881 882 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) { 883 if (!LangOpts.CPlusPlus) return nullptr; 884 885 switch (T.getCXXABI().getKind()) { 886 case TargetCXXABI::AppleARM64: 887 case TargetCXXABI::Fuchsia: 888 case TargetCXXABI::GenericARM: // Same as Itanium at this level 889 case TargetCXXABI::iOS: 890 case TargetCXXABI::WatchOS: 891 case TargetCXXABI::GenericAArch64: 892 case TargetCXXABI::GenericMIPS: 893 case TargetCXXABI::GenericItanium: 894 case TargetCXXABI::WebAssembly: 895 case TargetCXXABI::XL: 896 return CreateItaniumCXXABI(*this); 897 case TargetCXXABI::Microsoft: 898 return CreateMicrosoftCXXABI(*this); 899 } 900 llvm_unreachable("Invalid CXXABI type!"); 901 } 902 903 interp::Context &ASTContext::getInterpContext() { 904 if (!InterpContext) { 905 InterpContext.reset(new interp::Context(*this)); 906 } 907 return *InterpContext.get(); 908 } 909 910 ParentMapContext &ASTContext::getParentMapContext() { 911 if (!ParentMapCtx) 912 ParentMapCtx.reset(new ParentMapContext(*this)); 913 return *ParentMapCtx.get(); 914 } 915 916 static const LangASMap *getAddressSpaceMap(const TargetInfo &T, 917 const LangOptions &LOpts) { 918 if (LOpts.FakeAddressSpaceMap) { 919 // The fake address space map must have a distinct entry for each 920 // language-specific address space. 921 static const unsigned FakeAddrSpaceMap[] = { 922 0, // Default 923 1, // opencl_global 924 3, // opencl_local 925 2, // opencl_constant 926 0, // opencl_private 927 4, // opencl_generic 928 5, // opencl_global_device 929 6, // opencl_global_host 930 7, // cuda_device 931 8, // cuda_constant 932 9, // cuda_shared 933 10, // ptr32_sptr 934 11, // ptr32_uptr 935 12 // ptr64 936 }; 937 return &FakeAddrSpaceMap; 938 } else { 939 return &T.getAddressSpaceMap(); 940 } 941 } 942 943 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI, 944 const LangOptions &LangOpts) { 945 switch (LangOpts.getAddressSpaceMapMangling()) { 946 case LangOptions::ASMM_Target: 947 return TI.useAddressSpaceMapMangling(); 948 case LangOptions::ASMM_On: 949 return true; 950 case LangOptions::ASMM_Off: 951 return false; 952 } 953 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything."); 954 } 955 956 ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM, 957 IdentifierTable &idents, SelectorTable &sels, 958 Builtin::Context &builtins) 959 : ConstantArrayTypes(this_()), FunctionProtoTypes(this_()), 960 TemplateSpecializationTypes(this_()), 961 DependentTemplateSpecializationTypes(this_()), AutoTypes(this_()), 962 SubstTemplateTemplateParmPacks(this_()), 963 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts), 964 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)), 965 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles, 966 LangOpts.XRayNeverInstrumentFiles, 967 LangOpts.XRayAttrListFiles, SM)), 968 PrintingPolicy(LOpts), Idents(idents), Selectors(sels), 969 BuiltinInfo(builtins), DeclarationNames(*this), Comments(SM), 970 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), 971 CompCategories(this_()), LastSDM(nullptr, 0) { 972 TUDecl = TranslationUnitDecl::Create(*this); 973 TraversalScope = {TUDecl}; 974 } 975 976 ASTContext::~ASTContext() { 977 // Release the DenseMaps associated with DeclContext objects. 978 // FIXME: Is this the ideal solution? 979 ReleaseDeclContextMaps(); 980 981 // Call all of the deallocation functions on all of their targets. 982 for (auto &Pair : Deallocations) 983 (Pair.first)(Pair.second); 984 985 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed 986 // because they can contain DenseMaps. 987 for (llvm::DenseMap<const ObjCContainerDecl*, 988 const ASTRecordLayout*>::iterator 989 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) 990 // Increment in loop to prevent using deallocated memory. 991 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second)) 992 R->Destroy(*this); 993 994 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator 995 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) { 996 // Increment in loop to prevent using deallocated memory. 997 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second)) 998 R->Destroy(*this); 999 } 1000 1001 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(), 1002 AEnd = DeclAttrs.end(); 1003 A != AEnd; ++A) 1004 A->second->~AttrVec(); 1005 1006 for (const auto &Value : ModuleInitializers) 1007 Value.second->~PerModuleInitializers(); 1008 } 1009 1010 void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) { 1011 TraversalScope = TopLevelDecls; 1012 getParentMapContext().clear(); 1013 } 1014 1015 void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const { 1016 Deallocations.push_back({Callback, Data}); 1017 } 1018 1019 void 1020 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) { 1021 ExternalSource = std::move(Source); 1022 } 1023 1024 void ASTContext::PrintStats() const { 1025 llvm::errs() << "\n*** AST Context Stats:\n"; 1026 llvm::errs() << " " << Types.size() << " types total.\n"; 1027 1028 unsigned counts[] = { 1029 #define TYPE(Name, Parent) 0, 1030 #define ABSTRACT_TYPE(Name, Parent) 1031 #include "clang/AST/TypeNodes.inc" 1032 0 // Extra 1033 }; 1034 1035 for (unsigned i = 0, e = Types.size(); i != e; ++i) { 1036 Type *T = Types[i]; 1037 counts[(unsigned)T->getTypeClass()]++; 1038 } 1039 1040 unsigned Idx = 0; 1041 unsigned TotalBytes = 0; 1042 #define TYPE(Name, Parent) \ 1043 if (counts[Idx]) \ 1044 llvm::errs() << " " << counts[Idx] << " " << #Name \ 1045 << " types, " << sizeof(Name##Type) << " each " \ 1046 << "(" << counts[Idx] * sizeof(Name##Type) \ 1047 << " bytes)\n"; \ 1048 TotalBytes += counts[Idx] * sizeof(Name##Type); \ 1049 ++Idx; 1050 #define ABSTRACT_TYPE(Name, Parent) 1051 #include "clang/AST/TypeNodes.inc" 1052 1053 llvm::errs() << "Total bytes = " << TotalBytes << "\n"; 1054 1055 // Implicit special member functions. 1056 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/" 1057 << NumImplicitDefaultConstructors 1058 << " implicit default constructors created\n"; 1059 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/" 1060 << NumImplicitCopyConstructors 1061 << " implicit copy constructors created\n"; 1062 if (getLangOpts().CPlusPlus) 1063 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/" 1064 << NumImplicitMoveConstructors 1065 << " implicit move constructors created\n"; 1066 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/" 1067 << NumImplicitCopyAssignmentOperators 1068 << " implicit copy assignment operators created\n"; 1069 if (getLangOpts().CPlusPlus) 1070 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/" 1071 << NumImplicitMoveAssignmentOperators 1072 << " implicit move assignment operators created\n"; 1073 llvm::errs() << NumImplicitDestructorsDeclared << "/" 1074 << NumImplicitDestructors 1075 << " implicit destructors created\n"; 1076 1077 if (ExternalSource) { 1078 llvm::errs() << "\n"; 1079 ExternalSource->PrintStats(); 1080 } 1081 1082 BumpAlloc.PrintStats(); 1083 } 1084 1085 void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M, 1086 bool NotifyListeners) { 1087 if (NotifyListeners) 1088 if (auto *Listener = getASTMutationListener()) 1089 Listener->RedefinedHiddenDefinition(ND, M); 1090 1091 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M); 1092 } 1093 1094 void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) { 1095 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl())); 1096 if (It == MergedDefModules.end()) 1097 return; 1098 1099 auto &Merged = It->second; 1100 llvm::DenseSet<Module*> Found; 1101 for (Module *&M : Merged) 1102 if (!Found.insert(M).second) 1103 M = nullptr; 1104 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end()); 1105 } 1106 1107 ArrayRef<Module *> 1108 ASTContext::getModulesWithMergedDefinition(const NamedDecl *Def) { 1109 auto MergedIt = 1110 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl())); 1111 if (MergedIt == MergedDefModules.end()) 1112 return None; 1113 return MergedIt->second; 1114 } 1115 1116 void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) { 1117 if (LazyInitializers.empty()) 1118 return; 1119 1120 auto *Source = Ctx.getExternalSource(); 1121 assert(Source && "lazy initializers but no external source"); 1122 1123 auto LazyInits = std::move(LazyInitializers); 1124 LazyInitializers.clear(); 1125 1126 for (auto ID : LazyInits) 1127 Initializers.push_back(Source->GetExternalDecl(ID)); 1128 1129 assert(LazyInitializers.empty() && 1130 "GetExternalDecl for lazy module initializer added more inits"); 1131 } 1132 1133 void ASTContext::addModuleInitializer(Module *M, Decl *D) { 1134 // One special case: if we add a module initializer that imports another 1135 // module, and that module's only initializer is an ImportDecl, simplify. 1136 if (const auto *ID = dyn_cast<ImportDecl>(D)) { 1137 auto It = ModuleInitializers.find(ID->getImportedModule()); 1138 1139 // Maybe the ImportDecl does nothing at all. (Common case.) 1140 if (It == ModuleInitializers.end()) 1141 return; 1142 1143 // Maybe the ImportDecl only imports another ImportDecl. 1144 auto &Imported = *It->second; 1145 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) { 1146 Imported.resolve(*this); 1147 auto *OnlyDecl = Imported.Initializers.front(); 1148 if (isa<ImportDecl>(OnlyDecl)) 1149 D = OnlyDecl; 1150 } 1151 } 1152 1153 auto *&Inits = ModuleInitializers[M]; 1154 if (!Inits) 1155 Inits = new (*this) PerModuleInitializers; 1156 Inits->Initializers.push_back(D); 1157 } 1158 1159 void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) { 1160 auto *&Inits = ModuleInitializers[M]; 1161 if (!Inits) 1162 Inits = new (*this) PerModuleInitializers; 1163 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(), 1164 IDs.begin(), IDs.end()); 1165 } 1166 1167 ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) { 1168 auto It = ModuleInitializers.find(M); 1169 if (It == ModuleInitializers.end()) 1170 return None; 1171 1172 auto *Inits = It->second; 1173 Inits->resolve(*this); 1174 return Inits->Initializers; 1175 } 1176 1177 ExternCContextDecl *ASTContext::getExternCContextDecl() const { 1178 if (!ExternCContext) 1179 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl()); 1180 1181 return ExternCContext; 1182 } 1183 1184 BuiltinTemplateDecl * 1185 ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK, 1186 const IdentifierInfo *II) const { 1187 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK); 1188 BuiltinTemplate->setImplicit(); 1189 TUDecl->addDecl(BuiltinTemplate); 1190 1191 return BuiltinTemplate; 1192 } 1193 1194 BuiltinTemplateDecl * 1195 ASTContext::getMakeIntegerSeqDecl() const { 1196 if (!MakeIntegerSeqDecl) 1197 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq, 1198 getMakeIntegerSeqName()); 1199 return MakeIntegerSeqDecl; 1200 } 1201 1202 BuiltinTemplateDecl * 1203 ASTContext::getTypePackElementDecl() const { 1204 if (!TypePackElementDecl) 1205 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element, 1206 getTypePackElementName()); 1207 return TypePackElementDecl; 1208 } 1209 1210 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name, 1211 RecordDecl::TagKind TK) const { 1212 SourceLocation Loc; 1213 RecordDecl *NewDecl; 1214 if (getLangOpts().CPlusPlus) 1215 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, 1216 Loc, &Idents.get(Name)); 1217 else 1218 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc, 1219 &Idents.get(Name)); 1220 NewDecl->setImplicit(); 1221 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit( 1222 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default)); 1223 return NewDecl; 1224 } 1225 1226 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T, 1227 StringRef Name) const { 1228 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); 1229 TypedefDecl *NewDecl = TypedefDecl::Create( 1230 const_cast<ASTContext &>(*this), getTranslationUnitDecl(), 1231 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo); 1232 NewDecl->setImplicit(); 1233 return NewDecl; 1234 } 1235 1236 TypedefDecl *ASTContext::getInt128Decl() const { 1237 if (!Int128Decl) 1238 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t"); 1239 return Int128Decl; 1240 } 1241 1242 TypedefDecl *ASTContext::getUInt128Decl() const { 1243 if (!UInt128Decl) 1244 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t"); 1245 return UInt128Decl; 1246 } 1247 1248 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) { 1249 auto *Ty = new (*this, TypeAlignment) BuiltinType(K); 1250 R = CanQualType::CreateUnsafe(QualType(Ty, 0)); 1251 Types.push_back(Ty); 1252 } 1253 1254 void ASTContext::InitBuiltinTypes(const TargetInfo &Target, 1255 const TargetInfo *AuxTarget) { 1256 assert((!this->Target || this->Target == &Target) && 1257 "Incorrect target reinitialization"); 1258 assert(VoidTy.isNull() && "Context reinitialized?"); 1259 1260 this->Target = &Target; 1261 this->AuxTarget = AuxTarget; 1262 1263 ABI.reset(createCXXABI(Target)); 1264 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts); 1265 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts); 1266 1267 // C99 6.2.5p19. 1268 InitBuiltinType(VoidTy, BuiltinType::Void); 1269 1270 // C99 6.2.5p2. 1271 InitBuiltinType(BoolTy, BuiltinType::Bool); 1272 // C99 6.2.5p3. 1273 if (LangOpts.CharIsSigned) 1274 InitBuiltinType(CharTy, BuiltinType::Char_S); 1275 else 1276 InitBuiltinType(CharTy, BuiltinType::Char_U); 1277 // C99 6.2.5p4. 1278 InitBuiltinType(SignedCharTy, BuiltinType::SChar); 1279 InitBuiltinType(ShortTy, BuiltinType::Short); 1280 InitBuiltinType(IntTy, BuiltinType::Int); 1281 InitBuiltinType(LongTy, BuiltinType::Long); 1282 InitBuiltinType(LongLongTy, BuiltinType::LongLong); 1283 1284 // C99 6.2.5p6. 1285 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar); 1286 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort); 1287 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt); 1288 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong); 1289 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong); 1290 1291 // C99 6.2.5p10. 1292 InitBuiltinType(FloatTy, BuiltinType::Float); 1293 InitBuiltinType(DoubleTy, BuiltinType::Double); 1294 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble); 1295 1296 // GNU extension, __float128 for IEEE quadruple precision 1297 InitBuiltinType(Float128Ty, BuiltinType::Float128); 1298 1299 // C11 extension ISO/IEC TS 18661-3 1300 InitBuiltinType(Float16Ty, BuiltinType::Float16); 1301 1302 // ISO/IEC JTC1 SC22 WG14 N1169 Extension 1303 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum); 1304 InitBuiltinType(AccumTy, BuiltinType::Accum); 1305 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum); 1306 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum); 1307 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum); 1308 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum); 1309 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract); 1310 InitBuiltinType(FractTy, BuiltinType::Fract); 1311 InitBuiltinType(LongFractTy, BuiltinType::LongFract); 1312 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract); 1313 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract); 1314 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract); 1315 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum); 1316 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum); 1317 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum); 1318 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum); 1319 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum); 1320 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum); 1321 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract); 1322 InitBuiltinType(SatFractTy, BuiltinType::SatFract); 1323 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract); 1324 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract); 1325 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract); 1326 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract); 1327 1328 // GNU extension, 128-bit integers. 1329 InitBuiltinType(Int128Ty, BuiltinType::Int128); 1330 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128); 1331 1332 // C++ 3.9.1p5 1333 if (TargetInfo::isTypeSigned(Target.getWCharType())) 1334 InitBuiltinType(WCharTy, BuiltinType::WChar_S); 1335 else // -fshort-wchar makes wchar_t be unsigned. 1336 InitBuiltinType(WCharTy, BuiltinType::WChar_U); 1337 if (LangOpts.CPlusPlus && LangOpts.WChar) 1338 WideCharTy = WCharTy; 1339 else { 1340 // C99 (or C++ using -fno-wchar). 1341 WideCharTy = getFromTargetType(Target.getWCharType()); 1342 } 1343 1344 WIntTy = getFromTargetType(Target.getWIntType()); 1345 1346 // C++20 (proposed) 1347 InitBuiltinType(Char8Ty, BuiltinType::Char8); 1348 1349 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 1350 InitBuiltinType(Char16Ty, BuiltinType::Char16); 1351 else // C99 1352 Char16Ty = getFromTargetType(Target.getChar16Type()); 1353 1354 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 1355 InitBuiltinType(Char32Ty, BuiltinType::Char32); 1356 else // C99 1357 Char32Ty = getFromTargetType(Target.getChar32Type()); 1358 1359 // Placeholder type for type-dependent expressions whose type is 1360 // completely unknown. No code should ever check a type against 1361 // DependentTy and users should never see it; however, it is here to 1362 // help diagnose failures to properly check for type-dependent 1363 // expressions. 1364 InitBuiltinType(DependentTy, BuiltinType::Dependent); 1365 1366 // Placeholder type for functions. 1367 InitBuiltinType(OverloadTy, BuiltinType::Overload); 1368 1369 // Placeholder type for bound members. 1370 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember); 1371 1372 // Placeholder type for pseudo-objects. 1373 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject); 1374 1375 // "any" type; useful for debugger-like clients. 1376 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny); 1377 1378 // Placeholder type for unbridged ARC casts. 1379 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast); 1380 1381 // Placeholder type for builtin functions. 1382 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn); 1383 1384 // Placeholder type for OMP array sections. 1385 if (LangOpts.OpenMP) { 1386 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection); 1387 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping); 1388 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator); 1389 } 1390 if (LangOpts.MatrixTypes) 1391 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx); 1392 1393 // C99 6.2.5p11. 1394 FloatComplexTy = getComplexType(FloatTy); 1395 DoubleComplexTy = getComplexType(DoubleTy); 1396 LongDoubleComplexTy = getComplexType(LongDoubleTy); 1397 Float128ComplexTy = getComplexType(Float128Ty); 1398 1399 // Builtin types for 'id', 'Class', and 'SEL'. 1400 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId); 1401 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass); 1402 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel); 1403 1404 if (LangOpts.OpenCL) { 1405 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 1406 InitBuiltinType(SingletonId, BuiltinType::Id); 1407 #include "clang/Basic/OpenCLImageTypes.def" 1408 1409 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler); 1410 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent); 1411 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent); 1412 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue); 1413 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID); 1414 1415 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 1416 InitBuiltinType(Id##Ty, BuiltinType::Id); 1417 #include "clang/Basic/OpenCLExtensionTypes.def" 1418 } 1419 1420 if (Target.hasAArch64SVETypes()) { 1421 #define SVE_TYPE(Name, Id, SingletonId) \ 1422 InitBuiltinType(SingletonId, BuiltinType::Id); 1423 #include "clang/Basic/AArch64SVEACLETypes.def" 1424 } 1425 1426 if (Target.getTriple().isPPC64() && Target.hasFeature("mma")) { 1427 #define PPC_MMA_VECTOR_TYPE(Name, Id, Size) \ 1428 InitBuiltinType(Id##Ty, BuiltinType::Id); 1429 #include "clang/Basic/PPCTypes.def" 1430 } 1431 1432 // Builtin type for __objc_yes and __objc_no 1433 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ? 1434 SignedCharTy : BoolTy); 1435 1436 ObjCConstantStringType = QualType(); 1437 1438 ObjCSuperType = QualType(); 1439 1440 // void * type 1441 if (LangOpts.OpenCLVersion >= 200) { 1442 auto Q = VoidTy.getQualifiers(); 1443 Q.setAddressSpace(LangAS::opencl_generic); 1444 VoidPtrTy = getPointerType(getCanonicalType( 1445 getQualifiedType(VoidTy.getUnqualifiedType(), Q))); 1446 } else { 1447 VoidPtrTy = getPointerType(VoidTy); 1448 } 1449 1450 // nullptr type (C++0x 2.14.7) 1451 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr); 1452 1453 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16 1454 InitBuiltinType(HalfTy, BuiltinType::Half); 1455 1456 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16); 1457 1458 // Builtin type used to help define __builtin_va_list. 1459 VaListTagDecl = nullptr; 1460 1461 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls. 1462 if (LangOpts.MicrosoftExt || LangOpts.Borland) { 1463 MSGuidTagDecl = buildImplicitRecord("_GUID"); 1464 TUDecl->addDecl(MSGuidTagDecl); 1465 } 1466 } 1467 1468 DiagnosticsEngine &ASTContext::getDiagnostics() const { 1469 return SourceMgr.getDiagnostics(); 1470 } 1471 1472 AttrVec& ASTContext::getDeclAttrs(const Decl *D) { 1473 AttrVec *&Result = DeclAttrs[D]; 1474 if (!Result) { 1475 void *Mem = Allocate(sizeof(AttrVec)); 1476 Result = new (Mem) AttrVec; 1477 } 1478 1479 return *Result; 1480 } 1481 1482 /// Erase the attributes corresponding to the given declaration. 1483 void ASTContext::eraseDeclAttrs(const Decl *D) { 1484 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D); 1485 if (Pos != DeclAttrs.end()) { 1486 Pos->second->~AttrVec(); 1487 DeclAttrs.erase(Pos); 1488 } 1489 } 1490 1491 // FIXME: Remove ? 1492 MemberSpecializationInfo * 1493 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) { 1494 assert(Var->isStaticDataMember() && "Not a static data member"); 1495 return getTemplateOrSpecializationInfo(Var) 1496 .dyn_cast<MemberSpecializationInfo *>(); 1497 } 1498 1499 ASTContext::TemplateOrSpecializationInfo 1500 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) { 1501 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos = 1502 TemplateOrInstantiation.find(Var); 1503 if (Pos == TemplateOrInstantiation.end()) 1504 return {}; 1505 1506 return Pos->second; 1507 } 1508 1509 void 1510 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, 1511 TemplateSpecializationKind TSK, 1512 SourceLocation PointOfInstantiation) { 1513 assert(Inst->isStaticDataMember() && "Not a static data member"); 1514 assert(Tmpl->isStaticDataMember() && "Not a static data member"); 1515 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo( 1516 Tmpl, TSK, PointOfInstantiation)); 1517 } 1518 1519 void 1520 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst, 1521 TemplateOrSpecializationInfo TSI) { 1522 assert(!TemplateOrInstantiation[Inst] && 1523 "Already noted what the variable was instantiated from"); 1524 TemplateOrInstantiation[Inst] = TSI; 1525 } 1526 1527 NamedDecl * 1528 ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) { 1529 auto Pos = InstantiatedFromUsingDecl.find(UUD); 1530 if (Pos == InstantiatedFromUsingDecl.end()) 1531 return nullptr; 1532 1533 return Pos->second; 1534 } 1535 1536 void 1537 ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) { 1538 assert((isa<UsingDecl>(Pattern) || 1539 isa<UnresolvedUsingValueDecl>(Pattern) || 1540 isa<UnresolvedUsingTypenameDecl>(Pattern)) && 1541 "pattern decl is not a using decl"); 1542 assert((isa<UsingDecl>(Inst) || 1543 isa<UnresolvedUsingValueDecl>(Inst) || 1544 isa<UnresolvedUsingTypenameDecl>(Inst)) && 1545 "instantiation did not produce a using decl"); 1546 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists"); 1547 InstantiatedFromUsingDecl[Inst] = Pattern; 1548 } 1549 1550 UsingShadowDecl * 1551 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) { 1552 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos 1553 = InstantiatedFromUsingShadowDecl.find(Inst); 1554 if (Pos == InstantiatedFromUsingShadowDecl.end()) 1555 return nullptr; 1556 1557 return Pos->second; 1558 } 1559 1560 void 1561 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, 1562 UsingShadowDecl *Pattern) { 1563 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists"); 1564 InstantiatedFromUsingShadowDecl[Inst] = Pattern; 1565 } 1566 1567 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) { 1568 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos 1569 = InstantiatedFromUnnamedFieldDecl.find(Field); 1570 if (Pos == InstantiatedFromUnnamedFieldDecl.end()) 1571 return nullptr; 1572 1573 return Pos->second; 1574 } 1575 1576 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, 1577 FieldDecl *Tmpl) { 1578 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed"); 1579 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed"); 1580 assert(!InstantiatedFromUnnamedFieldDecl[Inst] && 1581 "Already noted what unnamed field was instantiated from"); 1582 1583 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl; 1584 } 1585 1586 ASTContext::overridden_cxx_method_iterator 1587 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const { 1588 return overridden_methods(Method).begin(); 1589 } 1590 1591 ASTContext::overridden_cxx_method_iterator 1592 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const { 1593 return overridden_methods(Method).end(); 1594 } 1595 1596 unsigned 1597 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const { 1598 auto Range = overridden_methods(Method); 1599 return Range.end() - Range.begin(); 1600 } 1601 1602 ASTContext::overridden_method_range 1603 ASTContext::overridden_methods(const CXXMethodDecl *Method) const { 1604 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos = 1605 OverriddenMethods.find(Method->getCanonicalDecl()); 1606 if (Pos == OverriddenMethods.end()) 1607 return overridden_method_range(nullptr, nullptr); 1608 return overridden_method_range(Pos->second.begin(), Pos->second.end()); 1609 } 1610 1611 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method, 1612 const CXXMethodDecl *Overridden) { 1613 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl()); 1614 OverriddenMethods[Method].push_back(Overridden); 1615 } 1616 1617 void ASTContext::getOverriddenMethods( 1618 const NamedDecl *D, 1619 SmallVectorImpl<const NamedDecl *> &Overridden) const { 1620 assert(D); 1621 1622 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) { 1623 Overridden.append(overridden_methods_begin(CXXMethod), 1624 overridden_methods_end(CXXMethod)); 1625 return; 1626 } 1627 1628 const auto *Method = dyn_cast<ObjCMethodDecl>(D); 1629 if (!Method) 1630 return; 1631 1632 SmallVector<const ObjCMethodDecl *, 8> OverDecls; 1633 Method->getOverriddenMethods(OverDecls); 1634 Overridden.append(OverDecls.begin(), OverDecls.end()); 1635 } 1636 1637 void ASTContext::addedLocalImportDecl(ImportDecl *Import) { 1638 assert(!Import->getNextLocalImport() && 1639 "Import declaration already in the chain"); 1640 assert(!Import->isFromASTFile() && "Non-local import declaration"); 1641 if (!FirstLocalImport) { 1642 FirstLocalImport = Import; 1643 LastLocalImport = Import; 1644 return; 1645 } 1646 1647 LastLocalImport->setNextLocalImport(Import); 1648 LastLocalImport = Import; 1649 } 1650 1651 //===----------------------------------------------------------------------===// 1652 // Type Sizing and Analysis 1653 //===----------------------------------------------------------------------===// 1654 1655 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified 1656 /// scalar floating point type. 1657 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const { 1658 switch (T->castAs<BuiltinType>()->getKind()) { 1659 default: 1660 llvm_unreachable("Not a floating point type!"); 1661 case BuiltinType::BFloat16: 1662 return Target->getBFloat16Format(); 1663 case BuiltinType::Float16: 1664 case BuiltinType::Half: 1665 return Target->getHalfFormat(); 1666 case BuiltinType::Float: return Target->getFloatFormat(); 1667 case BuiltinType::Double: return Target->getDoubleFormat(); 1668 case BuiltinType::LongDouble: 1669 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) 1670 return AuxTarget->getLongDoubleFormat(); 1671 return Target->getLongDoubleFormat(); 1672 case BuiltinType::Float128: 1673 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) 1674 return AuxTarget->getFloat128Format(); 1675 return Target->getFloat128Format(); 1676 } 1677 } 1678 1679 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const { 1680 unsigned Align = Target->getCharWidth(); 1681 1682 bool UseAlignAttrOnly = false; 1683 if (unsigned AlignFromAttr = D->getMaxAlignment()) { 1684 Align = AlignFromAttr; 1685 1686 // __attribute__((aligned)) can increase or decrease alignment 1687 // *except* on a struct or struct member, where it only increases 1688 // alignment unless 'packed' is also specified. 1689 // 1690 // It is an error for alignas to decrease alignment, so we can 1691 // ignore that possibility; Sema should diagnose it. 1692 if (isa<FieldDecl>(D)) { 1693 UseAlignAttrOnly = D->hasAttr<PackedAttr>() || 1694 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 1695 } else { 1696 UseAlignAttrOnly = true; 1697 } 1698 } 1699 else if (isa<FieldDecl>(D)) 1700 UseAlignAttrOnly = 1701 D->hasAttr<PackedAttr>() || 1702 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 1703 1704 // If we're using the align attribute only, just ignore everything 1705 // else about the declaration and its type. 1706 if (UseAlignAttrOnly) { 1707 // do nothing 1708 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) { 1709 QualType T = VD->getType(); 1710 if (const auto *RT = T->getAs<ReferenceType>()) { 1711 if (ForAlignof) 1712 T = RT->getPointeeType(); 1713 else 1714 T = getPointerType(RT->getPointeeType()); 1715 } 1716 QualType BaseT = getBaseElementType(T); 1717 if (T->isFunctionType()) 1718 Align = getTypeInfoImpl(T.getTypePtr()).Align; 1719 else if (!BaseT->isIncompleteType()) { 1720 // Adjust alignments of declarations with array type by the 1721 // large-array alignment on the target. 1722 if (const ArrayType *arrayType = getAsArrayType(T)) { 1723 unsigned MinWidth = Target->getLargeArrayMinWidth(); 1724 if (!ForAlignof && MinWidth) { 1725 if (isa<VariableArrayType>(arrayType)) 1726 Align = std::max(Align, Target->getLargeArrayAlign()); 1727 else if (isa<ConstantArrayType>(arrayType) && 1728 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType))) 1729 Align = std::max(Align, Target->getLargeArrayAlign()); 1730 } 1731 } 1732 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr())); 1733 if (BaseT.getQualifiers().hasUnaligned()) 1734 Align = Target->getCharWidth(); 1735 if (const auto *VD = dyn_cast<VarDecl>(D)) { 1736 if (VD->hasGlobalStorage() && !ForAlignof) { 1737 uint64_t TypeSize = getTypeSize(T.getTypePtr()); 1738 Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize)); 1739 } 1740 } 1741 } 1742 1743 // Fields can be subject to extra alignment constraints, like if 1744 // the field is packed, the struct is packed, or the struct has a 1745 // a max-field-alignment constraint (#pragma pack). So calculate 1746 // the actual alignment of the field within the struct, and then 1747 // (as we're expected to) constrain that by the alignment of the type. 1748 if (const auto *Field = dyn_cast<FieldDecl>(VD)) { 1749 const RecordDecl *Parent = Field->getParent(); 1750 // We can only produce a sensible answer if the record is valid. 1751 if (!Parent->isInvalidDecl()) { 1752 const ASTRecordLayout &Layout = getASTRecordLayout(Parent); 1753 1754 // Start with the record's overall alignment. 1755 unsigned FieldAlign = toBits(Layout.getAlignment()); 1756 1757 // Use the GCD of that and the offset within the record. 1758 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex()); 1759 if (Offset > 0) { 1760 // Alignment is always a power of 2, so the GCD will be a power of 2, 1761 // which means we get to do this crazy thing instead of Euclid's. 1762 uint64_t LowBitOfOffset = Offset & (~Offset + 1); 1763 if (LowBitOfOffset < FieldAlign) 1764 FieldAlign = static_cast<unsigned>(LowBitOfOffset); 1765 } 1766 1767 Align = std::min(Align, FieldAlign); 1768 } 1769 } 1770 } 1771 1772 return toCharUnitsFromBits(Align); 1773 } 1774 1775 CharUnits ASTContext::getExnObjectAlignment() const { 1776 return toCharUnitsFromBits(Target->getExnObjectAlignment()); 1777 } 1778 1779 // getTypeInfoDataSizeInChars - Return the size of a type, in 1780 // chars. If the type is a record, its data size is returned. This is 1781 // the size of the memcpy that's performed when assigning this type 1782 // using a trivial copy/move assignment operator. 1783 TypeInfoChars ASTContext::getTypeInfoDataSizeInChars(QualType T) const { 1784 TypeInfoChars Info = getTypeInfoInChars(T); 1785 1786 // In C++, objects can sometimes be allocated into the tail padding 1787 // of a base-class subobject. We decide whether that's possible 1788 // during class layout, so here we can just trust the layout results. 1789 if (getLangOpts().CPlusPlus) { 1790 if (const auto *RT = T->getAs<RecordType>()) { 1791 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl()); 1792 Info.Width = layout.getDataSize(); 1793 } 1794 } 1795 1796 return Info; 1797 } 1798 1799 /// getConstantArrayInfoInChars - Performing the computation in CharUnits 1800 /// instead of in bits prevents overflowing the uint64_t for some large arrays. 1801 TypeInfoChars 1802 static getConstantArrayInfoInChars(const ASTContext &Context, 1803 const ConstantArrayType *CAT) { 1804 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType()); 1805 uint64_t Size = CAT->getSize().getZExtValue(); 1806 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <= 1807 (uint64_t)(-1)/Size) && 1808 "Overflow in array type char size evaluation"); 1809 uint64_t Width = EltInfo.Width.getQuantity() * Size; 1810 unsigned Align = EltInfo.Align.getQuantity(); 1811 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() || 1812 Context.getTargetInfo().getPointerWidth(0) == 64) 1813 Width = llvm::alignTo(Width, Align); 1814 return TypeInfoChars(CharUnits::fromQuantity(Width), 1815 CharUnits::fromQuantity(Align), 1816 EltInfo.AlignIsRequired); 1817 } 1818 1819 TypeInfoChars ASTContext::getTypeInfoInChars(const Type *T) const { 1820 if (const auto *CAT = dyn_cast<ConstantArrayType>(T)) 1821 return getConstantArrayInfoInChars(*this, CAT); 1822 TypeInfo Info = getTypeInfo(T); 1823 return TypeInfoChars(toCharUnitsFromBits(Info.Width), 1824 toCharUnitsFromBits(Info.Align), 1825 Info.AlignIsRequired); 1826 } 1827 1828 TypeInfoChars ASTContext::getTypeInfoInChars(QualType T) const { 1829 return getTypeInfoInChars(T.getTypePtr()); 1830 } 1831 1832 bool ASTContext::isAlignmentRequired(const Type *T) const { 1833 return getTypeInfo(T).AlignIsRequired; 1834 } 1835 1836 bool ASTContext::isAlignmentRequired(QualType T) const { 1837 return isAlignmentRequired(T.getTypePtr()); 1838 } 1839 1840 unsigned ASTContext::getTypeAlignIfKnown(QualType T, 1841 bool NeedsPreferredAlignment) const { 1842 // An alignment on a typedef overrides anything else. 1843 if (const auto *TT = T->getAs<TypedefType>()) 1844 if (unsigned Align = TT->getDecl()->getMaxAlignment()) 1845 return Align; 1846 1847 // If we have an (array of) complete type, we're done. 1848 T = getBaseElementType(T); 1849 if (!T->isIncompleteType()) 1850 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T); 1851 1852 // If we had an array type, its element type might be a typedef 1853 // type with an alignment attribute. 1854 if (const auto *TT = T->getAs<TypedefType>()) 1855 if (unsigned Align = TT->getDecl()->getMaxAlignment()) 1856 return Align; 1857 1858 // Otherwise, see if the declaration of the type had an attribute. 1859 if (const auto *TT = T->getAs<TagType>()) 1860 return TT->getDecl()->getMaxAlignment(); 1861 1862 return 0; 1863 } 1864 1865 TypeInfo ASTContext::getTypeInfo(const Type *T) const { 1866 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T); 1867 if (I != MemoizedTypeInfo.end()) 1868 return I->second; 1869 1870 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup. 1871 TypeInfo TI = getTypeInfoImpl(T); 1872 MemoizedTypeInfo[T] = TI; 1873 return TI; 1874 } 1875 1876 /// getTypeInfoImpl - Return the size of the specified type, in bits. This 1877 /// method does not work on incomplete types. 1878 /// 1879 /// FIXME: Pointers into different addr spaces could have different sizes and 1880 /// alignment requirements: getPointerInfo should take an AddrSpace, this 1881 /// should take a QualType, &c. 1882 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const { 1883 uint64_t Width = 0; 1884 unsigned Align = 8; 1885 bool AlignIsRequired = false; 1886 unsigned AS = 0; 1887 switch (T->getTypeClass()) { 1888 #define TYPE(Class, Base) 1889 #define ABSTRACT_TYPE(Class, Base) 1890 #define NON_CANONICAL_TYPE(Class, Base) 1891 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 1892 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \ 1893 case Type::Class: \ 1894 assert(!T->isDependentType() && "should not see dependent types here"); \ 1895 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr()); 1896 #include "clang/AST/TypeNodes.inc" 1897 llvm_unreachable("Should not see dependent types"); 1898 1899 case Type::FunctionNoProto: 1900 case Type::FunctionProto: 1901 // GCC extension: alignof(function) = 32 bits 1902 Width = 0; 1903 Align = 32; 1904 break; 1905 1906 case Type::IncompleteArray: 1907 case Type::VariableArray: 1908 case Type::ConstantArray: { 1909 // Model non-constant sized arrays as size zero, but track the alignment. 1910 uint64_t Size = 0; 1911 if (const auto *CAT = dyn_cast<ConstantArrayType>(T)) 1912 Size = CAT->getSize().getZExtValue(); 1913 1914 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType()); 1915 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) && 1916 "Overflow in array type bit size evaluation"); 1917 Width = EltInfo.Width * Size; 1918 Align = EltInfo.Align; 1919 AlignIsRequired = EltInfo.AlignIsRequired; 1920 if (!getTargetInfo().getCXXABI().isMicrosoft() || 1921 getTargetInfo().getPointerWidth(0) == 64) 1922 Width = llvm::alignTo(Width, Align); 1923 break; 1924 } 1925 1926 case Type::ExtVector: 1927 case Type::Vector: { 1928 const auto *VT = cast<VectorType>(T); 1929 TypeInfo EltInfo = getTypeInfo(VT->getElementType()); 1930 Width = EltInfo.Width * VT->getNumElements(); 1931 Align = Width; 1932 // If the alignment is not a power of 2, round up to the next power of 2. 1933 // This happens for non-power-of-2 length vectors. 1934 if (Align & (Align-1)) { 1935 Align = llvm::NextPowerOf2(Align); 1936 Width = llvm::alignTo(Width, Align); 1937 } 1938 // Adjust the alignment based on the target max. 1939 uint64_t TargetVectorAlign = Target->getMaxVectorAlign(); 1940 if (TargetVectorAlign && TargetVectorAlign < Align) 1941 Align = TargetVectorAlign; 1942 if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) 1943 // Adjust the alignment for fixed-length SVE vectors. This is important 1944 // for non-power-of-2 vector lengths. 1945 Align = 128; 1946 else if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 1947 // Adjust the alignment for fixed-length SVE predicates. 1948 Align = 16; 1949 break; 1950 } 1951 1952 case Type::ConstantMatrix: { 1953 const auto *MT = cast<ConstantMatrixType>(T); 1954 TypeInfo ElementInfo = getTypeInfo(MT->getElementType()); 1955 // The internal layout of a matrix value is implementation defined. 1956 // Initially be ABI compatible with arrays with respect to alignment and 1957 // size. 1958 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns(); 1959 Align = ElementInfo.Align; 1960 break; 1961 } 1962 1963 case Type::Builtin: 1964 switch (cast<BuiltinType>(T)->getKind()) { 1965 default: llvm_unreachable("Unknown builtin type!"); 1966 case BuiltinType::Void: 1967 // GCC extension: alignof(void) = 8 bits. 1968 Width = 0; 1969 Align = 8; 1970 break; 1971 case BuiltinType::Bool: 1972 Width = Target->getBoolWidth(); 1973 Align = Target->getBoolAlign(); 1974 break; 1975 case BuiltinType::Char_S: 1976 case BuiltinType::Char_U: 1977 case BuiltinType::UChar: 1978 case BuiltinType::SChar: 1979 case BuiltinType::Char8: 1980 Width = Target->getCharWidth(); 1981 Align = Target->getCharAlign(); 1982 break; 1983 case BuiltinType::WChar_S: 1984 case BuiltinType::WChar_U: 1985 Width = Target->getWCharWidth(); 1986 Align = Target->getWCharAlign(); 1987 break; 1988 case BuiltinType::Char16: 1989 Width = Target->getChar16Width(); 1990 Align = Target->getChar16Align(); 1991 break; 1992 case BuiltinType::Char32: 1993 Width = Target->getChar32Width(); 1994 Align = Target->getChar32Align(); 1995 break; 1996 case BuiltinType::UShort: 1997 case BuiltinType::Short: 1998 Width = Target->getShortWidth(); 1999 Align = Target->getShortAlign(); 2000 break; 2001 case BuiltinType::UInt: 2002 case BuiltinType::Int: 2003 Width = Target->getIntWidth(); 2004 Align = Target->getIntAlign(); 2005 break; 2006 case BuiltinType::ULong: 2007 case BuiltinType::Long: 2008 Width = Target->getLongWidth(); 2009 Align = Target->getLongAlign(); 2010 break; 2011 case BuiltinType::ULongLong: 2012 case BuiltinType::LongLong: 2013 Width = Target->getLongLongWidth(); 2014 Align = Target->getLongLongAlign(); 2015 break; 2016 case BuiltinType::Int128: 2017 case BuiltinType::UInt128: 2018 Width = 128; 2019 Align = 128; // int128_t is 128-bit aligned on all targets. 2020 break; 2021 case BuiltinType::ShortAccum: 2022 case BuiltinType::UShortAccum: 2023 case BuiltinType::SatShortAccum: 2024 case BuiltinType::SatUShortAccum: 2025 Width = Target->getShortAccumWidth(); 2026 Align = Target->getShortAccumAlign(); 2027 break; 2028 case BuiltinType::Accum: 2029 case BuiltinType::UAccum: 2030 case BuiltinType::SatAccum: 2031 case BuiltinType::SatUAccum: 2032 Width = Target->getAccumWidth(); 2033 Align = Target->getAccumAlign(); 2034 break; 2035 case BuiltinType::LongAccum: 2036 case BuiltinType::ULongAccum: 2037 case BuiltinType::SatLongAccum: 2038 case BuiltinType::SatULongAccum: 2039 Width = Target->getLongAccumWidth(); 2040 Align = Target->getLongAccumAlign(); 2041 break; 2042 case BuiltinType::ShortFract: 2043 case BuiltinType::UShortFract: 2044 case BuiltinType::SatShortFract: 2045 case BuiltinType::SatUShortFract: 2046 Width = Target->getShortFractWidth(); 2047 Align = Target->getShortFractAlign(); 2048 break; 2049 case BuiltinType::Fract: 2050 case BuiltinType::UFract: 2051 case BuiltinType::SatFract: 2052 case BuiltinType::SatUFract: 2053 Width = Target->getFractWidth(); 2054 Align = Target->getFractAlign(); 2055 break; 2056 case BuiltinType::LongFract: 2057 case BuiltinType::ULongFract: 2058 case BuiltinType::SatLongFract: 2059 case BuiltinType::SatULongFract: 2060 Width = Target->getLongFractWidth(); 2061 Align = Target->getLongFractAlign(); 2062 break; 2063 case BuiltinType::BFloat16: 2064 Width = Target->getBFloat16Width(); 2065 Align = Target->getBFloat16Align(); 2066 break; 2067 case BuiltinType::Float16: 2068 case BuiltinType::Half: 2069 if (Target->hasFloat16Type() || !getLangOpts().OpenMP || 2070 !getLangOpts().OpenMPIsDevice) { 2071 Width = Target->getHalfWidth(); 2072 Align = Target->getHalfAlign(); 2073 } else { 2074 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 2075 "Expected OpenMP device compilation."); 2076 Width = AuxTarget->getHalfWidth(); 2077 Align = AuxTarget->getHalfAlign(); 2078 } 2079 break; 2080 case BuiltinType::Float: 2081 Width = Target->getFloatWidth(); 2082 Align = Target->getFloatAlign(); 2083 break; 2084 case BuiltinType::Double: 2085 Width = Target->getDoubleWidth(); 2086 Align = Target->getDoubleAlign(); 2087 break; 2088 case BuiltinType::LongDouble: 2089 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 2090 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() || 2091 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) { 2092 Width = AuxTarget->getLongDoubleWidth(); 2093 Align = AuxTarget->getLongDoubleAlign(); 2094 } else { 2095 Width = Target->getLongDoubleWidth(); 2096 Align = Target->getLongDoubleAlign(); 2097 } 2098 break; 2099 case BuiltinType::Float128: 2100 if (Target->hasFloat128Type() || !getLangOpts().OpenMP || 2101 !getLangOpts().OpenMPIsDevice) { 2102 Width = Target->getFloat128Width(); 2103 Align = Target->getFloat128Align(); 2104 } else { 2105 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 2106 "Expected OpenMP device compilation."); 2107 Width = AuxTarget->getFloat128Width(); 2108 Align = AuxTarget->getFloat128Align(); 2109 } 2110 break; 2111 case BuiltinType::NullPtr: 2112 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t) 2113 Align = Target->getPointerAlign(0); // == sizeof(void*) 2114 break; 2115 case BuiltinType::ObjCId: 2116 case BuiltinType::ObjCClass: 2117 case BuiltinType::ObjCSel: 2118 Width = Target->getPointerWidth(0); 2119 Align = Target->getPointerAlign(0); 2120 break; 2121 case BuiltinType::OCLSampler: 2122 case BuiltinType::OCLEvent: 2123 case BuiltinType::OCLClkEvent: 2124 case BuiltinType::OCLQueue: 2125 case BuiltinType::OCLReserveID: 2126 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 2127 case BuiltinType::Id: 2128 #include "clang/Basic/OpenCLImageTypes.def" 2129 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 2130 case BuiltinType::Id: 2131 #include "clang/Basic/OpenCLExtensionTypes.def" 2132 AS = getTargetAddressSpace( 2133 Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T))); 2134 Width = Target->getPointerWidth(AS); 2135 Align = Target->getPointerAlign(AS); 2136 break; 2137 // The SVE types are effectively target-specific. The length of an 2138 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple 2139 // of 128 bits. There is one predicate bit for each vector byte, so the 2140 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits. 2141 // 2142 // Because the length is only known at runtime, we use a dummy value 2143 // of 0 for the static length. The alignment values are those defined 2144 // by the Procedure Call Standard for the Arm Architecture. 2145 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \ 2146 IsSigned, IsFP, IsBF) \ 2147 case BuiltinType::Id: \ 2148 Width = 0; \ 2149 Align = 128; \ 2150 break; 2151 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \ 2152 case BuiltinType::Id: \ 2153 Width = 0; \ 2154 Align = 16; \ 2155 break; 2156 #include "clang/Basic/AArch64SVEACLETypes.def" 2157 #define PPC_MMA_VECTOR_TYPE(Name, Id, Size) \ 2158 case BuiltinType::Id: \ 2159 Width = Size; \ 2160 Align = Size; \ 2161 break; 2162 #include "clang/Basic/PPCTypes.def" 2163 } 2164 break; 2165 case Type::ObjCObjectPointer: 2166 Width = Target->getPointerWidth(0); 2167 Align = Target->getPointerAlign(0); 2168 break; 2169 case Type::BlockPointer: 2170 AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType()); 2171 Width = Target->getPointerWidth(AS); 2172 Align = Target->getPointerAlign(AS); 2173 break; 2174 case Type::LValueReference: 2175 case Type::RValueReference: 2176 // alignof and sizeof should never enter this code path here, so we go 2177 // the pointer route. 2178 AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType()); 2179 Width = Target->getPointerWidth(AS); 2180 Align = Target->getPointerAlign(AS); 2181 break; 2182 case Type::Pointer: 2183 AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType()); 2184 Width = Target->getPointerWidth(AS); 2185 Align = Target->getPointerAlign(AS); 2186 break; 2187 case Type::MemberPointer: { 2188 const auto *MPT = cast<MemberPointerType>(T); 2189 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT); 2190 Width = MPI.Width; 2191 Align = MPI.Align; 2192 break; 2193 } 2194 case Type::Complex: { 2195 // Complex types have the same alignment as their elements, but twice the 2196 // size. 2197 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType()); 2198 Width = EltInfo.Width * 2; 2199 Align = EltInfo.Align; 2200 break; 2201 } 2202 case Type::ObjCObject: 2203 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr()); 2204 case Type::Adjusted: 2205 case Type::Decayed: 2206 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr()); 2207 case Type::ObjCInterface: { 2208 const auto *ObjCI = cast<ObjCInterfaceType>(T); 2209 if (ObjCI->getDecl()->isInvalidDecl()) { 2210 Width = 8; 2211 Align = 8; 2212 break; 2213 } 2214 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 2215 Width = toBits(Layout.getSize()); 2216 Align = toBits(Layout.getAlignment()); 2217 break; 2218 } 2219 case Type::ExtInt: { 2220 const auto *EIT = cast<ExtIntType>(T); 2221 Align = 2222 std::min(static_cast<unsigned>(std::max( 2223 getCharWidth(), llvm::PowerOf2Ceil(EIT->getNumBits()))), 2224 Target->getLongLongAlign()); 2225 Width = llvm::alignTo(EIT->getNumBits(), Align); 2226 break; 2227 } 2228 case Type::Record: 2229 case Type::Enum: { 2230 const auto *TT = cast<TagType>(T); 2231 2232 if (TT->getDecl()->isInvalidDecl()) { 2233 Width = 8; 2234 Align = 8; 2235 break; 2236 } 2237 2238 if (const auto *ET = dyn_cast<EnumType>(TT)) { 2239 const EnumDecl *ED = ET->getDecl(); 2240 TypeInfo Info = 2241 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType()); 2242 if (unsigned AttrAlign = ED->getMaxAlignment()) { 2243 Info.Align = AttrAlign; 2244 Info.AlignIsRequired = true; 2245 } 2246 return Info; 2247 } 2248 2249 const auto *RT = cast<RecordType>(TT); 2250 const RecordDecl *RD = RT->getDecl(); 2251 const ASTRecordLayout &Layout = getASTRecordLayout(RD); 2252 Width = toBits(Layout.getSize()); 2253 Align = toBits(Layout.getAlignment()); 2254 AlignIsRequired = RD->hasAttr<AlignedAttr>(); 2255 break; 2256 } 2257 2258 case Type::SubstTemplateTypeParm: 2259 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)-> 2260 getReplacementType().getTypePtr()); 2261 2262 case Type::Auto: 2263 case Type::DeducedTemplateSpecialization: { 2264 const auto *A = cast<DeducedType>(T); 2265 assert(!A->getDeducedType().isNull() && 2266 "cannot request the size of an undeduced or dependent auto type"); 2267 return getTypeInfo(A->getDeducedType().getTypePtr()); 2268 } 2269 2270 case Type::Paren: 2271 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr()); 2272 2273 case Type::MacroQualified: 2274 return getTypeInfo( 2275 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr()); 2276 2277 case Type::ObjCTypeParam: 2278 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr()); 2279 2280 case Type::Typedef: { 2281 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl(); 2282 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr()); 2283 // If the typedef has an aligned attribute on it, it overrides any computed 2284 // alignment we have. This violates the GCC documentation (which says that 2285 // attribute(aligned) can only round up) but matches its implementation. 2286 if (unsigned AttrAlign = Typedef->getMaxAlignment()) { 2287 Align = AttrAlign; 2288 AlignIsRequired = true; 2289 } else { 2290 Align = Info.Align; 2291 AlignIsRequired = Info.AlignIsRequired; 2292 } 2293 Width = Info.Width; 2294 break; 2295 } 2296 2297 case Type::Elaborated: 2298 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr()); 2299 2300 case Type::Attributed: 2301 return getTypeInfo( 2302 cast<AttributedType>(T)->getEquivalentType().getTypePtr()); 2303 2304 case Type::Atomic: { 2305 // Start with the base type information. 2306 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType()); 2307 Width = Info.Width; 2308 Align = Info.Align; 2309 2310 if (!Width) { 2311 // An otherwise zero-sized type should still generate an 2312 // atomic operation. 2313 Width = Target->getCharWidth(); 2314 assert(Align); 2315 } else if (Width <= Target->getMaxAtomicPromoteWidth()) { 2316 // If the size of the type doesn't exceed the platform's max 2317 // atomic promotion width, make the size and alignment more 2318 // favorable to atomic operations: 2319 2320 // Round the size up to a power of 2. 2321 if (!llvm::isPowerOf2_64(Width)) 2322 Width = llvm::NextPowerOf2(Width); 2323 2324 // Set the alignment equal to the size. 2325 Align = static_cast<unsigned>(Width); 2326 } 2327 } 2328 break; 2329 2330 case Type::Pipe: 2331 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global)); 2332 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global)); 2333 break; 2334 } 2335 2336 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2"); 2337 return TypeInfo(Width, Align, AlignIsRequired); 2338 } 2339 2340 unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const { 2341 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T); 2342 if (I != MemoizedUnadjustedAlign.end()) 2343 return I->second; 2344 2345 unsigned UnadjustedAlign; 2346 if (const auto *RT = T->getAs<RecordType>()) { 2347 const RecordDecl *RD = RT->getDecl(); 2348 const ASTRecordLayout &Layout = getASTRecordLayout(RD); 2349 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment()); 2350 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) { 2351 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 2352 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment()); 2353 } else { 2354 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType()); 2355 } 2356 2357 MemoizedUnadjustedAlign[T] = UnadjustedAlign; 2358 return UnadjustedAlign; 2359 } 2360 2361 unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const { 2362 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign(); 2363 return SimdAlign; 2364 } 2365 2366 /// toCharUnitsFromBits - Convert a size in bits to a size in characters. 2367 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const { 2368 return CharUnits::fromQuantity(BitSize / getCharWidth()); 2369 } 2370 2371 /// toBits - Convert a size in characters to a size in characters. 2372 int64_t ASTContext::toBits(CharUnits CharSize) const { 2373 return CharSize.getQuantity() * getCharWidth(); 2374 } 2375 2376 /// getTypeSizeInChars - Return the size of the specified type, in characters. 2377 /// This method does not work on incomplete types. 2378 CharUnits ASTContext::getTypeSizeInChars(QualType T) const { 2379 return getTypeInfoInChars(T).Width; 2380 } 2381 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const { 2382 return getTypeInfoInChars(T).Width; 2383 } 2384 2385 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in 2386 /// characters. This method does not work on incomplete types. 2387 CharUnits ASTContext::getTypeAlignInChars(QualType T) const { 2388 return toCharUnitsFromBits(getTypeAlign(T)); 2389 } 2390 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const { 2391 return toCharUnitsFromBits(getTypeAlign(T)); 2392 } 2393 2394 /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a 2395 /// type, in characters, before alignment adustments. This method does 2396 /// not work on incomplete types. 2397 CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const { 2398 return toCharUnitsFromBits(getTypeUnadjustedAlign(T)); 2399 } 2400 CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const { 2401 return toCharUnitsFromBits(getTypeUnadjustedAlign(T)); 2402 } 2403 2404 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified 2405 /// type for the current target in bits. This can be different than the ABI 2406 /// alignment in cases where it is beneficial for performance or backwards 2407 /// compatibility preserving to overalign a data type. (Note: despite the name, 2408 /// the preferred alignment is ABI-impacting, and not an optimization.) 2409 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const { 2410 TypeInfo TI = getTypeInfo(T); 2411 unsigned ABIAlign = TI.Align; 2412 2413 T = T->getBaseElementTypeUnsafe(); 2414 2415 // The preferred alignment of member pointers is that of a pointer. 2416 if (T->isMemberPointerType()) 2417 return getPreferredTypeAlign(getPointerDiffType().getTypePtr()); 2418 2419 if (!Target->allowsLargerPreferedTypeAlignment()) 2420 return ABIAlign; 2421 2422 if (const auto *RT = T->getAs<RecordType>()) { 2423 if (TI.AlignIsRequired || RT->getDecl()->isInvalidDecl()) 2424 return ABIAlign; 2425 2426 unsigned PreferredAlign = static_cast<unsigned>( 2427 toBits(getASTRecordLayout(RT->getDecl()).PreferredAlignment)); 2428 assert(PreferredAlign >= ABIAlign && 2429 "PreferredAlign should be at least as large as ABIAlign."); 2430 return PreferredAlign; 2431 } 2432 2433 // Double (and, for targets supporting AIX `power` alignment, long double) and 2434 // long long should be naturally aligned (despite requiring less alignment) if 2435 // possible. 2436 if (const auto *CT = T->getAs<ComplexType>()) 2437 T = CT->getElementType().getTypePtr(); 2438 if (const auto *ET = T->getAs<EnumType>()) 2439 T = ET->getDecl()->getIntegerType().getTypePtr(); 2440 if (T->isSpecificBuiltinType(BuiltinType::Double) || 2441 T->isSpecificBuiltinType(BuiltinType::LongLong) || 2442 T->isSpecificBuiltinType(BuiltinType::ULongLong) || 2443 (T->isSpecificBuiltinType(BuiltinType::LongDouble) && 2444 Target->defaultsToAIXPowerAlignment())) 2445 // Don't increase the alignment if an alignment attribute was specified on a 2446 // typedef declaration. 2447 if (!TI.AlignIsRequired) 2448 return std::max(ABIAlign, (unsigned)getTypeSize(T)); 2449 2450 return ABIAlign; 2451 } 2452 2453 /// getTargetDefaultAlignForAttributeAligned - Return the default alignment 2454 /// for __attribute__((aligned)) on this target, to be used if no alignment 2455 /// value is specified. 2456 unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const { 2457 return getTargetInfo().getDefaultAlignForAttributeAligned(); 2458 } 2459 2460 /// getAlignOfGlobalVar - Return the alignment in bits that should be given 2461 /// to a global variable of the specified type. 2462 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const { 2463 uint64_t TypeSize = getTypeSize(T.getTypePtr()); 2464 return std::max(getPreferredTypeAlign(T), 2465 getTargetInfo().getMinGlobalAlign(TypeSize)); 2466 } 2467 2468 /// getAlignOfGlobalVarInChars - Return the alignment in characters that 2469 /// should be given to a global variable of the specified type. 2470 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const { 2471 return toCharUnitsFromBits(getAlignOfGlobalVar(T)); 2472 } 2473 2474 CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const { 2475 CharUnits Offset = CharUnits::Zero(); 2476 const ASTRecordLayout *Layout = &getASTRecordLayout(RD); 2477 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) { 2478 Offset += Layout->getBaseClassOffset(Base); 2479 Layout = &getASTRecordLayout(Base); 2480 } 2481 return Offset; 2482 } 2483 2484 CharUnits ASTContext::getMemberPointerPathAdjustment(const APValue &MP) const { 2485 const ValueDecl *MPD = MP.getMemberPointerDecl(); 2486 CharUnits ThisAdjustment = CharUnits::Zero(); 2487 ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath(); 2488 bool DerivedMember = MP.isMemberPointerToDerivedMember(); 2489 const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext()); 2490 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 2491 const CXXRecordDecl *Base = RD; 2492 const CXXRecordDecl *Derived = Path[I]; 2493 if (DerivedMember) 2494 std::swap(Base, Derived); 2495 ThisAdjustment += getASTRecordLayout(Derived).getBaseClassOffset(Base); 2496 RD = Path[I]; 2497 } 2498 if (DerivedMember) 2499 ThisAdjustment = -ThisAdjustment; 2500 return ThisAdjustment; 2501 } 2502 2503 /// DeepCollectObjCIvars - 2504 /// This routine first collects all declared, but not synthesized, ivars in 2505 /// super class and then collects all ivars, including those synthesized for 2506 /// current class. This routine is used for implementation of current class 2507 /// when all ivars, declared and synthesized are known. 2508 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, 2509 bool leafClass, 2510 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const { 2511 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass()) 2512 DeepCollectObjCIvars(SuperClass, false, Ivars); 2513 if (!leafClass) { 2514 for (const auto *I : OI->ivars()) 2515 Ivars.push_back(I); 2516 } else { 2517 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI); 2518 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv; 2519 Iv= Iv->getNextIvar()) 2520 Ivars.push_back(Iv); 2521 } 2522 } 2523 2524 /// CollectInheritedProtocols - Collect all protocols in current class and 2525 /// those inherited by it. 2526 void ASTContext::CollectInheritedProtocols(const Decl *CDecl, 2527 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) { 2528 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) { 2529 // We can use protocol_iterator here instead of 2530 // all_referenced_protocol_iterator since we are walking all categories. 2531 for (auto *Proto : OI->all_referenced_protocols()) { 2532 CollectInheritedProtocols(Proto, Protocols); 2533 } 2534 2535 // Categories of this Interface. 2536 for (const auto *Cat : OI->visible_categories()) 2537 CollectInheritedProtocols(Cat, Protocols); 2538 2539 if (ObjCInterfaceDecl *SD = OI->getSuperClass()) 2540 while (SD) { 2541 CollectInheritedProtocols(SD, Protocols); 2542 SD = SD->getSuperClass(); 2543 } 2544 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) { 2545 for (auto *Proto : OC->protocols()) { 2546 CollectInheritedProtocols(Proto, Protocols); 2547 } 2548 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) { 2549 // Insert the protocol. 2550 if (!Protocols.insert( 2551 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second) 2552 return; 2553 2554 for (auto *Proto : OP->protocols()) 2555 CollectInheritedProtocols(Proto, Protocols); 2556 } 2557 } 2558 2559 static bool unionHasUniqueObjectRepresentations(const ASTContext &Context, 2560 const RecordDecl *RD) { 2561 assert(RD->isUnion() && "Must be union type"); 2562 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl()); 2563 2564 for (const auto *Field : RD->fields()) { 2565 if (!Context.hasUniqueObjectRepresentations(Field->getType())) 2566 return false; 2567 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType()); 2568 if (FieldSize != UnionSize) 2569 return false; 2570 } 2571 return !RD->field_empty(); 2572 } 2573 2574 static bool isStructEmpty(QualType Ty) { 2575 const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl(); 2576 2577 if (!RD->field_empty()) 2578 return false; 2579 2580 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) 2581 return ClassDecl->isEmpty(); 2582 2583 return true; 2584 } 2585 2586 static llvm::Optional<int64_t> 2587 structHasUniqueObjectRepresentations(const ASTContext &Context, 2588 const RecordDecl *RD) { 2589 assert(!RD->isUnion() && "Must be struct/class type"); 2590 const auto &Layout = Context.getASTRecordLayout(RD); 2591 2592 int64_t CurOffsetInBits = 0; 2593 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) { 2594 if (ClassDecl->isDynamicClass()) 2595 return llvm::None; 2596 2597 SmallVector<std::pair<QualType, int64_t>, 4> Bases; 2598 for (const auto &Base : ClassDecl->bases()) { 2599 // Empty types can be inherited from, and non-empty types can potentially 2600 // have tail padding, so just make sure there isn't an error. 2601 if (!isStructEmpty(Base.getType())) { 2602 llvm::Optional<int64_t> Size = structHasUniqueObjectRepresentations( 2603 Context, Base.getType()->castAs<RecordType>()->getDecl()); 2604 if (!Size) 2605 return llvm::None; 2606 Bases.emplace_back(Base.getType(), Size.getValue()); 2607 } 2608 } 2609 2610 llvm::sort(Bases, [&](const std::pair<QualType, int64_t> &L, 2611 const std::pair<QualType, int64_t> &R) { 2612 return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) < 2613 Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl()); 2614 }); 2615 2616 for (const auto &Base : Bases) { 2617 int64_t BaseOffset = Context.toBits( 2618 Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl())); 2619 int64_t BaseSize = Base.second; 2620 if (BaseOffset != CurOffsetInBits) 2621 return llvm::None; 2622 CurOffsetInBits = BaseOffset + BaseSize; 2623 } 2624 } 2625 2626 for (const auto *Field : RD->fields()) { 2627 if (!Field->getType()->isReferenceType() && 2628 !Context.hasUniqueObjectRepresentations(Field->getType())) 2629 return llvm::None; 2630 2631 int64_t FieldSizeInBits = 2632 Context.toBits(Context.getTypeSizeInChars(Field->getType())); 2633 if (Field->isBitField()) { 2634 int64_t BitfieldSize = Field->getBitWidthValue(Context); 2635 2636 if (BitfieldSize > FieldSizeInBits) 2637 return llvm::None; 2638 FieldSizeInBits = BitfieldSize; 2639 } 2640 2641 int64_t FieldOffsetInBits = Context.getFieldOffset(Field); 2642 2643 if (FieldOffsetInBits != CurOffsetInBits) 2644 return llvm::None; 2645 2646 CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits; 2647 } 2648 2649 return CurOffsetInBits; 2650 } 2651 2652 bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const { 2653 // C++17 [meta.unary.prop]: 2654 // The predicate condition for a template specialization 2655 // has_unique_object_representations<T> shall be 2656 // satisfied if and only if: 2657 // (9.1) - T is trivially copyable, and 2658 // (9.2) - any two objects of type T with the same value have the same 2659 // object representation, where two objects 2660 // of array or non-union class type are considered to have the same value 2661 // if their respective sequences of 2662 // direct subobjects have the same values, and two objects of union type 2663 // are considered to have the same 2664 // value if they have the same active member and the corresponding members 2665 // have the same value. 2666 // The set of scalar types for which this condition holds is 2667 // implementation-defined. [ Note: If a type has padding 2668 // bits, the condition does not hold; otherwise, the condition holds true 2669 // for unsigned integral types. -- end note ] 2670 assert(!Ty.isNull() && "Null QualType sent to unique object rep check"); 2671 2672 // Arrays are unique only if their element type is unique. 2673 if (Ty->isArrayType()) 2674 return hasUniqueObjectRepresentations(getBaseElementType(Ty)); 2675 2676 // (9.1) - T is trivially copyable... 2677 if (!Ty.isTriviallyCopyableType(*this)) 2678 return false; 2679 2680 // All integrals and enums are unique. 2681 if (Ty->isIntegralOrEnumerationType()) 2682 return true; 2683 2684 // All other pointers are unique. 2685 if (Ty->isPointerType()) 2686 return true; 2687 2688 if (Ty->isMemberPointerType()) { 2689 const auto *MPT = Ty->getAs<MemberPointerType>(); 2690 return !ABI->getMemberPointerInfo(MPT).HasPadding; 2691 } 2692 2693 if (Ty->isRecordType()) { 2694 const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl(); 2695 2696 if (Record->isInvalidDecl()) 2697 return false; 2698 2699 if (Record->isUnion()) 2700 return unionHasUniqueObjectRepresentations(*this, Record); 2701 2702 Optional<int64_t> StructSize = 2703 structHasUniqueObjectRepresentations(*this, Record); 2704 2705 return StructSize && 2706 StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty)); 2707 } 2708 2709 // FIXME: More cases to handle here (list by rsmith): 2710 // vectors (careful about, eg, vector of 3 foo) 2711 // _Complex int and friends 2712 // _Atomic T 2713 // Obj-C block pointers 2714 // Obj-C object pointers 2715 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t, 2716 // clk_event_t, queue_t, reserve_id_t) 2717 // There're also Obj-C class types and the Obj-C selector type, but I think it 2718 // makes sense for those to return false here. 2719 2720 return false; 2721 } 2722 2723 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const { 2724 unsigned count = 0; 2725 // Count ivars declared in class extension. 2726 for (const auto *Ext : OI->known_extensions()) 2727 count += Ext->ivar_size(); 2728 2729 // Count ivar defined in this class's implementation. This 2730 // includes synthesized ivars. 2731 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) 2732 count += ImplDecl->ivar_size(); 2733 2734 return count; 2735 } 2736 2737 bool ASTContext::isSentinelNullExpr(const Expr *E) { 2738 if (!E) 2739 return false; 2740 2741 // nullptr_t is always treated as null. 2742 if (E->getType()->isNullPtrType()) return true; 2743 2744 if (E->getType()->isAnyPointerType() && 2745 E->IgnoreParenCasts()->isNullPointerConstant(*this, 2746 Expr::NPC_ValueDependentIsNull)) 2747 return true; 2748 2749 // Unfortunately, __null has type 'int'. 2750 if (isa<GNUNullExpr>(E)) return true; 2751 2752 return false; 2753 } 2754 2755 /// Get the implementation of ObjCInterfaceDecl, or nullptr if none 2756 /// exists. 2757 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) { 2758 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 2759 I = ObjCImpls.find(D); 2760 if (I != ObjCImpls.end()) 2761 return cast<ObjCImplementationDecl>(I->second); 2762 return nullptr; 2763 } 2764 2765 /// Get the implementation of ObjCCategoryDecl, or nullptr if none 2766 /// exists. 2767 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) { 2768 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 2769 I = ObjCImpls.find(D); 2770 if (I != ObjCImpls.end()) 2771 return cast<ObjCCategoryImplDecl>(I->second); 2772 return nullptr; 2773 } 2774 2775 /// Set the implementation of ObjCInterfaceDecl. 2776 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD, 2777 ObjCImplementationDecl *ImplD) { 2778 assert(IFaceD && ImplD && "Passed null params"); 2779 ObjCImpls[IFaceD] = ImplD; 2780 } 2781 2782 /// Set the implementation of ObjCCategoryDecl. 2783 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD, 2784 ObjCCategoryImplDecl *ImplD) { 2785 assert(CatD && ImplD && "Passed null params"); 2786 ObjCImpls[CatD] = ImplD; 2787 } 2788 2789 const ObjCMethodDecl * 2790 ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const { 2791 return ObjCMethodRedecls.lookup(MD); 2792 } 2793 2794 void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD, 2795 const ObjCMethodDecl *Redecl) { 2796 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration"); 2797 ObjCMethodRedecls[MD] = Redecl; 2798 } 2799 2800 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface( 2801 const NamedDecl *ND) const { 2802 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext())) 2803 return ID; 2804 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext())) 2805 return CD->getClassInterface(); 2806 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext())) 2807 return IMD->getClassInterface(); 2808 2809 return nullptr; 2810 } 2811 2812 /// Get the copy initialization expression of VarDecl, or nullptr if 2813 /// none exists. 2814 BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const { 2815 assert(VD && "Passed null params"); 2816 assert(VD->hasAttr<BlocksAttr>() && 2817 "getBlockVarCopyInits - not __block var"); 2818 auto I = BlockVarCopyInits.find(VD); 2819 if (I != BlockVarCopyInits.end()) 2820 return I->second; 2821 return {nullptr, false}; 2822 } 2823 2824 /// Set the copy initialization expression of a block var decl. 2825 void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr, 2826 bool CanThrow) { 2827 assert(VD && CopyExpr && "Passed null params"); 2828 assert(VD->hasAttr<BlocksAttr>() && 2829 "setBlockVarCopyInits - not __block var"); 2830 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow); 2831 } 2832 2833 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T, 2834 unsigned DataSize) const { 2835 if (!DataSize) 2836 DataSize = TypeLoc::getFullDataSizeForType(T); 2837 else 2838 assert(DataSize == TypeLoc::getFullDataSizeForType(T) && 2839 "incorrect data size provided to CreateTypeSourceInfo!"); 2840 2841 auto *TInfo = 2842 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8); 2843 new (TInfo) TypeSourceInfo(T); 2844 return TInfo; 2845 } 2846 2847 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T, 2848 SourceLocation L) const { 2849 TypeSourceInfo *DI = CreateTypeSourceInfo(T); 2850 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L); 2851 return DI; 2852 } 2853 2854 const ASTRecordLayout & 2855 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const { 2856 return getObjCLayout(D, nullptr); 2857 } 2858 2859 const ASTRecordLayout & 2860 ASTContext::getASTObjCImplementationLayout( 2861 const ObjCImplementationDecl *D) const { 2862 return getObjCLayout(D->getClassInterface(), D); 2863 } 2864 2865 //===----------------------------------------------------------------------===// 2866 // Type creation/memoization methods 2867 //===----------------------------------------------------------------------===// 2868 2869 QualType 2870 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const { 2871 unsigned fastQuals = quals.getFastQualifiers(); 2872 quals.removeFastQualifiers(); 2873 2874 // Check if we've already instantiated this type. 2875 llvm::FoldingSetNodeID ID; 2876 ExtQuals::Profile(ID, baseType, quals); 2877 void *insertPos = nullptr; 2878 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) { 2879 assert(eq->getQualifiers() == quals); 2880 return QualType(eq, fastQuals); 2881 } 2882 2883 // If the base type is not canonical, make the appropriate canonical type. 2884 QualType canon; 2885 if (!baseType->isCanonicalUnqualified()) { 2886 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split(); 2887 canonSplit.Quals.addConsistentQualifiers(quals); 2888 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals); 2889 2890 // Re-find the insert position. 2891 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos); 2892 } 2893 2894 auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals); 2895 ExtQualNodes.InsertNode(eq, insertPos); 2896 return QualType(eq, fastQuals); 2897 } 2898 2899 QualType ASTContext::getAddrSpaceQualType(QualType T, 2900 LangAS AddressSpace) const { 2901 QualType CanT = getCanonicalType(T); 2902 if (CanT.getAddressSpace() == AddressSpace) 2903 return T; 2904 2905 // If we are composing extended qualifiers together, merge together 2906 // into one ExtQuals node. 2907 QualifierCollector Quals; 2908 const Type *TypeNode = Quals.strip(T); 2909 2910 // If this type already has an address space specified, it cannot get 2911 // another one. 2912 assert(!Quals.hasAddressSpace() && 2913 "Type cannot be in multiple addr spaces!"); 2914 Quals.addAddressSpace(AddressSpace); 2915 2916 return getExtQualType(TypeNode, Quals); 2917 } 2918 2919 QualType ASTContext::removeAddrSpaceQualType(QualType T) const { 2920 // If the type is not qualified with an address space, just return it 2921 // immediately. 2922 if (!T.hasAddressSpace()) 2923 return T; 2924 2925 // If we are composing extended qualifiers together, merge together 2926 // into one ExtQuals node. 2927 QualifierCollector Quals; 2928 const Type *TypeNode; 2929 2930 while (T.hasAddressSpace()) { 2931 TypeNode = Quals.strip(T); 2932 2933 // If the type no longer has an address space after stripping qualifiers, 2934 // jump out. 2935 if (!QualType(TypeNode, 0).hasAddressSpace()) 2936 break; 2937 2938 // There might be sugar in the way. Strip it and try again. 2939 T = T.getSingleStepDesugaredType(*this); 2940 } 2941 2942 Quals.removeAddressSpace(); 2943 2944 // Removal of the address space can mean there are no longer any 2945 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts) 2946 // or required. 2947 if (Quals.hasNonFastQualifiers()) 2948 return getExtQualType(TypeNode, Quals); 2949 else 2950 return QualType(TypeNode, Quals.getFastQualifiers()); 2951 } 2952 2953 QualType ASTContext::getObjCGCQualType(QualType T, 2954 Qualifiers::GC GCAttr) const { 2955 QualType CanT = getCanonicalType(T); 2956 if (CanT.getObjCGCAttr() == GCAttr) 2957 return T; 2958 2959 if (const auto *ptr = T->getAs<PointerType>()) { 2960 QualType Pointee = ptr->getPointeeType(); 2961 if (Pointee->isAnyPointerType()) { 2962 QualType ResultType = getObjCGCQualType(Pointee, GCAttr); 2963 return getPointerType(ResultType); 2964 } 2965 } 2966 2967 // If we are composing extended qualifiers together, merge together 2968 // into one ExtQuals node. 2969 QualifierCollector Quals; 2970 const Type *TypeNode = Quals.strip(T); 2971 2972 // If this type already has an ObjCGC specified, it cannot get 2973 // another one. 2974 assert(!Quals.hasObjCGCAttr() && 2975 "Type cannot have multiple ObjCGCs!"); 2976 Quals.addObjCGCAttr(GCAttr); 2977 2978 return getExtQualType(TypeNode, Quals); 2979 } 2980 2981 QualType ASTContext::removePtrSizeAddrSpace(QualType T) const { 2982 if (const PointerType *Ptr = T->getAs<PointerType>()) { 2983 QualType Pointee = Ptr->getPointeeType(); 2984 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) { 2985 return getPointerType(removeAddrSpaceQualType(Pointee)); 2986 } 2987 } 2988 return T; 2989 } 2990 2991 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T, 2992 FunctionType::ExtInfo Info) { 2993 if (T->getExtInfo() == Info) 2994 return T; 2995 2996 QualType Result; 2997 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) { 2998 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info); 2999 } else { 3000 const auto *FPT = cast<FunctionProtoType>(T); 3001 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 3002 EPI.ExtInfo = Info; 3003 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI); 3004 } 3005 3006 return cast<FunctionType>(Result.getTypePtr()); 3007 } 3008 3009 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD, 3010 QualType ResultType) { 3011 FD = FD->getMostRecentDecl(); 3012 while (true) { 3013 const auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 3014 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 3015 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI)); 3016 if (FunctionDecl *Next = FD->getPreviousDecl()) 3017 FD = Next; 3018 else 3019 break; 3020 } 3021 if (ASTMutationListener *L = getASTMutationListener()) 3022 L->DeducedReturnType(FD, ResultType); 3023 } 3024 3025 /// Get a function type and produce the equivalent function type with the 3026 /// specified exception specification. Type sugar that can be present on a 3027 /// declaration of a function with an exception specification is permitted 3028 /// and preserved. Other type sugar (for instance, typedefs) is not. 3029 QualType ASTContext::getFunctionTypeWithExceptionSpec( 3030 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) { 3031 // Might have some parens. 3032 if (const auto *PT = dyn_cast<ParenType>(Orig)) 3033 return getParenType( 3034 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI)); 3035 3036 // Might be wrapped in a macro qualified type. 3037 if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig)) 3038 return getMacroQualifiedType( 3039 getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI), 3040 MQT->getMacroIdentifier()); 3041 3042 // Might have a calling-convention attribute. 3043 if (const auto *AT = dyn_cast<AttributedType>(Orig)) 3044 return getAttributedType( 3045 AT->getAttrKind(), 3046 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI), 3047 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI)); 3048 3049 // Anything else must be a function type. Rebuild it with the new exception 3050 // specification. 3051 const auto *Proto = Orig->castAs<FunctionProtoType>(); 3052 return getFunctionType( 3053 Proto->getReturnType(), Proto->getParamTypes(), 3054 Proto->getExtProtoInfo().withExceptionSpec(ESI)); 3055 } 3056 3057 bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T, 3058 QualType U) { 3059 return hasSameType(T, U) || 3060 (getLangOpts().CPlusPlus17 && 3061 hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None), 3062 getFunctionTypeWithExceptionSpec(U, EST_None))); 3063 } 3064 3065 QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) { 3066 if (const auto *Proto = T->getAs<FunctionProtoType>()) { 3067 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType()); 3068 SmallVector<QualType, 16> Args(Proto->param_types()); 3069 for (unsigned i = 0, n = Args.size(); i != n; ++i) 3070 Args[i] = removePtrSizeAddrSpace(Args[i]); 3071 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo()); 3072 } 3073 3074 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) { 3075 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType()); 3076 return getFunctionNoProtoType(RetTy, Proto->getExtInfo()); 3077 } 3078 3079 return T; 3080 } 3081 3082 bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) { 3083 return hasSameType(T, U) || 3084 hasSameType(getFunctionTypeWithoutPtrSizes(T), 3085 getFunctionTypeWithoutPtrSizes(U)); 3086 } 3087 3088 void ASTContext::adjustExceptionSpec( 3089 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, 3090 bool AsWritten) { 3091 // Update the type. 3092 QualType Updated = 3093 getFunctionTypeWithExceptionSpec(FD->getType(), ESI); 3094 FD->setType(Updated); 3095 3096 if (!AsWritten) 3097 return; 3098 3099 // Update the type in the type source information too. 3100 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) { 3101 // If the type and the type-as-written differ, we may need to update 3102 // the type-as-written too. 3103 if (TSInfo->getType() != FD->getType()) 3104 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI); 3105 3106 // FIXME: When we get proper type location information for exceptions, 3107 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch 3108 // up the TypeSourceInfo; 3109 assert(TypeLoc::getFullDataSizeForType(Updated) == 3110 TypeLoc::getFullDataSizeForType(TSInfo->getType()) && 3111 "TypeLoc size mismatch from updating exception specification"); 3112 TSInfo->overrideType(Updated); 3113 } 3114 } 3115 3116 /// getComplexType - Return the uniqued reference to the type for a complex 3117 /// number with the specified element type. 3118 QualType ASTContext::getComplexType(QualType T) const { 3119 // Unique pointers, to guarantee there is only one pointer of a particular 3120 // structure. 3121 llvm::FoldingSetNodeID ID; 3122 ComplexType::Profile(ID, T); 3123 3124 void *InsertPos = nullptr; 3125 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos)) 3126 return QualType(CT, 0); 3127 3128 // If the pointee type isn't canonical, this won't be a canonical type either, 3129 // so fill in the canonical type field. 3130 QualType Canonical; 3131 if (!T.isCanonical()) { 3132 Canonical = getComplexType(getCanonicalType(T)); 3133 3134 // Get the new insert position for the node we care about. 3135 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos); 3136 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3137 } 3138 auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical); 3139 Types.push_back(New); 3140 ComplexTypes.InsertNode(New, InsertPos); 3141 return QualType(New, 0); 3142 } 3143 3144 /// getPointerType - Return the uniqued reference to the type for a pointer to 3145 /// the specified type. 3146 QualType ASTContext::getPointerType(QualType T) const { 3147 // Unique pointers, to guarantee there is only one pointer of a particular 3148 // structure. 3149 llvm::FoldingSetNodeID ID; 3150 PointerType::Profile(ID, T); 3151 3152 void *InsertPos = nullptr; 3153 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3154 return QualType(PT, 0); 3155 3156 // If the pointee type isn't canonical, this won't be a canonical type either, 3157 // so fill in the canonical type field. 3158 QualType Canonical; 3159 if (!T.isCanonical()) { 3160 Canonical = getPointerType(getCanonicalType(T)); 3161 3162 // Get the new insert position for the node we care about. 3163 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3164 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3165 } 3166 auto *New = new (*this, TypeAlignment) PointerType(T, Canonical); 3167 Types.push_back(New); 3168 PointerTypes.InsertNode(New, InsertPos); 3169 return QualType(New, 0); 3170 } 3171 3172 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const { 3173 llvm::FoldingSetNodeID ID; 3174 AdjustedType::Profile(ID, Orig, New); 3175 void *InsertPos = nullptr; 3176 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3177 if (AT) 3178 return QualType(AT, 0); 3179 3180 QualType Canonical = getCanonicalType(New); 3181 3182 // Get the new insert position for the node we care about. 3183 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3184 assert(!AT && "Shouldn't be in the map!"); 3185 3186 AT = new (*this, TypeAlignment) 3187 AdjustedType(Type::Adjusted, Orig, New, Canonical); 3188 Types.push_back(AT); 3189 AdjustedTypes.InsertNode(AT, InsertPos); 3190 return QualType(AT, 0); 3191 } 3192 3193 QualType ASTContext::getDecayedType(QualType T) const { 3194 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay"); 3195 3196 QualType Decayed; 3197 3198 // C99 6.7.5.3p7: 3199 // A declaration of a parameter as "array of type" shall be 3200 // adjusted to "qualified pointer to type", where the type 3201 // qualifiers (if any) are those specified within the [ and ] of 3202 // the array type derivation. 3203 if (T->isArrayType()) 3204 Decayed = getArrayDecayedType(T); 3205 3206 // C99 6.7.5.3p8: 3207 // A declaration of a parameter as "function returning type" 3208 // shall be adjusted to "pointer to function returning type", as 3209 // in 6.3.2.1. 3210 if (T->isFunctionType()) 3211 Decayed = getPointerType(T); 3212 3213 llvm::FoldingSetNodeID ID; 3214 AdjustedType::Profile(ID, T, Decayed); 3215 void *InsertPos = nullptr; 3216 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3217 if (AT) 3218 return QualType(AT, 0); 3219 3220 QualType Canonical = getCanonicalType(Decayed); 3221 3222 // Get the new insert position for the node we care about. 3223 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3224 assert(!AT && "Shouldn't be in the map!"); 3225 3226 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical); 3227 Types.push_back(AT); 3228 AdjustedTypes.InsertNode(AT, InsertPos); 3229 return QualType(AT, 0); 3230 } 3231 3232 /// getBlockPointerType - Return the uniqued reference to the type for 3233 /// a pointer to the specified block. 3234 QualType ASTContext::getBlockPointerType(QualType T) const { 3235 assert(T->isFunctionType() && "block of function types only"); 3236 // Unique pointers, to guarantee there is only one block of a particular 3237 // structure. 3238 llvm::FoldingSetNodeID ID; 3239 BlockPointerType::Profile(ID, T); 3240 3241 void *InsertPos = nullptr; 3242 if (BlockPointerType *PT = 3243 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3244 return QualType(PT, 0); 3245 3246 // If the block pointee type isn't canonical, this won't be a canonical 3247 // type either so fill in the canonical type field. 3248 QualType Canonical; 3249 if (!T.isCanonical()) { 3250 Canonical = getBlockPointerType(getCanonicalType(T)); 3251 3252 // Get the new insert position for the node we care about. 3253 BlockPointerType *NewIP = 3254 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3255 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3256 } 3257 auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical); 3258 Types.push_back(New); 3259 BlockPointerTypes.InsertNode(New, InsertPos); 3260 return QualType(New, 0); 3261 } 3262 3263 /// getLValueReferenceType - Return the uniqued reference to the type for an 3264 /// lvalue reference to the specified type. 3265 QualType 3266 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const { 3267 assert(getCanonicalType(T) != OverloadTy && 3268 "Unresolved overloaded function type"); 3269 3270 // Unique pointers, to guarantee there is only one pointer of a particular 3271 // structure. 3272 llvm::FoldingSetNodeID ID; 3273 ReferenceType::Profile(ID, T, SpelledAsLValue); 3274 3275 void *InsertPos = nullptr; 3276 if (LValueReferenceType *RT = 3277 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 3278 return QualType(RT, 0); 3279 3280 const auto *InnerRef = T->getAs<ReferenceType>(); 3281 3282 // If the referencee type isn't canonical, this won't be a canonical type 3283 // either, so fill in the canonical type field. 3284 QualType Canonical; 3285 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) { 3286 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 3287 Canonical = getLValueReferenceType(getCanonicalType(PointeeType)); 3288 3289 // Get the new insert position for the node we care about. 3290 LValueReferenceType *NewIP = 3291 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 3292 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3293 } 3294 3295 auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical, 3296 SpelledAsLValue); 3297 Types.push_back(New); 3298 LValueReferenceTypes.InsertNode(New, InsertPos); 3299 3300 return QualType(New, 0); 3301 } 3302 3303 /// getRValueReferenceType - Return the uniqued reference to the type for an 3304 /// rvalue reference to the specified type. 3305 QualType ASTContext::getRValueReferenceType(QualType T) const { 3306 // Unique pointers, to guarantee there is only one pointer of a particular 3307 // structure. 3308 llvm::FoldingSetNodeID ID; 3309 ReferenceType::Profile(ID, T, false); 3310 3311 void *InsertPos = nullptr; 3312 if (RValueReferenceType *RT = 3313 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 3314 return QualType(RT, 0); 3315 3316 const auto *InnerRef = T->getAs<ReferenceType>(); 3317 3318 // If the referencee type isn't canonical, this won't be a canonical type 3319 // either, so fill in the canonical type field. 3320 QualType Canonical; 3321 if (InnerRef || !T.isCanonical()) { 3322 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 3323 Canonical = getRValueReferenceType(getCanonicalType(PointeeType)); 3324 3325 // Get the new insert position for the node we care about. 3326 RValueReferenceType *NewIP = 3327 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 3328 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3329 } 3330 3331 auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical); 3332 Types.push_back(New); 3333 RValueReferenceTypes.InsertNode(New, InsertPos); 3334 return QualType(New, 0); 3335 } 3336 3337 /// getMemberPointerType - Return the uniqued reference to the type for a 3338 /// member pointer to the specified type, in the specified class. 3339 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const { 3340 // Unique pointers, to guarantee there is only one pointer of a particular 3341 // structure. 3342 llvm::FoldingSetNodeID ID; 3343 MemberPointerType::Profile(ID, T, Cls); 3344 3345 void *InsertPos = nullptr; 3346 if (MemberPointerType *PT = 3347 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3348 return QualType(PT, 0); 3349 3350 // If the pointee or class type isn't canonical, this won't be a canonical 3351 // type either, so fill in the canonical type field. 3352 QualType Canonical; 3353 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) { 3354 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls)); 3355 3356 // Get the new insert position for the node we care about. 3357 MemberPointerType *NewIP = 3358 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3359 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3360 } 3361 auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical); 3362 Types.push_back(New); 3363 MemberPointerTypes.InsertNode(New, InsertPos); 3364 return QualType(New, 0); 3365 } 3366 3367 /// getConstantArrayType - Return the unique reference to the type for an 3368 /// array of the specified element type. 3369 QualType ASTContext::getConstantArrayType(QualType EltTy, 3370 const llvm::APInt &ArySizeIn, 3371 const Expr *SizeExpr, 3372 ArrayType::ArraySizeModifier ASM, 3373 unsigned IndexTypeQuals) const { 3374 assert((EltTy->isDependentType() || 3375 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) && 3376 "Constant array of VLAs is illegal!"); 3377 3378 // We only need the size as part of the type if it's instantiation-dependent. 3379 if (SizeExpr && !SizeExpr->isInstantiationDependent()) 3380 SizeExpr = nullptr; 3381 3382 // Convert the array size into a canonical width matching the pointer size for 3383 // the target. 3384 llvm::APInt ArySize(ArySizeIn); 3385 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth()); 3386 3387 llvm::FoldingSetNodeID ID; 3388 ConstantArrayType::Profile(ID, *this, EltTy, ArySize, SizeExpr, ASM, 3389 IndexTypeQuals); 3390 3391 void *InsertPos = nullptr; 3392 if (ConstantArrayType *ATP = 3393 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 3394 return QualType(ATP, 0); 3395 3396 // If the element type isn't canonical or has qualifiers, or the array bound 3397 // is instantiation-dependent, this won't be a canonical type either, so fill 3398 // in the canonical type field. 3399 QualType Canon; 3400 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) { 3401 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 3402 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr, 3403 ASM, IndexTypeQuals); 3404 Canon = getQualifiedType(Canon, canonSplit.Quals); 3405 3406 // Get the new insert position for the node we care about. 3407 ConstantArrayType *NewIP = 3408 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 3409 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3410 } 3411 3412 void *Mem = Allocate( 3413 ConstantArrayType::totalSizeToAlloc<const Expr *>(SizeExpr ? 1 : 0), 3414 TypeAlignment); 3415 auto *New = new (Mem) 3416 ConstantArrayType(EltTy, Canon, ArySize, SizeExpr, ASM, IndexTypeQuals); 3417 ConstantArrayTypes.InsertNode(New, InsertPos); 3418 Types.push_back(New); 3419 return QualType(New, 0); 3420 } 3421 3422 /// getVariableArrayDecayedType - Turns the given type, which may be 3423 /// variably-modified, into the corresponding type with all the known 3424 /// sizes replaced with [*]. 3425 QualType ASTContext::getVariableArrayDecayedType(QualType type) const { 3426 // Vastly most common case. 3427 if (!type->isVariablyModifiedType()) return type; 3428 3429 QualType result; 3430 3431 SplitQualType split = type.getSplitDesugaredType(); 3432 const Type *ty = split.Ty; 3433 switch (ty->getTypeClass()) { 3434 #define TYPE(Class, Base) 3435 #define ABSTRACT_TYPE(Class, Base) 3436 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 3437 #include "clang/AST/TypeNodes.inc" 3438 llvm_unreachable("didn't desugar past all non-canonical types?"); 3439 3440 // These types should never be variably-modified. 3441 case Type::Builtin: 3442 case Type::Complex: 3443 case Type::Vector: 3444 case Type::DependentVector: 3445 case Type::ExtVector: 3446 case Type::DependentSizedExtVector: 3447 case Type::ConstantMatrix: 3448 case Type::DependentSizedMatrix: 3449 case Type::DependentAddressSpace: 3450 case Type::ObjCObject: 3451 case Type::ObjCInterface: 3452 case Type::ObjCObjectPointer: 3453 case Type::Record: 3454 case Type::Enum: 3455 case Type::UnresolvedUsing: 3456 case Type::TypeOfExpr: 3457 case Type::TypeOf: 3458 case Type::Decltype: 3459 case Type::UnaryTransform: 3460 case Type::DependentName: 3461 case Type::InjectedClassName: 3462 case Type::TemplateSpecialization: 3463 case Type::DependentTemplateSpecialization: 3464 case Type::TemplateTypeParm: 3465 case Type::SubstTemplateTypeParmPack: 3466 case Type::Auto: 3467 case Type::DeducedTemplateSpecialization: 3468 case Type::PackExpansion: 3469 case Type::ExtInt: 3470 case Type::DependentExtInt: 3471 llvm_unreachable("type should never be variably-modified"); 3472 3473 // These types can be variably-modified but should never need to 3474 // further decay. 3475 case Type::FunctionNoProto: 3476 case Type::FunctionProto: 3477 case Type::BlockPointer: 3478 case Type::MemberPointer: 3479 case Type::Pipe: 3480 return type; 3481 3482 // These types can be variably-modified. All these modifications 3483 // preserve structure except as noted by comments. 3484 // TODO: if we ever care about optimizing VLAs, there are no-op 3485 // optimizations available here. 3486 case Type::Pointer: 3487 result = getPointerType(getVariableArrayDecayedType( 3488 cast<PointerType>(ty)->getPointeeType())); 3489 break; 3490 3491 case Type::LValueReference: { 3492 const auto *lv = cast<LValueReferenceType>(ty); 3493 result = getLValueReferenceType( 3494 getVariableArrayDecayedType(lv->getPointeeType()), 3495 lv->isSpelledAsLValue()); 3496 break; 3497 } 3498 3499 case Type::RValueReference: { 3500 const auto *lv = cast<RValueReferenceType>(ty); 3501 result = getRValueReferenceType( 3502 getVariableArrayDecayedType(lv->getPointeeType())); 3503 break; 3504 } 3505 3506 case Type::Atomic: { 3507 const auto *at = cast<AtomicType>(ty); 3508 result = getAtomicType(getVariableArrayDecayedType(at->getValueType())); 3509 break; 3510 } 3511 3512 case Type::ConstantArray: { 3513 const auto *cat = cast<ConstantArrayType>(ty); 3514 result = getConstantArrayType( 3515 getVariableArrayDecayedType(cat->getElementType()), 3516 cat->getSize(), 3517 cat->getSizeExpr(), 3518 cat->getSizeModifier(), 3519 cat->getIndexTypeCVRQualifiers()); 3520 break; 3521 } 3522 3523 case Type::DependentSizedArray: { 3524 const auto *dat = cast<DependentSizedArrayType>(ty); 3525 result = getDependentSizedArrayType( 3526 getVariableArrayDecayedType(dat->getElementType()), 3527 dat->getSizeExpr(), 3528 dat->getSizeModifier(), 3529 dat->getIndexTypeCVRQualifiers(), 3530 dat->getBracketsRange()); 3531 break; 3532 } 3533 3534 // Turn incomplete types into [*] types. 3535 case Type::IncompleteArray: { 3536 const auto *iat = cast<IncompleteArrayType>(ty); 3537 result = getVariableArrayType( 3538 getVariableArrayDecayedType(iat->getElementType()), 3539 /*size*/ nullptr, 3540 ArrayType::Normal, 3541 iat->getIndexTypeCVRQualifiers(), 3542 SourceRange()); 3543 break; 3544 } 3545 3546 // Turn VLA types into [*] types. 3547 case Type::VariableArray: { 3548 const auto *vat = cast<VariableArrayType>(ty); 3549 result = getVariableArrayType( 3550 getVariableArrayDecayedType(vat->getElementType()), 3551 /*size*/ nullptr, 3552 ArrayType::Star, 3553 vat->getIndexTypeCVRQualifiers(), 3554 vat->getBracketsRange()); 3555 break; 3556 } 3557 } 3558 3559 // Apply the top-level qualifiers from the original. 3560 return getQualifiedType(result, split.Quals); 3561 } 3562 3563 /// getVariableArrayType - Returns a non-unique reference to the type for a 3564 /// variable array of the specified element type. 3565 QualType ASTContext::getVariableArrayType(QualType EltTy, 3566 Expr *NumElts, 3567 ArrayType::ArraySizeModifier ASM, 3568 unsigned IndexTypeQuals, 3569 SourceRange Brackets) const { 3570 // Since we don't unique expressions, it isn't possible to unique VLA's 3571 // that have an expression provided for their size. 3572 QualType Canon; 3573 3574 // Be sure to pull qualifiers off the element type. 3575 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) { 3576 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 3577 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM, 3578 IndexTypeQuals, Brackets); 3579 Canon = getQualifiedType(Canon, canonSplit.Quals); 3580 } 3581 3582 auto *New = new (*this, TypeAlignment) 3583 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets); 3584 3585 VariableArrayTypes.push_back(New); 3586 Types.push_back(New); 3587 return QualType(New, 0); 3588 } 3589 3590 /// getDependentSizedArrayType - Returns a non-unique reference to 3591 /// the type for a dependently-sized array of the specified element 3592 /// type. 3593 QualType ASTContext::getDependentSizedArrayType(QualType elementType, 3594 Expr *numElements, 3595 ArrayType::ArraySizeModifier ASM, 3596 unsigned elementTypeQuals, 3597 SourceRange brackets) const { 3598 assert((!numElements || numElements->isTypeDependent() || 3599 numElements->isValueDependent()) && 3600 "Size must be type- or value-dependent!"); 3601 3602 // Dependently-sized array types that do not have a specified number 3603 // of elements will have their sizes deduced from a dependent 3604 // initializer. We do no canonicalization here at all, which is okay 3605 // because they can't be used in most locations. 3606 if (!numElements) { 3607 auto *newType 3608 = new (*this, TypeAlignment) 3609 DependentSizedArrayType(*this, elementType, QualType(), 3610 numElements, ASM, elementTypeQuals, 3611 brackets); 3612 Types.push_back(newType); 3613 return QualType(newType, 0); 3614 } 3615 3616 // Otherwise, we actually build a new type every time, but we 3617 // also build a canonical type. 3618 3619 SplitQualType canonElementType = getCanonicalType(elementType).split(); 3620 3621 void *insertPos = nullptr; 3622 llvm::FoldingSetNodeID ID; 3623 DependentSizedArrayType::Profile(ID, *this, 3624 QualType(canonElementType.Ty, 0), 3625 ASM, elementTypeQuals, numElements); 3626 3627 // Look for an existing type with these properties. 3628 DependentSizedArrayType *canonTy = 3629 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos); 3630 3631 // If we don't have one, build one. 3632 if (!canonTy) { 3633 canonTy = new (*this, TypeAlignment) 3634 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0), 3635 QualType(), numElements, ASM, elementTypeQuals, 3636 brackets); 3637 DependentSizedArrayTypes.InsertNode(canonTy, insertPos); 3638 Types.push_back(canonTy); 3639 } 3640 3641 // Apply qualifiers from the element type to the array. 3642 QualType canon = getQualifiedType(QualType(canonTy,0), 3643 canonElementType.Quals); 3644 3645 // If we didn't need extra canonicalization for the element type or the size 3646 // expression, then just use that as our result. 3647 if (QualType(canonElementType.Ty, 0) == elementType && 3648 canonTy->getSizeExpr() == numElements) 3649 return canon; 3650 3651 // Otherwise, we need to build a type which follows the spelling 3652 // of the element type. 3653 auto *sugaredType 3654 = new (*this, TypeAlignment) 3655 DependentSizedArrayType(*this, elementType, canon, numElements, 3656 ASM, elementTypeQuals, brackets); 3657 Types.push_back(sugaredType); 3658 return QualType(sugaredType, 0); 3659 } 3660 3661 QualType ASTContext::getIncompleteArrayType(QualType elementType, 3662 ArrayType::ArraySizeModifier ASM, 3663 unsigned elementTypeQuals) const { 3664 llvm::FoldingSetNodeID ID; 3665 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals); 3666 3667 void *insertPos = nullptr; 3668 if (IncompleteArrayType *iat = 3669 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos)) 3670 return QualType(iat, 0); 3671 3672 // If the element type isn't canonical, this won't be a canonical type 3673 // either, so fill in the canonical type field. We also have to pull 3674 // qualifiers off the element type. 3675 QualType canon; 3676 3677 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) { 3678 SplitQualType canonSplit = getCanonicalType(elementType).split(); 3679 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0), 3680 ASM, elementTypeQuals); 3681 canon = getQualifiedType(canon, canonSplit.Quals); 3682 3683 // Get the new insert position for the node we care about. 3684 IncompleteArrayType *existing = 3685 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos); 3686 assert(!existing && "Shouldn't be in the map!"); (void) existing; 3687 } 3688 3689 auto *newType = new (*this, TypeAlignment) 3690 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals); 3691 3692 IncompleteArrayTypes.InsertNode(newType, insertPos); 3693 Types.push_back(newType); 3694 return QualType(newType, 0); 3695 } 3696 3697 ASTContext::BuiltinVectorTypeInfo 3698 ASTContext::getBuiltinVectorTypeInfo(const BuiltinType *Ty) const { 3699 #define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \ 3700 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \ 3701 NUMVECTORS}; 3702 3703 #define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \ 3704 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS}; 3705 3706 switch (Ty->getKind()) { 3707 default: 3708 llvm_unreachable("Unsupported builtin vector type"); 3709 case BuiltinType::SveInt8: 3710 return SVE_INT_ELTTY(8, 16, true, 1); 3711 case BuiltinType::SveUint8: 3712 return SVE_INT_ELTTY(8, 16, false, 1); 3713 case BuiltinType::SveInt8x2: 3714 return SVE_INT_ELTTY(8, 16, true, 2); 3715 case BuiltinType::SveUint8x2: 3716 return SVE_INT_ELTTY(8, 16, false, 2); 3717 case BuiltinType::SveInt8x3: 3718 return SVE_INT_ELTTY(8, 16, true, 3); 3719 case BuiltinType::SveUint8x3: 3720 return SVE_INT_ELTTY(8, 16, false, 3); 3721 case BuiltinType::SveInt8x4: 3722 return SVE_INT_ELTTY(8, 16, true, 4); 3723 case BuiltinType::SveUint8x4: 3724 return SVE_INT_ELTTY(8, 16, false, 4); 3725 case BuiltinType::SveInt16: 3726 return SVE_INT_ELTTY(16, 8, true, 1); 3727 case BuiltinType::SveUint16: 3728 return SVE_INT_ELTTY(16, 8, false, 1); 3729 case BuiltinType::SveInt16x2: 3730 return SVE_INT_ELTTY(16, 8, true, 2); 3731 case BuiltinType::SveUint16x2: 3732 return SVE_INT_ELTTY(16, 8, false, 2); 3733 case BuiltinType::SveInt16x3: 3734 return SVE_INT_ELTTY(16, 8, true, 3); 3735 case BuiltinType::SveUint16x3: 3736 return SVE_INT_ELTTY(16, 8, false, 3); 3737 case BuiltinType::SveInt16x4: 3738 return SVE_INT_ELTTY(16, 8, true, 4); 3739 case BuiltinType::SveUint16x4: 3740 return SVE_INT_ELTTY(16, 8, false, 4); 3741 case BuiltinType::SveInt32: 3742 return SVE_INT_ELTTY(32, 4, true, 1); 3743 case BuiltinType::SveUint32: 3744 return SVE_INT_ELTTY(32, 4, false, 1); 3745 case BuiltinType::SveInt32x2: 3746 return SVE_INT_ELTTY(32, 4, true, 2); 3747 case BuiltinType::SveUint32x2: 3748 return SVE_INT_ELTTY(32, 4, false, 2); 3749 case BuiltinType::SveInt32x3: 3750 return SVE_INT_ELTTY(32, 4, true, 3); 3751 case BuiltinType::SveUint32x3: 3752 return SVE_INT_ELTTY(32, 4, false, 3); 3753 case BuiltinType::SveInt32x4: 3754 return SVE_INT_ELTTY(32, 4, true, 4); 3755 case BuiltinType::SveUint32x4: 3756 return SVE_INT_ELTTY(32, 4, false, 4); 3757 case BuiltinType::SveInt64: 3758 return SVE_INT_ELTTY(64, 2, true, 1); 3759 case BuiltinType::SveUint64: 3760 return SVE_INT_ELTTY(64, 2, false, 1); 3761 case BuiltinType::SveInt64x2: 3762 return SVE_INT_ELTTY(64, 2, true, 2); 3763 case BuiltinType::SveUint64x2: 3764 return SVE_INT_ELTTY(64, 2, false, 2); 3765 case BuiltinType::SveInt64x3: 3766 return SVE_INT_ELTTY(64, 2, true, 3); 3767 case BuiltinType::SveUint64x3: 3768 return SVE_INT_ELTTY(64, 2, false, 3); 3769 case BuiltinType::SveInt64x4: 3770 return SVE_INT_ELTTY(64, 2, true, 4); 3771 case BuiltinType::SveUint64x4: 3772 return SVE_INT_ELTTY(64, 2, false, 4); 3773 case BuiltinType::SveBool: 3774 return SVE_ELTTY(BoolTy, 16, 1); 3775 case BuiltinType::SveFloat16: 3776 return SVE_ELTTY(HalfTy, 8, 1); 3777 case BuiltinType::SveFloat16x2: 3778 return SVE_ELTTY(HalfTy, 8, 2); 3779 case BuiltinType::SveFloat16x3: 3780 return SVE_ELTTY(HalfTy, 8, 3); 3781 case BuiltinType::SveFloat16x4: 3782 return SVE_ELTTY(HalfTy, 8, 4); 3783 case BuiltinType::SveFloat32: 3784 return SVE_ELTTY(FloatTy, 4, 1); 3785 case BuiltinType::SveFloat32x2: 3786 return SVE_ELTTY(FloatTy, 4, 2); 3787 case BuiltinType::SveFloat32x3: 3788 return SVE_ELTTY(FloatTy, 4, 3); 3789 case BuiltinType::SveFloat32x4: 3790 return SVE_ELTTY(FloatTy, 4, 4); 3791 case BuiltinType::SveFloat64: 3792 return SVE_ELTTY(DoubleTy, 2, 1); 3793 case BuiltinType::SveFloat64x2: 3794 return SVE_ELTTY(DoubleTy, 2, 2); 3795 case BuiltinType::SveFloat64x3: 3796 return SVE_ELTTY(DoubleTy, 2, 3); 3797 case BuiltinType::SveFloat64x4: 3798 return SVE_ELTTY(DoubleTy, 2, 4); 3799 case BuiltinType::SveBFloat16: 3800 return SVE_ELTTY(BFloat16Ty, 8, 1); 3801 case BuiltinType::SveBFloat16x2: 3802 return SVE_ELTTY(BFloat16Ty, 8, 2); 3803 case BuiltinType::SveBFloat16x3: 3804 return SVE_ELTTY(BFloat16Ty, 8, 3); 3805 case BuiltinType::SveBFloat16x4: 3806 return SVE_ELTTY(BFloat16Ty, 8, 4); 3807 } 3808 } 3809 3810 /// getScalableVectorType - Return the unique reference to a scalable vector 3811 /// type of the specified element type and size. VectorType must be a built-in 3812 /// type. 3813 QualType ASTContext::getScalableVectorType(QualType EltTy, 3814 unsigned NumElts) const { 3815 if (Target->hasAArch64SVETypes()) { 3816 uint64_t EltTySize = getTypeSize(EltTy); 3817 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \ 3818 IsSigned, IsFP, IsBF) \ 3819 if (!EltTy->isBooleanType() && \ 3820 ((EltTy->hasIntegerRepresentation() && \ 3821 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \ 3822 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \ 3823 IsFP && !IsBF) || \ 3824 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \ 3825 IsBF && !IsFP)) && \ 3826 EltTySize == ElBits && NumElts == NumEls) { \ 3827 return SingletonId; \ 3828 } 3829 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \ 3830 if (EltTy->isBooleanType() && NumElts == NumEls) \ 3831 return SingletonId; 3832 #include "clang/Basic/AArch64SVEACLETypes.def" 3833 } 3834 return QualType(); 3835 } 3836 3837 /// getVectorType - Return the unique reference to a vector type of 3838 /// the specified element type and size. VectorType must be a built-in type. 3839 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts, 3840 VectorType::VectorKind VecKind) const { 3841 assert(vecType->isBuiltinType()); 3842 3843 // Check if we've already instantiated a vector of this type. 3844 llvm::FoldingSetNodeID ID; 3845 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind); 3846 3847 void *InsertPos = nullptr; 3848 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 3849 return QualType(VTP, 0); 3850 3851 // If the element type isn't canonical, this won't be a canonical type either, 3852 // so fill in the canonical type field. 3853 QualType Canonical; 3854 if (!vecType.isCanonical()) { 3855 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind); 3856 3857 // Get the new insert position for the node we care about. 3858 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3859 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3860 } 3861 auto *New = new (*this, TypeAlignment) 3862 VectorType(vecType, NumElts, Canonical, VecKind); 3863 VectorTypes.InsertNode(New, InsertPos); 3864 Types.push_back(New); 3865 return QualType(New, 0); 3866 } 3867 3868 QualType 3869 ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr, 3870 SourceLocation AttrLoc, 3871 VectorType::VectorKind VecKind) const { 3872 llvm::FoldingSetNodeID ID; 3873 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr, 3874 VecKind); 3875 void *InsertPos = nullptr; 3876 DependentVectorType *Canon = 3877 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3878 DependentVectorType *New; 3879 3880 if (Canon) { 3881 New = new (*this, TypeAlignment) DependentVectorType( 3882 *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind); 3883 } else { 3884 QualType CanonVecTy = getCanonicalType(VecType); 3885 if (CanonVecTy == VecType) { 3886 New = new (*this, TypeAlignment) DependentVectorType( 3887 *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind); 3888 3889 DependentVectorType *CanonCheck = 3890 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3891 assert(!CanonCheck && 3892 "Dependent-sized vector_size canonical type broken"); 3893 (void)CanonCheck; 3894 DependentVectorTypes.InsertNode(New, InsertPos); 3895 } else { 3896 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr, 3897 SourceLocation(), VecKind); 3898 New = new (*this, TypeAlignment) DependentVectorType( 3899 *this, VecType, CanonTy, SizeExpr, AttrLoc, VecKind); 3900 } 3901 } 3902 3903 Types.push_back(New); 3904 return QualType(New, 0); 3905 } 3906 3907 /// getExtVectorType - Return the unique reference to an extended vector type of 3908 /// the specified element type and size. VectorType must be a built-in type. 3909 QualType 3910 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const { 3911 assert(vecType->isBuiltinType() || vecType->isDependentType()); 3912 3913 // Check if we've already instantiated a vector of this type. 3914 llvm::FoldingSetNodeID ID; 3915 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, 3916 VectorType::GenericVector); 3917 void *InsertPos = nullptr; 3918 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 3919 return QualType(VTP, 0); 3920 3921 // If the element type isn't canonical, this won't be a canonical type either, 3922 // so fill in the canonical type field. 3923 QualType Canonical; 3924 if (!vecType.isCanonical()) { 3925 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts); 3926 3927 // Get the new insert position for the node we care about. 3928 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3929 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3930 } 3931 auto *New = new (*this, TypeAlignment) 3932 ExtVectorType(vecType, NumElts, Canonical); 3933 VectorTypes.InsertNode(New, InsertPos); 3934 Types.push_back(New); 3935 return QualType(New, 0); 3936 } 3937 3938 QualType 3939 ASTContext::getDependentSizedExtVectorType(QualType vecType, 3940 Expr *SizeExpr, 3941 SourceLocation AttrLoc) const { 3942 llvm::FoldingSetNodeID ID; 3943 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType), 3944 SizeExpr); 3945 3946 void *InsertPos = nullptr; 3947 DependentSizedExtVectorType *Canon 3948 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3949 DependentSizedExtVectorType *New; 3950 if (Canon) { 3951 // We already have a canonical version of this array type; use it as 3952 // the canonical type for a newly-built type. 3953 New = new (*this, TypeAlignment) 3954 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0), 3955 SizeExpr, AttrLoc); 3956 } else { 3957 QualType CanonVecTy = getCanonicalType(vecType); 3958 if (CanonVecTy == vecType) { 3959 New = new (*this, TypeAlignment) 3960 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr, 3961 AttrLoc); 3962 3963 DependentSizedExtVectorType *CanonCheck 3964 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3965 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken"); 3966 (void)CanonCheck; 3967 DependentSizedExtVectorTypes.InsertNode(New, InsertPos); 3968 } else { 3969 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr, 3970 SourceLocation()); 3971 New = new (*this, TypeAlignment) DependentSizedExtVectorType( 3972 *this, vecType, CanonExtTy, SizeExpr, AttrLoc); 3973 } 3974 } 3975 3976 Types.push_back(New); 3977 return QualType(New, 0); 3978 } 3979 3980 QualType ASTContext::getConstantMatrixType(QualType ElementTy, unsigned NumRows, 3981 unsigned NumColumns) const { 3982 llvm::FoldingSetNodeID ID; 3983 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns, 3984 Type::ConstantMatrix); 3985 3986 assert(MatrixType::isValidElementType(ElementTy) && 3987 "need a valid element type"); 3988 assert(ConstantMatrixType::isDimensionValid(NumRows) && 3989 ConstantMatrixType::isDimensionValid(NumColumns) && 3990 "need valid matrix dimensions"); 3991 void *InsertPos = nullptr; 3992 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos)) 3993 return QualType(MTP, 0); 3994 3995 QualType Canonical; 3996 if (!ElementTy.isCanonical()) { 3997 Canonical = 3998 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns); 3999 4000 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos); 4001 assert(!NewIP && "Matrix type shouldn't already exist in the map"); 4002 (void)NewIP; 4003 } 4004 4005 auto *New = new (*this, TypeAlignment) 4006 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical); 4007 MatrixTypes.InsertNode(New, InsertPos); 4008 Types.push_back(New); 4009 return QualType(New, 0); 4010 } 4011 4012 QualType ASTContext::getDependentSizedMatrixType(QualType ElementTy, 4013 Expr *RowExpr, 4014 Expr *ColumnExpr, 4015 SourceLocation AttrLoc) const { 4016 QualType CanonElementTy = getCanonicalType(ElementTy); 4017 llvm::FoldingSetNodeID ID; 4018 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr, 4019 ColumnExpr); 4020 4021 void *InsertPos = nullptr; 4022 DependentSizedMatrixType *Canon = 4023 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos); 4024 4025 if (!Canon) { 4026 Canon = new (*this, TypeAlignment) DependentSizedMatrixType( 4027 *this, CanonElementTy, QualType(), RowExpr, ColumnExpr, AttrLoc); 4028 #ifndef NDEBUG 4029 DependentSizedMatrixType *CanonCheck = 4030 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos); 4031 assert(!CanonCheck && "Dependent-sized matrix canonical type broken"); 4032 #endif 4033 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos); 4034 Types.push_back(Canon); 4035 } 4036 4037 // Already have a canonical version of the matrix type 4038 // 4039 // If it exactly matches the requested type, use it directly. 4040 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr && 4041 Canon->getRowExpr() == ColumnExpr) 4042 return QualType(Canon, 0); 4043 4044 // Use Canon as the canonical type for newly-built type. 4045 DependentSizedMatrixType *New = new (*this, TypeAlignment) 4046 DependentSizedMatrixType(*this, ElementTy, QualType(Canon, 0), RowExpr, 4047 ColumnExpr, AttrLoc); 4048 Types.push_back(New); 4049 return QualType(New, 0); 4050 } 4051 4052 QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType, 4053 Expr *AddrSpaceExpr, 4054 SourceLocation AttrLoc) const { 4055 assert(AddrSpaceExpr->isInstantiationDependent()); 4056 4057 QualType canonPointeeType = getCanonicalType(PointeeType); 4058 4059 void *insertPos = nullptr; 4060 llvm::FoldingSetNodeID ID; 4061 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType, 4062 AddrSpaceExpr); 4063 4064 DependentAddressSpaceType *canonTy = 4065 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos); 4066 4067 if (!canonTy) { 4068 canonTy = new (*this, TypeAlignment) 4069 DependentAddressSpaceType(*this, canonPointeeType, 4070 QualType(), AddrSpaceExpr, AttrLoc); 4071 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos); 4072 Types.push_back(canonTy); 4073 } 4074 4075 if (canonPointeeType == PointeeType && 4076 canonTy->getAddrSpaceExpr() == AddrSpaceExpr) 4077 return QualType(canonTy, 0); 4078 4079 auto *sugaredType 4080 = new (*this, TypeAlignment) 4081 DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0), 4082 AddrSpaceExpr, AttrLoc); 4083 Types.push_back(sugaredType); 4084 return QualType(sugaredType, 0); 4085 } 4086 4087 /// Determine whether \p T is canonical as the result type of a function. 4088 static bool isCanonicalResultType(QualType T) { 4089 return T.isCanonical() && 4090 (T.getObjCLifetime() == Qualifiers::OCL_None || 4091 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone); 4092 } 4093 4094 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'. 4095 QualType 4096 ASTContext::getFunctionNoProtoType(QualType ResultTy, 4097 const FunctionType::ExtInfo &Info) const { 4098 // Unique functions, to guarantee there is only one function of a particular 4099 // structure. 4100 llvm::FoldingSetNodeID ID; 4101 FunctionNoProtoType::Profile(ID, ResultTy, Info); 4102 4103 void *InsertPos = nullptr; 4104 if (FunctionNoProtoType *FT = 4105 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 4106 return QualType(FT, 0); 4107 4108 QualType Canonical; 4109 if (!isCanonicalResultType(ResultTy)) { 4110 Canonical = 4111 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info); 4112 4113 // Get the new insert position for the node we care about. 4114 FunctionNoProtoType *NewIP = 4115 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 4116 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4117 } 4118 4119 auto *New = new (*this, TypeAlignment) 4120 FunctionNoProtoType(ResultTy, Canonical, Info); 4121 Types.push_back(New); 4122 FunctionNoProtoTypes.InsertNode(New, InsertPos); 4123 return QualType(New, 0); 4124 } 4125 4126 CanQualType 4127 ASTContext::getCanonicalFunctionResultType(QualType ResultType) const { 4128 CanQualType CanResultType = getCanonicalType(ResultType); 4129 4130 // Canonical result types do not have ARC lifetime qualifiers. 4131 if (CanResultType.getQualifiers().hasObjCLifetime()) { 4132 Qualifiers Qs = CanResultType.getQualifiers(); 4133 Qs.removeObjCLifetime(); 4134 return CanQualType::CreateUnsafe( 4135 getQualifiedType(CanResultType.getUnqualifiedType(), Qs)); 4136 } 4137 4138 return CanResultType; 4139 } 4140 4141 static bool isCanonicalExceptionSpecification( 4142 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) { 4143 if (ESI.Type == EST_None) 4144 return true; 4145 if (!NoexceptInType) 4146 return false; 4147 4148 // C++17 onwards: exception specification is part of the type, as a simple 4149 // boolean "can this function type throw". 4150 if (ESI.Type == EST_BasicNoexcept) 4151 return true; 4152 4153 // A noexcept(expr) specification is (possibly) canonical if expr is 4154 // value-dependent. 4155 if (ESI.Type == EST_DependentNoexcept) 4156 return true; 4157 4158 // A dynamic exception specification is canonical if it only contains pack 4159 // expansions (so we can't tell whether it's non-throwing) and all its 4160 // contained types are canonical. 4161 if (ESI.Type == EST_Dynamic) { 4162 bool AnyPackExpansions = false; 4163 for (QualType ET : ESI.Exceptions) { 4164 if (!ET.isCanonical()) 4165 return false; 4166 if (ET->getAs<PackExpansionType>()) 4167 AnyPackExpansions = true; 4168 } 4169 return AnyPackExpansions; 4170 } 4171 4172 return false; 4173 } 4174 4175 QualType ASTContext::getFunctionTypeInternal( 4176 QualType ResultTy, ArrayRef<QualType> ArgArray, 4177 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const { 4178 size_t NumArgs = ArgArray.size(); 4179 4180 // Unique functions, to guarantee there is only one function of a particular 4181 // structure. 4182 llvm::FoldingSetNodeID ID; 4183 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI, 4184 *this, true); 4185 4186 QualType Canonical; 4187 bool Unique = false; 4188 4189 void *InsertPos = nullptr; 4190 if (FunctionProtoType *FPT = 4191 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) { 4192 QualType Existing = QualType(FPT, 0); 4193 4194 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse 4195 // it so long as our exception specification doesn't contain a dependent 4196 // noexcept expression, or we're just looking for a canonical type. 4197 // Otherwise, we're going to need to create a type 4198 // sugar node to hold the concrete expression. 4199 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) || 4200 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr()) 4201 return Existing; 4202 4203 // We need a new type sugar node for this one, to hold the new noexcept 4204 // expression. We do no canonicalization here, but that's OK since we don't 4205 // expect to see the same noexcept expression much more than once. 4206 Canonical = getCanonicalType(Existing); 4207 Unique = true; 4208 } 4209 4210 bool NoexceptInType = getLangOpts().CPlusPlus17; 4211 bool IsCanonicalExceptionSpec = 4212 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType); 4213 4214 // Determine whether the type being created is already canonical or not. 4215 bool isCanonical = !Unique && IsCanonicalExceptionSpec && 4216 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn; 4217 for (unsigned i = 0; i != NumArgs && isCanonical; ++i) 4218 if (!ArgArray[i].isCanonicalAsParam()) 4219 isCanonical = false; 4220 4221 if (OnlyWantCanonical) 4222 assert(isCanonical && 4223 "given non-canonical parameters constructing canonical type"); 4224 4225 // If this type isn't canonical, get the canonical version of it if we don't 4226 // already have it. The exception spec is only partially part of the 4227 // canonical type, and only in C++17 onwards. 4228 if (!isCanonical && Canonical.isNull()) { 4229 SmallVector<QualType, 16> CanonicalArgs; 4230 CanonicalArgs.reserve(NumArgs); 4231 for (unsigned i = 0; i != NumArgs; ++i) 4232 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i])); 4233 4234 llvm::SmallVector<QualType, 8> ExceptionTypeStorage; 4235 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI; 4236 CanonicalEPI.HasTrailingReturn = false; 4237 4238 if (IsCanonicalExceptionSpec) { 4239 // Exception spec is already OK. 4240 } else if (NoexceptInType) { 4241 switch (EPI.ExceptionSpec.Type) { 4242 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated: 4243 // We don't know yet. It shouldn't matter what we pick here; no-one 4244 // should ever look at this. 4245 LLVM_FALLTHROUGH; 4246 case EST_None: case EST_MSAny: case EST_NoexceptFalse: 4247 CanonicalEPI.ExceptionSpec.Type = EST_None; 4248 break; 4249 4250 // A dynamic exception specification is almost always "not noexcept", 4251 // with the exception that a pack expansion might expand to no types. 4252 case EST_Dynamic: { 4253 bool AnyPacks = false; 4254 for (QualType ET : EPI.ExceptionSpec.Exceptions) { 4255 if (ET->getAs<PackExpansionType>()) 4256 AnyPacks = true; 4257 ExceptionTypeStorage.push_back(getCanonicalType(ET)); 4258 } 4259 if (!AnyPacks) 4260 CanonicalEPI.ExceptionSpec.Type = EST_None; 4261 else { 4262 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic; 4263 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage; 4264 } 4265 break; 4266 } 4267 4268 case EST_DynamicNone: 4269 case EST_BasicNoexcept: 4270 case EST_NoexceptTrue: 4271 case EST_NoThrow: 4272 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept; 4273 break; 4274 4275 case EST_DependentNoexcept: 4276 llvm_unreachable("dependent noexcept is already canonical"); 4277 } 4278 } else { 4279 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo(); 4280 } 4281 4282 // Adjust the canonical function result type. 4283 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy); 4284 Canonical = 4285 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true); 4286 4287 // Get the new insert position for the node we care about. 4288 FunctionProtoType *NewIP = 4289 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 4290 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4291 } 4292 4293 // Compute the needed size to hold this FunctionProtoType and the 4294 // various trailing objects. 4295 auto ESH = FunctionProtoType::getExceptionSpecSize( 4296 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size()); 4297 size_t Size = FunctionProtoType::totalSizeToAlloc< 4298 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields, 4299 FunctionType::ExceptionType, Expr *, FunctionDecl *, 4300 FunctionProtoType::ExtParameterInfo, Qualifiers>( 4301 NumArgs, EPI.Variadic, 4302 FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type), 4303 ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr, 4304 EPI.ExtParameterInfos ? NumArgs : 0, 4305 EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0); 4306 4307 auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment); 4308 FunctionProtoType::ExtProtoInfo newEPI = EPI; 4309 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI); 4310 Types.push_back(FTP); 4311 if (!Unique) 4312 FunctionProtoTypes.InsertNode(FTP, InsertPos); 4313 return QualType(FTP, 0); 4314 } 4315 4316 QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const { 4317 llvm::FoldingSetNodeID ID; 4318 PipeType::Profile(ID, T, ReadOnly); 4319 4320 void *InsertPos = nullptr; 4321 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos)) 4322 return QualType(PT, 0); 4323 4324 // If the pipe element type isn't canonical, this won't be a canonical type 4325 // either, so fill in the canonical type field. 4326 QualType Canonical; 4327 if (!T.isCanonical()) { 4328 Canonical = getPipeType(getCanonicalType(T), ReadOnly); 4329 4330 // Get the new insert position for the node we care about. 4331 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos); 4332 assert(!NewIP && "Shouldn't be in the map!"); 4333 (void)NewIP; 4334 } 4335 auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly); 4336 Types.push_back(New); 4337 PipeTypes.InsertNode(New, InsertPos); 4338 return QualType(New, 0); 4339 } 4340 4341 QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const { 4342 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 4343 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant) 4344 : Ty; 4345 } 4346 4347 QualType ASTContext::getReadPipeType(QualType T) const { 4348 return getPipeType(T, true); 4349 } 4350 4351 QualType ASTContext::getWritePipeType(QualType T) const { 4352 return getPipeType(T, false); 4353 } 4354 4355 QualType ASTContext::getExtIntType(bool IsUnsigned, unsigned NumBits) const { 4356 llvm::FoldingSetNodeID ID; 4357 ExtIntType::Profile(ID, IsUnsigned, NumBits); 4358 4359 void *InsertPos = nullptr; 4360 if (ExtIntType *EIT = ExtIntTypes.FindNodeOrInsertPos(ID, InsertPos)) 4361 return QualType(EIT, 0); 4362 4363 auto *New = new (*this, TypeAlignment) ExtIntType(IsUnsigned, NumBits); 4364 ExtIntTypes.InsertNode(New, InsertPos); 4365 Types.push_back(New); 4366 return QualType(New, 0); 4367 } 4368 4369 QualType ASTContext::getDependentExtIntType(bool IsUnsigned, 4370 Expr *NumBitsExpr) const { 4371 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent"); 4372 llvm::FoldingSetNodeID ID; 4373 DependentExtIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr); 4374 4375 void *InsertPos = nullptr; 4376 if (DependentExtIntType *Existing = 4377 DependentExtIntTypes.FindNodeOrInsertPos(ID, InsertPos)) 4378 return QualType(Existing, 0); 4379 4380 auto *New = new (*this, TypeAlignment) 4381 DependentExtIntType(*this, IsUnsigned, NumBitsExpr); 4382 DependentExtIntTypes.InsertNode(New, InsertPos); 4383 4384 Types.push_back(New); 4385 return QualType(New, 0); 4386 } 4387 4388 #ifndef NDEBUG 4389 static bool NeedsInjectedClassNameType(const RecordDecl *D) { 4390 if (!isa<CXXRecordDecl>(D)) return false; 4391 const auto *RD = cast<CXXRecordDecl>(D); 4392 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) 4393 return true; 4394 if (RD->getDescribedClassTemplate() && 4395 !isa<ClassTemplateSpecializationDecl>(RD)) 4396 return true; 4397 return false; 4398 } 4399 #endif 4400 4401 /// getInjectedClassNameType - Return the unique reference to the 4402 /// injected class name type for the specified templated declaration. 4403 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl, 4404 QualType TST) const { 4405 assert(NeedsInjectedClassNameType(Decl)); 4406 if (Decl->TypeForDecl) { 4407 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 4408 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) { 4409 assert(PrevDecl->TypeForDecl && "previous declaration has no type"); 4410 Decl->TypeForDecl = PrevDecl->TypeForDecl; 4411 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 4412 } else { 4413 Type *newType = 4414 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST); 4415 Decl->TypeForDecl = newType; 4416 Types.push_back(newType); 4417 } 4418 return QualType(Decl->TypeForDecl, 0); 4419 } 4420 4421 /// getTypeDeclType - Return the unique reference to the type for the 4422 /// specified type declaration. 4423 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const { 4424 assert(Decl && "Passed null for Decl param"); 4425 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case"); 4426 4427 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl)) 4428 return getTypedefType(Typedef); 4429 4430 assert(!isa<TemplateTypeParmDecl>(Decl) && 4431 "Template type parameter types are always available."); 4432 4433 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) { 4434 assert(Record->isFirstDecl() && "struct/union has previous declaration"); 4435 assert(!NeedsInjectedClassNameType(Record)); 4436 return getRecordType(Record); 4437 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) { 4438 assert(Enum->isFirstDecl() && "enum has previous declaration"); 4439 return getEnumType(Enum); 4440 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) { 4441 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using); 4442 Decl->TypeForDecl = newType; 4443 Types.push_back(newType); 4444 } else 4445 llvm_unreachable("TypeDecl without a type?"); 4446 4447 return QualType(Decl->TypeForDecl, 0); 4448 } 4449 4450 /// getTypedefType - Return the unique reference to the type for the 4451 /// specified typedef name decl. 4452 QualType ASTContext::getTypedefType(const TypedefNameDecl *Decl, 4453 QualType Underlying) const { 4454 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 4455 4456 if (Underlying.isNull()) 4457 Underlying = Decl->getUnderlyingType(); 4458 QualType Canonical = getCanonicalType(Underlying); 4459 auto *newType = new (*this, TypeAlignment) 4460 TypedefType(Type::Typedef, Decl, Underlying, Canonical); 4461 Decl->TypeForDecl = newType; 4462 Types.push_back(newType); 4463 return QualType(newType, 0); 4464 } 4465 4466 QualType ASTContext::getRecordType(const RecordDecl *Decl) const { 4467 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 4468 4469 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl()) 4470 if (PrevDecl->TypeForDecl) 4471 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 4472 4473 auto *newType = new (*this, TypeAlignment) RecordType(Decl); 4474 Decl->TypeForDecl = newType; 4475 Types.push_back(newType); 4476 return QualType(newType, 0); 4477 } 4478 4479 QualType ASTContext::getEnumType(const EnumDecl *Decl) const { 4480 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 4481 4482 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl()) 4483 if (PrevDecl->TypeForDecl) 4484 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 4485 4486 auto *newType = new (*this, TypeAlignment) EnumType(Decl); 4487 Decl->TypeForDecl = newType; 4488 Types.push_back(newType); 4489 return QualType(newType, 0); 4490 } 4491 4492 QualType ASTContext::getAttributedType(attr::Kind attrKind, 4493 QualType modifiedType, 4494 QualType equivalentType) { 4495 llvm::FoldingSetNodeID id; 4496 AttributedType::Profile(id, attrKind, modifiedType, equivalentType); 4497 4498 void *insertPos = nullptr; 4499 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos); 4500 if (type) return QualType(type, 0); 4501 4502 QualType canon = getCanonicalType(equivalentType); 4503 type = new (*this, TypeAlignment) 4504 AttributedType(canon, attrKind, modifiedType, equivalentType); 4505 4506 Types.push_back(type); 4507 AttributedTypes.InsertNode(type, insertPos); 4508 4509 return QualType(type, 0); 4510 } 4511 4512 /// Retrieve a substitution-result type. 4513 QualType 4514 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm, 4515 QualType Replacement) const { 4516 assert(Replacement.isCanonical() 4517 && "replacement types must always be canonical"); 4518 4519 llvm::FoldingSetNodeID ID; 4520 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement); 4521 void *InsertPos = nullptr; 4522 SubstTemplateTypeParmType *SubstParm 4523 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 4524 4525 if (!SubstParm) { 4526 SubstParm = new (*this, TypeAlignment) 4527 SubstTemplateTypeParmType(Parm, Replacement); 4528 Types.push_back(SubstParm); 4529 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos); 4530 } 4531 4532 return QualType(SubstParm, 0); 4533 } 4534 4535 /// Retrieve a 4536 QualType ASTContext::getSubstTemplateTypeParmPackType( 4537 const TemplateTypeParmType *Parm, 4538 const TemplateArgument &ArgPack) { 4539 #ifndef NDEBUG 4540 for (const auto &P : ArgPack.pack_elements()) { 4541 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type"); 4542 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type"); 4543 } 4544 #endif 4545 4546 llvm::FoldingSetNodeID ID; 4547 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack); 4548 void *InsertPos = nullptr; 4549 if (SubstTemplateTypeParmPackType *SubstParm 4550 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos)) 4551 return QualType(SubstParm, 0); 4552 4553 QualType Canon; 4554 if (!Parm->isCanonicalUnqualified()) { 4555 Canon = getCanonicalType(QualType(Parm, 0)); 4556 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon), 4557 ArgPack); 4558 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos); 4559 } 4560 4561 auto *SubstParm 4562 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon, 4563 ArgPack); 4564 Types.push_back(SubstParm); 4565 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos); 4566 return QualType(SubstParm, 0); 4567 } 4568 4569 /// Retrieve the template type parameter type for a template 4570 /// parameter or parameter pack with the given depth, index, and (optionally) 4571 /// name. 4572 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index, 4573 bool ParameterPack, 4574 TemplateTypeParmDecl *TTPDecl) const { 4575 llvm::FoldingSetNodeID ID; 4576 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl); 4577 void *InsertPos = nullptr; 4578 TemplateTypeParmType *TypeParm 4579 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 4580 4581 if (TypeParm) 4582 return QualType(TypeParm, 0); 4583 4584 if (TTPDecl) { 4585 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack); 4586 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon); 4587 4588 TemplateTypeParmType *TypeCheck 4589 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 4590 assert(!TypeCheck && "Template type parameter canonical type broken"); 4591 (void)TypeCheck; 4592 } else 4593 TypeParm = new (*this, TypeAlignment) 4594 TemplateTypeParmType(Depth, Index, ParameterPack); 4595 4596 Types.push_back(TypeParm); 4597 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos); 4598 4599 return QualType(TypeParm, 0); 4600 } 4601 4602 TypeSourceInfo * 4603 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name, 4604 SourceLocation NameLoc, 4605 const TemplateArgumentListInfo &Args, 4606 QualType Underlying) const { 4607 assert(!Name.getAsDependentTemplateName() && 4608 "No dependent template names here!"); 4609 QualType TST = getTemplateSpecializationType(Name, Args, Underlying); 4610 4611 TypeSourceInfo *DI = CreateTypeSourceInfo(TST); 4612 TemplateSpecializationTypeLoc TL = 4613 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>(); 4614 TL.setTemplateKeywordLoc(SourceLocation()); 4615 TL.setTemplateNameLoc(NameLoc); 4616 TL.setLAngleLoc(Args.getLAngleLoc()); 4617 TL.setRAngleLoc(Args.getRAngleLoc()); 4618 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 4619 TL.setArgLocInfo(i, Args[i].getLocInfo()); 4620 return DI; 4621 } 4622 4623 QualType 4624 ASTContext::getTemplateSpecializationType(TemplateName Template, 4625 const TemplateArgumentListInfo &Args, 4626 QualType Underlying) const { 4627 assert(!Template.getAsDependentTemplateName() && 4628 "No dependent template names here!"); 4629 4630 SmallVector<TemplateArgument, 4> ArgVec; 4631 ArgVec.reserve(Args.size()); 4632 for (const TemplateArgumentLoc &Arg : Args.arguments()) 4633 ArgVec.push_back(Arg.getArgument()); 4634 4635 return getTemplateSpecializationType(Template, ArgVec, Underlying); 4636 } 4637 4638 #ifndef NDEBUG 4639 static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) { 4640 for (const TemplateArgument &Arg : Args) 4641 if (Arg.isPackExpansion()) 4642 return true; 4643 4644 return true; 4645 } 4646 #endif 4647 4648 QualType 4649 ASTContext::getTemplateSpecializationType(TemplateName Template, 4650 ArrayRef<TemplateArgument> Args, 4651 QualType Underlying) const { 4652 assert(!Template.getAsDependentTemplateName() && 4653 "No dependent template names here!"); 4654 // Look through qualified template names. 4655 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 4656 Template = TemplateName(QTN->getTemplateDecl()); 4657 4658 bool IsTypeAlias = 4659 Template.getAsTemplateDecl() && 4660 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl()); 4661 QualType CanonType; 4662 if (!Underlying.isNull()) 4663 CanonType = getCanonicalType(Underlying); 4664 else { 4665 // We can get here with an alias template when the specialization contains 4666 // a pack expansion that does not match up with a parameter pack. 4667 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) && 4668 "Caller must compute aliased type"); 4669 IsTypeAlias = false; 4670 CanonType = getCanonicalTemplateSpecializationType(Template, Args); 4671 } 4672 4673 // Allocate the (non-canonical) template specialization type, but don't 4674 // try to unique it: these types typically have location information that 4675 // we don't unique and don't want to lose. 4676 void *Mem = Allocate(sizeof(TemplateSpecializationType) + 4677 sizeof(TemplateArgument) * Args.size() + 4678 (IsTypeAlias? sizeof(QualType) : 0), 4679 TypeAlignment); 4680 auto *Spec 4681 = new (Mem) TemplateSpecializationType(Template, Args, CanonType, 4682 IsTypeAlias ? Underlying : QualType()); 4683 4684 Types.push_back(Spec); 4685 return QualType(Spec, 0); 4686 } 4687 4688 QualType ASTContext::getCanonicalTemplateSpecializationType( 4689 TemplateName Template, ArrayRef<TemplateArgument> Args) const { 4690 assert(!Template.getAsDependentTemplateName() && 4691 "No dependent template names here!"); 4692 4693 // Look through qualified template names. 4694 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 4695 Template = TemplateName(QTN->getTemplateDecl()); 4696 4697 // Build the canonical template specialization type. 4698 TemplateName CanonTemplate = getCanonicalTemplateName(Template); 4699 SmallVector<TemplateArgument, 4> CanonArgs; 4700 unsigned NumArgs = Args.size(); 4701 CanonArgs.reserve(NumArgs); 4702 for (const TemplateArgument &Arg : Args) 4703 CanonArgs.push_back(getCanonicalTemplateArgument(Arg)); 4704 4705 // Determine whether this canonical template specialization type already 4706 // exists. 4707 llvm::FoldingSetNodeID ID; 4708 TemplateSpecializationType::Profile(ID, CanonTemplate, 4709 CanonArgs, *this); 4710 4711 void *InsertPos = nullptr; 4712 TemplateSpecializationType *Spec 4713 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 4714 4715 if (!Spec) { 4716 // Allocate a new canonical template specialization type. 4717 void *Mem = Allocate((sizeof(TemplateSpecializationType) + 4718 sizeof(TemplateArgument) * NumArgs), 4719 TypeAlignment); 4720 Spec = new (Mem) TemplateSpecializationType(CanonTemplate, 4721 CanonArgs, 4722 QualType(), QualType()); 4723 Types.push_back(Spec); 4724 TemplateSpecializationTypes.InsertNode(Spec, InsertPos); 4725 } 4726 4727 assert(Spec->isDependentType() && 4728 "Non-dependent template-id type must have a canonical type"); 4729 return QualType(Spec, 0); 4730 } 4731 4732 QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword, 4733 NestedNameSpecifier *NNS, 4734 QualType NamedType, 4735 TagDecl *OwnedTagDecl) const { 4736 llvm::FoldingSetNodeID ID; 4737 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl); 4738 4739 void *InsertPos = nullptr; 4740 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 4741 if (T) 4742 return QualType(T, 0); 4743 4744 QualType Canon = NamedType; 4745 if (!Canon.isCanonical()) { 4746 Canon = getCanonicalType(NamedType); 4747 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 4748 assert(!CheckT && "Elaborated canonical type broken"); 4749 (void)CheckT; 4750 } 4751 4752 void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl), 4753 TypeAlignment); 4754 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl); 4755 4756 Types.push_back(T); 4757 ElaboratedTypes.InsertNode(T, InsertPos); 4758 return QualType(T, 0); 4759 } 4760 4761 QualType 4762 ASTContext::getParenType(QualType InnerType) const { 4763 llvm::FoldingSetNodeID ID; 4764 ParenType::Profile(ID, InnerType); 4765 4766 void *InsertPos = nullptr; 4767 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 4768 if (T) 4769 return QualType(T, 0); 4770 4771 QualType Canon = InnerType; 4772 if (!Canon.isCanonical()) { 4773 Canon = getCanonicalType(InnerType); 4774 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 4775 assert(!CheckT && "Paren canonical type broken"); 4776 (void)CheckT; 4777 } 4778 4779 T = new (*this, TypeAlignment) ParenType(InnerType, Canon); 4780 Types.push_back(T); 4781 ParenTypes.InsertNode(T, InsertPos); 4782 return QualType(T, 0); 4783 } 4784 4785 QualType 4786 ASTContext::getMacroQualifiedType(QualType UnderlyingTy, 4787 const IdentifierInfo *MacroII) const { 4788 QualType Canon = UnderlyingTy; 4789 if (!Canon.isCanonical()) 4790 Canon = getCanonicalType(UnderlyingTy); 4791 4792 auto *newType = new (*this, TypeAlignment) 4793 MacroQualifiedType(UnderlyingTy, Canon, MacroII); 4794 Types.push_back(newType); 4795 return QualType(newType, 0); 4796 } 4797 4798 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword, 4799 NestedNameSpecifier *NNS, 4800 const IdentifierInfo *Name, 4801 QualType Canon) const { 4802 if (Canon.isNull()) { 4803 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 4804 if (CanonNNS != NNS) 4805 Canon = getDependentNameType(Keyword, CanonNNS, Name); 4806 } 4807 4808 llvm::FoldingSetNodeID ID; 4809 DependentNameType::Profile(ID, Keyword, NNS, Name); 4810 4811 void *InsertPos = nullptr; 4812 DependentNameType *T 4813 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos); 4814 if (T) 4815 return QualType(T, 0); 4816 4817 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon); 4818 Types.push_back(T); 4819 DependentNameTypes.InsertNode(T, InsertPos); 4820 return QualType(T, 0); 4821 } 4822 4823 QualType 4824 ASTContext::getDependentTemplateSpecializationType( 4825 ElaboratedTypeKeyword Keyword, 4826 NestedNameSpecifier *NNS, 4827 const IdentifierInfo *Name, 4828 const TemplateArgumentListInfo &Args) const { 4829 // TODO: avoid this copy 4830 SmallVector<TemplateArgument, 16> ArgCopy; 4831 for (unsigned I = 0, E = Args.size(); I != E; ++I) 4832 ArgCopy.push_back(Args[I].getArgument()); 4833 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy); 4834 } 4835 4836 QualType 4837 ASTContext::getDependentTemplateSpecializationType( 4838 ElaboratedTypeKeyword Keyword, 4839 NestedNameSpecifier *NNS, 4840 const IdentifierInfo *Name, 4841 ArrayRef<TemplateArgument> Args) const { 4842 assert((!NNS || NNS->isDependent()) && 4843 "nested-name-specifier must be dependent"); 4844 4845 llvm::FoldingSetNodeID ID; 4846 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS, 4847 Name, Args); 4848 4849 void *InsertPos = nullptr; 4850 DependentTemplateSpecializationType *T 4851 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 4852 if (T) 4853 return QualType(T, 0); 4854 4855 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 4856 4857 ElaboratedTypeKeyword CanonKeyword = Keyword; 4858 if (Keyword == ETK_None) CanonKeyword = ETK_Typename; 4859 4860 bool AnyNonCanonArgs = false; 4861 unsigned NumArgs = Args.size(); 4862 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs); 4863 for (unsigned I = 0; I != NumArgs; ++I) { 4864 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]); 4865 if (!CanonArgs[I].structurallyEquals(Args[I])) 4866 AnyNonCanonArgs = true; 4867 } 4868 4869 QualType Canon; 4870 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) { 4871 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS, 4872 Name, 4873 CanonArgs); 4874 4875 // Find the insert position again. 4876 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 4877 } 4878 4879 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) + 4880 sizeof(TemplateArgument) * NumArgs), 4881 TypeAlignment); 4882 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS, 4883 Name, Args, Canon); 4884 Types.push_back(T); 4885 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos); 4886 return QualType(T, 0); 4887 } 4888 4889 TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) { 4890 TemplateArgument Arg; 4891 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) { 4892 QualType ArgType = getTypeDeclType(TTP); 4893 if (TTP->isParameterPack()) 4894 ArgType = getPackExpansionType(ArgType, None); 4895 4896 Arg = TemplateArgument(ArgType); 4897 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 4898 QualType T = 4899 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this); 4900 // For class NTTPs, ensure we include the 'const' so the type matches that 4901 // of a real template argument. 4902 // FIXME: It would be more faithful to model this as something like an 4903 // lvalue-to-rvalue conversion applied to a const-qualified lvalue. 4904 if (T->isRecordType()) 4905 T.addConst(); 4906 Expr *E = new (*this) DeclRefExpr( 4907 *this, NTTP, /*enclosing*/ false, T, 4908 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation()); 4909 4910 if (NTTP->isParameterPack()) 4911 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(), 4912 None); 4913 Arg = TemplateArgument(E); 4914 } else { 4915 auto *TTP = cast<TemplateTemplateParmDecl>(Param); 4916 if (TTP->isParameterPack()) 4917 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>()); 4918 else 4919 Arg = TemplateArgument(TemplateName(TTP)); 4920 } 4921 4922 if (Param->isTemplateParameterPack()) 4923 Arg = TemplateArgument::CreatePackCopy(*this, Arg); 4924 4925 return Arg; 4926 } 4927 4928 void 4929 ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params, 4930 SmallVectorImpl<TemplateArgument> &Args) { 4931 Args.reserve(Args.size() + Params->size()); 4932 4933 for (NamedDecl *Param : *Params) 4934 Args.push_back(getInjectedTemplateArg(Param)); 4935 } 4936 4937 QualType ASTContext::getPackExpansionType(QualType Pattern, 4938 Optional<unsigned> NumExpansions, 4939 bool ExpectPackInType) { 4940 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) && 4941 "Pack expansions must expand one or more parameter packs"); 4942 4943 llvm::FoldingSetNodeID ID; 4944 PackExpansionType::Profile(ID, Pattern, NumExpansions); 4945 4946 void *InsertPos = nullptr; 4947 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 4948 if (T) 4949 return QualType(T, 0); 4950 4951 QualType Canon; 4952 if (!Pattern.isCanonical()) { 4953 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions, 4954 /*ExpectPackInType=*/false); 4955 4956 // Find the insert position again, in case we inserted an element into 4957 // PackExpansionTypes and invalidated our insert position. 4958 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 4959 } 4960 4961 T = new (*this, TypeAlignment) 4962 PackExpansionType(Pattern, Canon, NumExpansions); 4963 Types.push_back(T); 4964 PackExpansionTypes.InsertNode(T, InsertPos); 4965 return QualType(T, 0); 4966 } 4967 4968 /// CmpProtocolNames - Comparison predicate for sorting protocols 4969 /// alphabetically. 4970 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS, 4971 ObjCProtocolDecl *const *RHS) { 4972 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName()); 4973 } 4974 4975 static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) { 4976 if (Protocols.empty()) return true; 4977 4978 if (Protocols[0]->getCanonicalDecl() != Protocols[0]) 4979 return false; 4980 4981 for (unsigned i = 1; i != Protocols.size(); ++i) 4982 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 || 4983 Protocols[i]->getCanonicalDecl() != Protocols[i]) 4984 return false; 4985 return true; 4986 } 4987 4988 static void 4989 SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) { 4990 // Sort protocols, keyed by name. 4991 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames); 4992 4993 // Canonicalize. 4994 for (ObjCProtocolDecl *&P : Protocols) 4995 P = P->getCanonicalDecl(); 4996 4997 // Remove duplicates. 4998 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end()); 4999 Protocols.erase(ProtocolsEnd, Protocols.end()); 5000 } 5001 5002 QualType ASTContext::getObjCObjectType(QualType BaseType, 5003 ObjCProtocolDecl * const *Protocols, 5004 unsigned NumProtocols) const { 5005 return getObjCObjectType(BaseType, {}, 5006 llvm::makeArrayRef(Protocols, NumProtocols), 5007 /*isKindOf=*/false); 5008 } 5009 5010 QualType ASTContext::getObjCObjectType( 5011 QualType baseType, 5012 ArrayRef<QualType> typeArgs, 5013 ArrayRef<ObjCProtocolDecl *> protocols, 5014 bool isKindOf) const { 5015 // If the base type is an interface and there aren't any protocols or 5016 // type arguments to add, then the interface type will do just fine. 5017 if (typeArgs.empty() && protocols.empty() && !isKindOf && 5018 isa<ObjCInterfaceType>(baseType)) 5019 return baseType; 5020 5021 // Look in the folding set for an existing type. 5022 llvm::FoldingSetNodeID ID; 5023 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf); 5024 void *InsertPos = nullptr; 5025 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos)) 5026 return QualType(QT, 0); 5027 5028 // Determine the type arguments to be used for canonicalization, 5029 // which may be explicitly specified here or written on the base 5030 // type. 5031 ArrayRef<QualType> effectiveTypeArgs = typeArgs; 5032 if (effectiveTypeArgs.empty()) { 5033 if (const auto *baseObject = baseType->getAs<ObjCObjectType>()) 5034 effectiveTypeArgs = baseObject->getTypeArgs(); 5035 } 5036 5037 // Build the canonical type, which has the canonical base type and a 5038 // sorted-and-uniqued list of protocols and the type arguments 5039 // canonicalized. 5040 QualType canonical; 5041 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(), 5042 effectiveTypeArgs.end(), 5043 [&](QualType type) { 5044 return type.isCanonical(); 5045 }); 5046 bool protocolsSorted = areSortedAndUniqued(protocols); 5047 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) { 5048 // Determine the canonical type arguments. 5049 ArrayRef<QualType> canonTypeArgs; 5050 SmallVector<QualType, 4> canonTypeArgsVec; 5051 if (!typeArgsAreCanonical) { 5052 canonTypeArgsVec.reserve(effectiveTypeArgs.size()); 5053 for (auto typeArg : effectiveTypeArgs) 5054 canonTypeArgsVec.push_back(getCanonicalType(typeArg)); 5055 canonTypeArgs = canonTypeArgsVec; 5056 } else { 5057 canonTypeArgs = effectiveTypeArgs; 5058 } 5059 5060 ArrayRef<ObjCProtocolDecl *> canonProtocols; 5061 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec; 5062 if (!protocolsSorted) { 5063 canonProtocolsVec.append(protocols.begin(), protocols.end()); 5064 SortAndUniqueProtocols(canonProtocolsVec); 5065 canonProtocols = canonProtocolsVec; 5066 } else { 5067 canonProtocols = protocols; 5068 } 5069 5070 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs, 5071 canonProtocols, isKindOf); 5072 5073 // Regenerate InsertPos. 5074 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos); 5075 } 5076 5077 unsigned size = sizeof(ObjCObjectTypeImpl); 5078 size += typeArgs.size() * sizeof(QualType); 5079 size += protocols.size() * sizeof(ObjCProtocolDecl *); 5080 void *mem = Allocate(size, TypeAlignment); 5081 auto *T = 5082 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols, 5083 isKindOf); 5084 5085 Types.push_back(T); 5086 ObjCObjectTypes.InsertNode(T, InsertPos); 5087 return QualType(T, 0); 5088 } 5089 5090 /// Apply Objective-C protocol qualifiers to the given type. 5091 /// If this is for the canonical type of a type parameter, we can apply 5092 /// protocol qualifiers on the ObjCObjectPointerType. 5093 QualType 5094 ASTContext::applyObjCProtocolQualifiers(QualType type, 5095 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError, 5096 bool allowOnPointerType) const { 5097 hasError = false; 5098 5099 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) { 5100 return getObjCTypeParamType(objT->getDecl(), protocols); 5101 } 5102 5103 // Apply protocol qualifiers to ObjCObjectPointerType. 5104 if (allowOnPointerType) { 5105 if (const auto *objPtr = 5106 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) { 5107 const ObjCObjectType *objT = objPtr->getObjectType(); 5108 // Merge protocol lists and construct ObjCObjectType. 5109 SmallVector<ObjCProtocolDecl*, 8> protocolsVec; 5110 protocolsVec.append(objT->qual_begin(), 5111 objT->qual_end()); 5112 protocolsVec.append(protocols.begin(), protocols.end()); 5113 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec; 5114 type = getObjCObjectType( 5115 objT->getBaseType(), 5116 objT->getTypeArgsAsWritten(), 5117 protocols, 5118 objT->isKindOfTypeAsWritten()); 5119 return getObjCObjectPointerType(type); 5120 } 5121 } 5122 5123 // Apply protocol qualifiers to ObjCObjectType. 5124 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){ 5125 // FIXME: Check for protocols to which the class type is already 5126 // known to conform. 5127 5128 return getObjCObjectType(objT->getBaseType(), 5129 objT->getTypeArgsAsWritten(), 5130 protocols, 5131 objT->isKindOfTypeAsWritten()); 5132 } 5133 5134 // If the canonical type is ObjCObjectType, ... 5135 if (type->isObjCObjectType()) { 5136 // Silently overwrite any existing protocol qualifiers. 5137 // TODO: determine whether that's the right thing to do. 5138 5139 // FIXME: Check for protocols to which the class type is already 5140 // known to conform. 5141 return getObjCObjectType(type, {}, protocols, false); 5142 } 5143 5144 // id<protocol-list> 5145 if (type->isObjCIdType()) { 5146 const auto *objPtr = type->castAs<ObjCObjectPointerType>(); 5147 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols, 5148 objPtr->isKindOfType()); 5149 return getObjCObjectPointerType(type); 5150 } 5151 5152 // Class<protocol-list> 5153 if (type->isObjCClassType()) { 5154 const auto *objPtr = type->castAs<ObjCObjectPointerType>(); 5155 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols, 5156 objPtr->isKindOfType()); 5157 return getObjCObjectPointerType(type); 5158 } 5159 5160 hasError = true; 5161 return type; 5162 } 5163 5164 QualType 5165 ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl, 5166 ArrayRef<ObjCProtocolDecl *> protocols) const { 5167 // Look in the folding set for an existing type. 5168 llvm::FoldingSetNodeID ID; 5169 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols); 5170 void *InsertPos = nullptr; 5171 if (ObjCTypeParamType *TypeParam = 5172 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos)) 5173 return QualType(TypeParam, 0); 5174 5175 // We canonicalize to the underlying type. 5176 QualType Canonical = getCanonicalType(Decl->getUnderlyingType()); 5177 if (!protocols.empty()) { 5178 // Apply the protocol qualifers. 5179 bool hasError; 5180 Canonical = getCanonicalType(applyObjCProtocolQualifiers( 5181 Canonical, protocols, hasError, true /*allowOnPointerType*/)); 5182 assert(!hasError && "Error when apply protocol qualifier to bound type"); 5183 } 5184 5185 unsigned size = sizeof(ObjCTypeParamType); 5186 size += protocols.size() * sizeof(ObjCProtocolDecl *); 5187 void *mem = Allocate(size, TypeAlignment); 5188 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols); 5189 5190 Types.push_back(newType); 5191 ObjCTypeParamTypes.InsertNode(newType, InsertPos); 5192 return QualType(newType, 0); 5193 } 5194 5195 void ASTContext::adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig, 5196 ObjCTypeParamDecl *New) const { 5197 New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType())); 5198 // Update TypeForDecl after updating TypeSourceInfo. 5199 auto NewTypeParamTy = cast<ObjCTypeParamType>(New->getTypeForDecl()); 5200 SmallVector<ObjCProtocolDecl *, 8> protocols; 5201 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end()); 5202 QualType UpdatedTy = getObjCTypeParamType(New, protocols); 5203 New->setTypeForDecl(UpdatedTy.getTypePtr()); 5204 } 5205 5206 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's 5207 /// protocol list adopt all protocols in QT's qualified-id protocol 5208 /// list. 5209 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT, 5210 ObjCInterfaceDecl *IC) { 5211 if (!QT->isObjCQualifiedIdType()) 5212 return false; 5213 5214 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) { 5215 // If both the right and left sides have qualifiers. 5216 for (auto *Proto : OPT->quals()) { 5217 if (!IC->ClassImplementsProtocol(Proto, false)) 5218 return false; 5219 } 5220 return true; 5221 } 5222 return false; 5223 } 5224 5225 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in 5226 /// QT's qualified-id protocol list adopt all protocols in IDecl's list 5227 /// of protocols. 5228 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT, 5229 ObjCInterfaceDecl *IDecl) { 5230 if (!QT->isObjCQualifiedIdType()) 5231 return false; 5232 const auto *OPT = QT->getAs<ObjCObjectPointerType>(); 5233 if (!OPT) 5234 return false; 5235 if (!IDecl->hasDefinition()) 5236 return false; 5237 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols; 5238 CollectInheritedProtocols(IDecl, InheritedProtocols); 5239 if (InheritedProtocols.empty()) 5240 return false; 5241 // Check that if every protocol in list of id<plist> conforms to a protocol 5242 // of IDecl's, then bridge casting is ok. 5243 bool Conforms = false; 5244 for (auto *Proto : OPT->quals()) { 5245 Conforms = false; 5246 for (auto *PI : InheritedProtocols) { 5247 if (ProtocolCompatibleWithProtocol(Proto, PI)) { 5248 Conforms = true; 5249 break; 5250 } 5251 } 5252 if (!Conforms) 5253 break; 5254 } 5255 if (Conforms) 5256 return true; 5257 5258 for (auto *PI : InheritedProtocols) { 5259 // If both the right and left sides have qualifiers. 5260 bool Adopts = false; 5261 for (auto *Proto : OPT->quals()) { 5262 // return 'true' if 'PI' is in the inheritance hierarchy of Proto 5263 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto))) 5264 break; 5265 } 5266 if (!Adopts) 5267 return false; 5268 } 5269 return true; 5270 } 5271 5272 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for 5273 /// the given object type. 5274 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const { 5275 llvm::FoldingSetNodeID ID; 5276 ObjCObjectPointerType::Profile(ID, ObjectT); 5277 5278 void *InsertPos = nullptr; 5279 if (ObjCObjectPointerType *QT = 5280 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 5281 return QualType(QT, 0); 5282 5283 // Find the canonical object type. 5284 QualType Canonical; 5285 if (!ObjectT.isCanonical()) { 5286 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT)); 5287 5288 // Regenerate InsertPos. 5289 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 5290 } 5291 5292 // No match. 5293 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment); 5294 auto *QType = 5295 new (Mem) ObjCObjectPointerType(Canonical, ObjectT); 5296 5297 Types.push_back(QType); 5298 ObjCObjectPointerTypes.InsertNode(QType, InsertPos); 5299 return QualType(QType, 0); 5300 } 5301 5302 /// getObjCInterfaceType - Return the unique reference to the type for the 5303 /// specified ObjC interface decl. The list of protocols is optional. 5304 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl, 5305 ObjCInterfaceDecl *PrevDecl) const { 5306 if (Decl->TypeForDecl) 5307 return QualType(Decl->TypeForDecl, 0); 5308 5309 if (PrevDecl) { 5310 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl"); 5311 Decl->TypeForDecl = PrevDecl->TypeForDecl; 5312 return QualType(PrevDecl->TypeForDecl, 0); 5313 } 5314 5315 // Prefer the definition, if there is one. 5316 if (const ObjCInterfaceDecl *Def = Decl->getDefinition()) 5317 Decl = Def; 5318 5319 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment); 5320 auto *T = new (Mem) ObjCInterfaceType(Decl); 5321 Decl->TypeForDecl = T; 5322 Types.push_back(T); 5323 return QualType(T, 0); 5324 } 5325 5326 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique 5327 /// TypeOfExprType AST's (since expression's are never shared). For example, 5328 /// multiple declarations that refer to "typeof(x)" all contain different 5329 /// DeclRefExpr's. This doesn't effect the type checker, since it operates 5330 /// on canonical type's (which are always unique). 5331 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const { 5332 TypeOfExprType *toe; 5333 if (tofExpr->isTypeDependent()) { 5334 llvm::FoldingSetNodeID ID; 5335 DependentTypeOfExprType::Profile(ID, *this, tofExpr); 5336 5337 void *InsertPos = nullptr; 5338 DependentTypeOfExprType *Canon 5339 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos); 5340 if (Canon) { 5341 // We already have a "canonical" version of an identical, dependent 5342 // typeof(expr) type. Use that as our canonical type. 5343 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, 5344 QualType((TypeOfExprType*)Canon, 0)); 5345 } else { 5346 // Build a new, canonical typeof(expr) type. 5347 Canon 5348 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr); 5349 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos); 5350 toe = Canon; 5351 } 5352 } else { 5353 QualType Canonical = getCanonicalType(tofExpr->getType()); 5354 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical); 5355 } 5356 Types.push_back(toe); 5357 return QualType(toe, 0); 5358 } 5359 5360 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique 5361 /// TypeOfType nodes. The only motivation to unique these nodes would be 5362 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be 5363 /// an issue. This doesn't affect the type checker, since it operates 5364 /// on canonical types (which are always unique). 5365 QualType ASTContext::getTypeOfType(QualType tofType) const { 5366 QualType Canonical = getCanonicalType(tofType); 5367 auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical); 5368 Types.push_back(tot); 5369 return QualType(tot, 0); 5370 } 5371 5372 /// Unlike many "get<Type>" functions, we don't unique DecltypeType 5373 /// nodes. This would never be helpful, since each such type has its own 5374 /// expression, and would not give a significant memory saving, since there 5375 /// is an Expr tree under each such type. 5376 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const { 5377 DecltypeType *dt; 5378 5379 // C++11 [temp.type]p2: 5380 // If an expression e involves a template parameter, decltype(e) denotes a 5381 // unique dependent type. Two such decltype-specifiers refer to the same 5382 // type only if their expressions are equivalent (14.5.6.1). 5383 if (e->isInstantiationDependent()) { 5384 llvm::FoldingSetNodeID ID; 5385 DependentDecltypeType::Profile(ID, *this, e); 5386 5387 void *InsertPos = nullptr; 5388 DependentDecltypeType *Canon 5389 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos); 5390 if (!Canon) { 5391 // Build a new, canonical decltype(expr) type. 5392 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e); 5393 DependentDecltypeTypes.InsertNode(Canon, InsertPos); 5394 } 5395 dt = new (*this, TypeAlignment) 5396 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0)); 5397 } else { 5398 dt = new (*this, TypeAlignment) 5399 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType)); 5400 } 5401 Types.push_back(dt); 5402 return QualType(dt, 0); 5403 } 5404 5405 /// getUnaryTransformationType - We don't unique these, since the memory 5406 /// savings are minimal and these are rare. 5407 QualType ASTContext::getUnaryTransformType(QualType BaseType, 5408 QualType UnderlyingType, 5409 UnaryTransformType::UTTKind Kind) 5410 const { 5411 UnaryTransformType *ut = nullptr; 5412 5413 if (BaseType->isDependentType()) { 5414 // Look in the folding set for an existing type. 5415 llvm::FoldingSetNodeID ID; 5416 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind); 5417 5418 void *InsertPos = nullptr; 5419 DependentUnaryTransformType *Canon 5420 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos); 5421 5422 if (!Canon) { 5423 // Build a new, canonical __underlying_type(type) type. 5424 Canon = new (*this, TypeAlignment) 5425 DependentUnaryTransformType(*this, getCanonicalType(BaseType), 5426 Kind); 5427 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos); 5428 } 5429 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType, 5430 QualType(), Kind, 5431 QualType(Canon, 0)); 5432 } else { 5433 QualType CanonType = getCanonicalType(UnderlyingType); 5434 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType, 5435 UnderlyingType, Kind, 5436 CanonType); 5437 } 5438 Types.push_back(ut); 5439 return QualType(ut, 0); 5440 } 5441 5442 /// getAutoType - Return the uniqued reference to the 'auto' type which has been 5443 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the 5444 /// canonical deduced-but-dependent 'auto' type. 5445 QualType 5446 ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, 5447 bool IsDependent, bool IsPack, 5448 ConceptDecl *TypeConstraintConcept, 5449 ArrayRef<TemplateArgument> TypeConstraintArgs) const { 5450 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack"); 5451 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && 5452 !TypeConstraintConcept && !IsDependent) 5453 return getAutoDeductType(); 5454 5455 // Look in the folding set for an existing type. 5456 void *InsertPos = nullptr; 5457 llvm::FoldingSetNodeID ID; 5458 AutoType::Profile(ID, *this, DeducedType, Keyword, IsDependent, 5459 TypeConstraintConcept, TypeConstraintArgs); 5460 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos)) 5461 return QualType(AT, 0); 5462 5463 void *Mem = Allocate(sizeof(AutoType) + 5464 sizeof(TemplateArgument) * TypeConstraintArgs.size(), 5465 TypeAlignment); 5466 auto *AT = new (Mem) AutoType( 5467 DeducedType, Keyword, 5468 (IsDependent ? TypeDependence::DependentInstantiation 5469 : TypeDependence::None) | 5470 (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None), 5471 TypeConstraintConcept, TypeConstraintArgs); 5472 Types.push_back(AT); 5473 if (InsertPos) 5474 AutoTypes.InsertNode(AT, InsertPos); 5475 return QualType(AT, 0); 5476 } 5477 5478 /// Return the uniqued reference to the deduced template specialization type 5479 /// which has been deduced to the given type, or to the canonical undeduced 5480 /// such type, or the canonical deduced-but-dependent such type. 5481 QualType ASTContext::getDeducedTemplateSpecializationType( 5482 TemplateName Template, QualType DeducedType, bool IsDependent) const { 5483 // Look in the folding set for an existing type. 5484 void *InsertPos = nullptr; 5485 llvm::FoldingSetNodeID ID; 5486 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType, 5487 IsDependent); 5488 if (DeducedTemplateSpecializationType *DTST = 5489 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos)) 5490 return QualType(DTST, 0); 5491 5492 auto *DTST = new (*this, TypeAlignment) 5493 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent); 5494 Types.push_back(DTST); 5495 if (InsertPos) 5496 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos); 5497 return QualType(DTST, 0); 5498 } 5499 5500 /// getAtomicType - Return the uniqued reference to the atomic type for 5501 /// the given value type. 5502 QualType ASTContext::getAtomicType(QualType T) const { 5503 // Unique pointers, to guarantee there is only one pointer of a particular 5504 // structure. 5505 llvm::FoldingSetNodeID ID; 5506 AtomicType::Profile(ID, T); 5507 5508 void *InsertPos = nullptr; 5509 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos)) 5510 return QualType(AT, 0); 5511 5512 // If the atomic value type isn't canonical, this won't be a canonical type 5513 // either, so fill in the canonical type field. 5514 QualType Canonical; 5515 if (!T.isCanonical()) { 5516 Canonical = getAtomicType(getCanonicalType(T)); 5517 5518 // Get the new insert position for the node we care about. 5519 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos); 5520 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 5521 } 5522 auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical); 5523 Types.push_back(New); 5524 AtomicTypes.InsertNode(New, InsertPos); 5525 return QualType(New, 0); 5526 } 5527 5528 /// getAutoDeductType - Get type pattern for deducing against 'auto'. 5529 QualType ASTContext::getAutoDeductType() const { 5530 if (AutoDeductTy.isNull()) 5531 AutoDeductTy = QualType(new (*this, TypeAlignment) 5532 AutoType(QualType(), AutoTypeKeyword::Auto, 5533 TypeDependence::None, 5534 /*concept*/ nullptr, /*args*/ {}), 5535 0); 5536 return AutoDeductTy; 5537 } 5538 5539 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'. 5540 QualType ASTContext::getAutoRRefDeductType() const { 5541 if (AutoRRefDeductTy.isNull()) 5542 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType()); 5543 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern"); 5544 return AutoRRefDeductTy; 5545 } 5546 5547 /// getTagDeclType - Return the unique reference to the type for the 5548 /// specified TagDecl (struct/union/class/enum) decl. 5549 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const { 5550 assert(Decl); 5551 // FIXME: What is the design on getTagDeclType when it requires casting 5552 // away const? mutable? 5553 return getTypeDeclType(const_cast<TagDecl*>(Decl)); 5554 } 5555 5556 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result 5557 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and 5558 /// needs to agree with the definition in <stddef.h>. 5559 CanQualType ASTContext::getSizeType() const { 5560 return getFromTargetType(Target->getSizeType()); 5561 } 5562 5563 /// Return the unique signed counterpart of the integer type 5564 /// corresponding to size_t. 5565 CanQualType ASTContext::getSignedSizeType() const { 5566 return getFromTargetType(Target->getSignedSizeType()); 5567 } 5568 5569 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5). 5570 CanQualType ASTContext::getIntMaxType() const { 5571 return getFromTargetType(Target->getIntMaxType()); 5572 } 5573 5574 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5). 5575 CanQualType ASTContext::getUIntMaxType() const { 5576 return getFromTargetType(Target->getUIntMaxType()); 5577 } 5578 5579 /// getSignedWCharType - Return the type of "signed wchar_t". 5580 /// Used when in C++, as a GCC extension. 5581 QualType ASTContext::getSignedWCharType() const { 5582 // FIXME: derive from "Target" ? 5583 return WCharTy; 5584 } 5585 5586 /// getUnsignedWCharType - Return the type of "unsigned wchar_t". 5587 /// Used when in C++, as a GCC extension. 5588 QualType ASTContext::getUnsignedWCharType() const { 5589 // FIXME: derive from "Target" ? 5590 return UnsignedIntTy; 5591 } 5592 5593 QualType ASTContext::getIntPtrType() const { 5594 return getFromTargetType(Target->getIntPtrType()); 5595 } 5596 5597 QualType ASTContext::getUIntPtrType() const { 5598 return getCorrespondingUnsignedType(getIntPtrType()); 5599 } 5600 5601 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17) 5602 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9). 5603 QualType ASTContext::getPointerDiffType() const { 5604 return getFromTargetType(Target->getPtrDiffType(0)); 5605 } 5606 5607 /// Return the unique unsigned counterpart of "ptrdiff_t" 5608 /// integer type. The standard (C11 7.21.6.1p7) refers to this type 5609 /// in the definition of %tu format specifier. 5610 QualType ASTContext::getUnsignedPointerDiffType() const { 5611 return getFromTargetType(Target->getUnsignedPtrDiffType(0)); 5612 } 5613 5614 /// Return the unique type for "pid_t" defined in 5615 /// <sys/types.h>. We need this to compute the correct type for vfork(). 5616 QualType ASTContext::getProcessIDType() const { 5617 return getFromTargetType(Target->getProcessIDType()); 5618 } 5619 5620 //===----------------------------------------------------------------------===// 5621 // Type Operators 5622 //===----------------------------------------------------------------------===// 5623 5624 CanQualType ASTContext::getCanonicalParamType(QualType T) const { 5625 // Push qualifiers into arrays, and then discard any remaining 5626 // qualifiers. 5627 T = getCanonicalType(T); 5628 T = getVariableArrayDecayedType(T); 5629 const Type *Ty = T.getTypePtr(); 5630 QualType Result; 5631 if (isa<ArrayType>(Ty)) { 5632 Result = getArrayDecayedType(QualType(Ty,0)); 5633 } else if (isa<FunctionType>(Ty)) { 5634 Result = getPointerType(QualType(Ty, 0)); 5635 } else { 5636 Result = QualType(Ty, 0); 5637 } 5638 5639 return CanQualType::CreateUnsafe(Result); 5640 } 5641 5642 QualType ASTContext::getUnqualifiedArrayType(QualType type, 5643 Qualifiers &quals) { 5644 SplitQualType splitType = type.getSplitUnqualifiedType(); 5645 5646 // FIXME: getSplitUnqualifiedType() actually walks all the way to 5647 // the unqualified desugared type and then drops it on the floor. 5648 // We then have to strip that sugar back off with 5649 // getUnqualifiedDesugaredType(), which is silly. 5650 const auto *AT = 5651 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType()); 5652 5653 // If we don't have an array, just use the results in splitType. 5654 if (!AT) { 5655 quals = splitType.Quals; 5656 return QualType(splitType.Ty, 0); 5657 } 5658 5659 // Otherwise, recurse on the array's element type. 5660 QualType elementType = AT->getElementType(); 5661 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals); 5662 5663 // If that didn't change the element type, AT has no qualifiers, so we 5664 // can just use the results in splitType. 5665 if (elementType == unqualElementType) { 5666 assert(quals.empty()); // from the recursive call 5667 quals = splitType.Quals; 5668 return QualType(splitType.Ty, 0); 5669 } 5670 5671 // Otherwise, add in the qualifiers from the outermost type, then 5672 // build the type back up. 5673 quals.addConsistentQualifiers(splitType.Quals); 5674 5675 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 5676 return getConstantArrayType(unqualElementType, CAT->getSize(), 5677 CAT->getSizeExpr(), CAT->getSizeModifier(), 0); 5678 } 5679 5680 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) { 5681 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0); 5682 } 5683 5684 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) { 5685 return getVariableArrayType(unqualElementType, 5686 VAT->getSizeExpr(), 5687 VAT->getSizeModifier(), 5688 VAT->getIndexTypeCVRQualifiers(), 5689 VAT->getBracketsRange()); 5690 } 5691 5692 const auto *DSAT = cast<DependentSizedArrayType>(AT); 5693 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(), 5694 DSAT->getSizeModifier(), 0, 5695 SourceRange()); 5696 } 5697 5698 /// Attempt to unwrap two types that may both be array types with the same bound 5699 /// (or both be array types of unknown bound) for the purpose of comparing the 5700 /// cv-decomposition of two types per C++ [conv.qual]. 5701 bool ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2) { 5702 bool UnwrappedAny = false; 5703 while (true) { 5704 auto *AT1 = getAsArrayType(T1); 5705 if (!AT1) return UnwrappedAny; 5706 5707 auto *AT2 = getAsArrayType(T2); 5708 if (!AT2) return UnwrappedAny; 5709 5710 // If we don't have two array types with the same constant bound nor two 5711 // incomplete array types, we've unwrapped everything we can. 5712 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) { 5713 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2); 5714 if (!CAT2 || CAT1->getSize() != CAT2->getSize()) 5715 return UnwrappedAny; 5716 } else if (!isa<IncompleteArrayType>(AT1) || 5717 !isa<IncompleteArrayType>(AT2)) { 5718 return UnwrappedAny; 5719 } 5720 5721 T1 = AT1->getElementType(); 5722 T2 = AT2->getElementType(); 5723 UnwrappedAny = true; 5724 } 5725 } 5726 5727 /// Attempt to unwrap two types that may be similar (C++ [conv.qual]). 5728 /// 5729 /// If T1 and T2 are both pointer types of the same kind, or both array types 5730 /// with the same bound, unwraps layers from T1 and T2 until a pointer type is 5731 /// unwrapped. Top-level qualifiers on T1 and T2 are ignored. 5732 /// 5733 /// This function will typically be called in a loop that successively 5734 /// "unwraps" pointer and pointer-to-member types to compare them at each 5735 /// level. 5736 /// 5737 /// \return \c true if a pointer type was unwrapped, \c false if we reached a 5738 /// pair of types that can't be unwrapped further. 5739 bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) { 5740 UnwrapSimilarArrayTypes(T1, T2); 5741 5742 const auto *T1PtrType = T1->getAs<PointerType>(); 5743 const auto *T2PtrType = T2->getAs<PointerType>(); 5744 if (T1PtrType && T2PtrType) { 5745 T1 = T1PtrType->getPointeeType(); 5746 T2 = T2PtrType->getPointeeType(); 5747 return true; 5748 } 5749 5750 const auto *T1MPType = T1->getAs<MemberPointerType>(); 5751 const auto *T2MPType = T2->getAs<MemberPointerType>(); 5752 if (T1MPType && T2MPType && 5753 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0), 5754 QualType(T2MPType->getClass(), 0))) { 5755 T1 = T1MPType->getPointeeType(); 5756 T2 = T2MPType->getPointeeType(); 5757 return true; 5758 } 5759 5760 if (getLangOpts().ObjC) { 5761 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>(); 5762 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>(); 5763 if (T1OPType && T2OPType) { 5764 T1 = T1OPType->getPointeeType(); 5765 T2 = T2OPType->getPointeeType(); 5766 return true; 5767 } 5768 } 5769 5770 // FIXME: Block pointers, too? 5771 5772 return false; 5773 } 5774 5775 bool ASTContext::hasSimilarType(QualType T1, QualType T2) { 5776 while (true) { 5777 Qualifiers Quals; 5778 T1 = getUnqualifiedArrayType(T1, Quals); 5779 T2 = getUnqualifiedArrayType(T2, Quals); 5780 if (hasSameType(T1, T2)) 5781 return true; 5782 if (!UnwrapSimilarTypes(T1, T2)) 5783 return false; 5784 } 5785 } 5786 5787 bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) { 5788 while (true) { 5789 Qualifiers Quals1, Quals2; 5790 T1 = getUnqualifiedArrayType(T1, Quals1); 5791 T2 = getUnqualifiedArrayType(T2, Quals2); 5792 5793 Quals1.removeCVRQualifiers(); 5794 Quals2.removeCVRQualifiers(); 5795 if (Quals1 != Quals2) 5796 return false; 5797 5798 if (hasSameType(T1, T2)) 5799 return true; 5800 5801 if (!UnwrapSimilarTypes(T1, T2)) 5802 return false; 5803 } 5804 } 5805 5806 DeclarationNameInfo 5807 ASTContext::getNameForTemplate(TemplateName Name, 5808 SourceLocation NameLoc) const { 5809 switch (Name.getKind()) { 5810 case TemplateName::QualifiedTemplate: 5811 case TemplateName::Template: 5812 // DNInfo work in progress: CHECKME: what about DNLoc? 5813 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(), 5814 NameLoc); 5815 5816 case TemplateName::OverloadedTemplate: { 5817 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate(); 5818 // DNInfo work in progress: CHECKME: what about DNLoc? 5819 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc); 5820 } 5821 5822 case TemplateName::AssumedTemplate: { 5823 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName(); 5824 return DeclarationNameInfo(Storage->getDeclName(), NameLoc); 5825 } 5826 5827 case TemplateName::DependentTemplate: { 5828 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 5829 DeclarationName DName; 5830 if (DTN->isIdentifier()) { 5831 DName = DeclarationNames.getIdentifier(DTN->getIdentifier()); 5832 return DeclarationNameInfo(DName, NameLoc); 5833 } else { 5834 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator()); 5835 // DNInfo work in progress: FIXME: source locations? 5836 DeclarationNameLoc DNLoc; 5837 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding(); 5838 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding(); 5839 return DeclarationNameInfo(DName, NameLoc, DNLoc); 5840 } 5841 } 5842 5843 case TemplateName::SubstTemplateTemplateParm: { 5844 SubstTemplateTemplateParmStorage *subst 5845 = Name.getAsSubstTemplateTemplateParm(); 5846 return DeclarationNameInfo(subst->getParameter()->getDeclName(), 5847 NameLoc); 5848 } 5849 5850 case TemplateName::SubstTemplateTemplateParmPack: { 5851 SubstTemplateTemplateParmPackStorage *subst 5852 = Name.getAsSubstTemplateTemplateParmPack(); 5853 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(), 5854 NameLoc); 5855 } 5856 } 5857 5858 llvm_unreachable("bad template name kind!"); 5859 } 5860 5861 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const { 5862 switch (Name.getKind()) { 5863 case TemplateName::QualifiedTemplate: 5864 case TemplateName::Template: { 5865 TemplateDecl *Template = Name.getAsTemplateDecl(); 5866 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template)) 5867 Template = getCanonicalTemplateTemplateParmDecl(TTP); 5868 5869 // The canonical template name is the canonical template declaration. 5870 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl())); 5871 } 5872 5873 case TemplateName::OverloadedTemplate: 5874 case TemplateName::AssumedTemplate: 5875 llvm_unreachable("cannot canonicalize unresolved template"); 5876 5877 case TemplateName::DependentTemplate: { 5878 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 5879 assert(DTN && "Non-dependent template names must refer to template decls."); 5880 return DTN->CanonicalTemplateName; 5881 } 5882 5883 case TemplateName::SubstTemplateTemplateParm: { 5884 SubstTemplateTemplateParmStorage *subst 5885 = Name.getAsSubstTemplateTemplateParm(); 5886 return getCanonicalTemplateName(subst->getReplacement()); 5887 } 5888 5889 case TemplateName::SubstTemplateTemplateParmPack: { 5890 SubstTemplateTemplateParmPackStorage *subst 5891 = Name.getAsSubstTemplateTemplateParmPack(); 5892 TemplateTemplateParmDecl *canonParameter 5893 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack()); 5894 TemplateArgument canonArgPack 5895 = getCanonicalTemplateArgument(subst->getArgumentPack()); 5896 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack); 5897 } 5898 } 5899 5900 llvm_unreachable("bad template name!"); 5901 } 5902 5903 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) { 5904 X = getCanonicalTemplateName(X); 5905 Y = getCanonicalTemplateName(Y); 5906 return X.getAsVoidPointer() == Y.getAsVoidPointer(); 5907 } 5908 5909 TemplateArgument 5910 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const { 5911 switch (Arg.getKind()) { 5912 case TemplateArgument::Null: 5913 return Arg; 5914 5915 case TemplateArgument::Expression: 5916 return Arg; 5917 5918 case TemplateArgument::Declaration: { 5919 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl()); 5920 return TemplateArgument(D, Arg.getParamTypeForDecl()); 5921 } 5922 5923 case TemplateArgument::NullPtr: 5924 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()), 5925 /*isNullPtr*/true); 5926 5927 case TemplateArgument::Template: 5928 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate())); 5929 5930 case TemplateArgument::TemplateExpansion: 5931 return TemplateArgument(getCanonicalTemplateName( 5932 Arg.getAsTemplateOrTemplatePattern()), 5933 Arg.getNumTemplateExpansions()); 5934 5935 case TemplateArgument::Integral: 5936 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType())); 5937 5938 case TemplateArgument::Type: 5939 return TemplateArgument(getCanonicalType(Arg.getAsType())); 5940 5941 case TemplateArgument::Pack: { 5942 if (Arg.pack_size() == 0) 5943 return Arg; 5944 5945 auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()]; 5946 unsigned Idx = 0; 5947 for (TemplateArgument::pack_iterator A = Arg.pack_begin(), 5948 AEnd = Arg.pack_end(); 5949 A != AEnd; (void)++A, ++Idx) 5950 CanonArgs[Idx] = getCanonicalTemplateArgument(*A); 5951 5952 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size())); 5953 } 5954 } 5955 5956 // Silence GCC warning 5957 llvm_unreachable("Unhandled template argument kind"); 5958 } 5959 5960 NestedNameSpecifier * 5961 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const { 5962 if (!NNS) 5963 return nullptr; 5964 5965 switch (NNS->getKind()) { 5966 case NestedNameSpecifier::Identifier: 5967 // Canonicalize the prefix but keep the identifier the same. 5968 return NestedNameSpecifier::Create(*this, 5969 getCanonicalNestedNameSpecifier(NNS->getPrefix()), 5970 NNS->getAsIdentifier()); 5971 5972 case NestedNameSpecifier::Namespace: 5973 // A namespace is canonical; build a nested-name-specifier with 5974 // this namespace and no prefix. 5975 return NestedNameSpecifier::Create(*this, nullptr, 5976 NNS->getAsNamespace()->getOriginalNamespace()); 5977 5978 case NestedNameSpecifier::NamespaceAlias: 5979 // A namespace is canonical; build a nested-name-specifier with 5980 // this namespace and no prefix. 5981 return NestedNameSpecifier::Create(*this, nullptr, 5982 NNS->getAsNamespaceAlias()->getNamespace() 5983 ->getOriginalNamespace()); 5984 5985 case NestedNameSpecifier::TypeSpec: 5986 case NestedNameSpecifier::TypeSpecWithTemplate: { 5987 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0)); 5988 5989 // If we have some kind of dependent-named type (e.g., "typename T::type"), 5990 // break it apart into its prefix and identifier, then reconsititute those 5991 // as the canonical nested-name-specifier. This is required to canonicalize 5992 // a dependent nested-name-specifier involving typedefs of dependent-name 5993 // types, e.g., 5994 // typedef typename T::type T1; 5995 // typedef typename T1::type T2; 5996 if (const auto *DNT = T->getAs<DependentNameType>()) 5997 return NestedNameSpecifier::Create(*this, DNT->getQualifier(), 5998 const_cast<IdentifierInfo *>(DNT->getIdentifier())); 5999 6000 // Otherwise, just canonicalize the type, and force it to be a TypeSpec. 6001 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the 6002 // first place? 6003 return NestedNameSpecifier::Create(*this, nullptr, false, 6004 const_cast<Type *>(T.getTypePtr())); 6005 } 6006 6007 case NestedNameSpecifier::Global: 6008 case NestedNameSpecifier::Super: 6009 // The global specifier and __super specifer are canonical and unique. 6010 return NNS; 6011 } 6012 6013 llvm_unreachable("Invalid NestedNameSpecifier::Kind!"); 6014 } 6015 6016 const ArrayType *ASTContext::getAsArrayType(QualType T) const { 6017 // Handle the non-qualified case efficiently. 6018 if (!T.hasLocalQualifiers()) { 6019 // Handle the common positive case fast. 6020 if (const auto *AT = dyn_cast<ArrayType>(T)) 6021 return AT; 6022 } 6023 6024 // Handle the common negative case fast. 6025 if (!isa<ArrayType>(T.getCanonicalType())) 6026 return nullptr; 6027 6028 // Apply any qualifiers from the array type to the element type. This 6029 // implements C99 6.7.3p8: "If the specification of an array type includes 6030 // any type qualifiers, the element type is so qualified, not the array type." 6031 6032 // If we get here, we either have type qualifiers on the type, or we have 6033 // sugar such as a typedef in the way. If we have type qualifiers on the type 6034 // we must propagate them down into the element type. 6035 6036 SplitQualType split = T.getSplitDesugaredType(); 6037 Qualifiers qs = split.Quals; 6038 6039 // If we have a simple case, just return now. 6040 const auto *ATy = dyn_cast<ArrayType>(split.Ty); 6041 if (!ATy || qs.empty()) 6042 return ATy; 6043 6044 // Otherwise, we have an array and we have qualifiers on it. Push the 6045 // qualifiers into the array element type and return a new array type. 6046 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs); 6047 6048 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy)) 6049 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(), 6050 CAT->getSizeExpr(), 6051 CAT->getSizeModifier(), 6052 CAT->getIndexTypeCVRQualifiers())); 6053 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy)) 6054 return cast<ArrayType>(getIncompleteArrayType(NewEltTy, 6055 IAT->getSizeModifier(), 6056 IAT->getIndexTypeCVRQualifiers())); 6057 6058 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy)) 6059 return cast<ArrayType>( 6060 getDependentSizedArrayType(NewEltTy, 6061 DSAT->getSizeExpr(), 6062 DSAT->getSizeModifier(), 6063 DSAT->getIndexTypeCVRQualifiers(), 6064 DSAT->getBracketsRange())); 6065 6066 const auto *VAT = cast<VariableArrayType>(ATy); 6067 return cast<ArrayType>(getVariableArrayType(NewEltTy, 6068 VAT->getSizeExpr(), 6069 VAT->getSizeModifier(), 6070 VAT->getIndexTypeCVRQualifiers(), 6071 VAT->getBracketsRange())); 6072 } 6073 6074 QualType ASTContext::getAdjustedParameterType(QualType T) const { 6075 if (T->isArrayType() || T->isFunctionType()) 6076 return getDecayedType(T); 6077 return T; 6078 } 6079 6080 QualType ASTContext::getSignatureParameterType(QualType T) const { 6081 T = getVariableArrayDecayedType(T); 6082 T = getAdjustedParameterType(T); 6083 return T.getUnqualifiedType(); 6084 } 6085 6086 QualType ASTContext::getExceptionObjectType(QualType T) const { 6087 // C++ [except.throw]p3: 6088 // A throw-expression initializes a temporary object, called the exception 6089 // object, the type of which is determined by removing any top-level 6090 // cv-qualifiers from the static type of the operand of throw and adjusting 6091 // the type from "array of T" or "function returning T" to "pointer to T" 6092 // or "pointer to function returning T", [...] 6093 T = getVariableArrayDecayedType(T); 6094 if (T->isArrayType() || T->isFunctionType()) 6095 T = getDecayedType(T); 6096 return T.getUnqualifiedType(); 6097 } 6098 6099 /// getArrayDecayedType - Return the properly qualified result of decaying the 6100 /// specified array type to a pointer. This operation is non-trivial when 6101 /// handling typedefs etc. The canonical type of "T" must be an array type, 6102 /// this returns a pointer to a properly qualified element of the array. 6103 /// 6104 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3. 6105 QualType ASTContext::getArrayDecayedType(QualType Ty) const { 6106 // Get the element type with 'getAsArrayType' so that we don't lose any 6107 // typedefs in the element type of the array. This also handles propagation 6108 // of type qualifiers from the array type into the element type if present 6109 // (C99 6.7.3p8). 6110 const ArrayType *PrettyArrayType = getAsArrayType(Ty); 6111 assert(PrettyArrayType && "Not an array type!"); 6112 6113 QualType PtrTy = getPointerType(PrettyArrayType->getElementType()); 6114 6115 // int x[restrict 4] -> int *restrict 6116 QualType Result = getQualifiedType(PtrTy, 6117 PrettyArrayType->getIndexTypeQualifiers()); 6118 6119 // int x[_Nullable] -> int * _Nullable 6120 if (auto Nullability = Ty->getNullability(*this)) { 6121 Result = const_cast<ASTContext *>(this)->getAttributedType( 6122 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result); 6123 } 6124 return Result; 6125 } 6126 6127 QualType ASTContext::getBaseElementType(const ArrayType *array) const { 6128 return getBaseElementType(array->getElementType()); 6129 } 6130 6131 QualType ASTContext::getBaseElementType(QualType type) const { 6132 Qualifiers qs; 6133 while (true) { 6134 SplitQualType split = type.getSplitDesugaredType(); 6135 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe(); 6136 if (!array) break; 6137 6138 type = array->getElementType(); 6139 qs.addConsistentQualifiers(split.Quals); 6140 } 6141 6142 return getQualifiedType(type, qs); 6143 } 6144 6145 /// getConstantArrayElementCount - Returns number of constant array elements. 6146 uint64_t 6147 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const { 6148 uint64_t ElementCount = 1; 6149 do { 6150 ElementCount *= CA->getSize().getZExtValue(); 6151 CA = dyn_cast_or_null<ConstantArrayType>( 6152 CA->getElementType()->getAsArrayTypeUnsafe()); 6153 } while (CA); 6154 return ElementCount; 6155 } 6156 6157 /// getFloatingRank - Return a relative rank for floating point types. 6158 /// This routine will assert if passed a built-in type that isn't a float. 6159 static FloatingRank getFloatingRank(QualType T) { 6160 if (const auto *CT = T->getAs<ComplexType>()) 6161 return getFloatingRank(CT->getElementType()); 6162 6163 switch (T->castAs<BuiltinType>()->getKind()) { 6164 default: llvm_unreachable("getFloatingRank(): not a floating type"); 6165 case BuiltinType::Float16: return Float16Rank; 6166 case BuiltinType::Half: return HalfRank; 6167 case BuiltinType::Float: return FloatRank; 6168 case BuiltinType::Double: return DoubleRank; 6169 case BuiltinType::LongDouble: return LongDoubleRank; 6170 case BuiltinType::Float128: return Float128Rank; 6171 case BuiltinType::BFloat16: return BFloat16Rank; 6172 } 6173 } 6174 6175 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating 6176 /// point or a complex type (based on typeDomain/typeSize). 6177 /// 'typeDomain' is a real floating point or complex type. 6178 /// 'typeSize' is a real floating point or complex type. 6179 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size, 6180 QualType Domain) const { 6181 FloatingRank EltRank = getFloatingRank(Size); 6182 if (Domain->isComplexType()) { 6183 switch (EltRank) { 6184 case BFloat16Rank: llvm_unreachable("Complex bfloat16 is not supported"); 6185 case Float16Rank: 6186 case HalfRank: llvm_unreachable("Complex half is not supported"); 6187 case FloatRank: return FloatComplexTy; 6188 case DoubleRank: return DoubleComplexTy; 6189 case LongDoubleRank: return LongDoubleComplexTy; 6190 case Float128Rank: return Float128ComplexTy; 6191 } 6192 } 6193 6194 assert(Domain->isRealFloatingType() && "Unknown domain!"); 6195 switch (EltRank) { 6196 case Float16Rank: return HalfTy; 6197 case BFloat16Rank: return BFloat16Ty; 6198 case HalfRank: return HalfTy; 6199 case FloatRank: return FloatTy; 6200 case DoubleRank: return DoubleTy; 6201 case LongDoubleRank: return LongDoubleTy; 6202 case Float128Rank: return Float128Ty; 6203 } 6204 llvm_unreachable("getFloatingRank(): illegal value for rank"); 6205 } 6206 6207 /// getFloatingTypeOrder - Compare the rank of the two specified floating 6208 /// point types, ignoring the domain of the type (i.e. 'double' == 6209 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If 6210 /// LHS < RHS, return -1. 6211 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const { 6212 FloatingRank LHSR = getFloatingRank(LHS); 6213 FloatingRank RHSR = getFloatingRank(RHS); 6214 6215 if (LHSR == RHSR) 6216 return 0; 6217 if (LHSR > RHSR) 6218 return 1; 6219 return -1; 6220 } 6221 6222 int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const { 6223 if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS)) 6224 return 0; 6225 return getFloatingTypeOrder(LHS, RHS); 6226 } 6227 6228 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This 6229 /// routine will assert if passed a built-in type that isn't an integer or enum, 6230 /// or if it is not canonicalized. 6231 unsigned ASTContext::getIntegerRank(const Type *T) const { 6232 assert(T->isCanonicalUnqualified() && "T should be canonicalized"); 6233 6234 // Results in this 'losing' to any type of the same size, but winning if 6235 // larger. 6236 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 6237 return 0 + (EIT->getNumBits() << 3); 6238 6239 switch (cast<BuiltinType>(T)->getKind()) { 6240 default: llvm_unreachable("getIntegerRank(): not a built-in integer"); 6241 case BuiltinType::Bool: 6242 return 1 + (getIntWidth(BoolTy) << 3); 6243 case BuiltinType::Char_S: 6244 case BuiltinType::Char_U: 6245 case BuiltinType::SChar: 6246 case BuiltinType::UChar: 6247 return 2 + (getIntWidth(CharTy) << 3); 6248 case BuiltinType::Short: 6249 case BuiltinType::UShort: 6250 return 3 + (getIntWidth(ShortTy) << 3); 6251 case BuiltinType::Int: 6252 case BuiltinType::UInt: 6253 return 4 + (getIntWidth(IntTy) << 3); 6254 case BuiltinType::Long: 6255 case BuiltinType::ULong: 6256 return 5 + (getIntWidth(LongTy) << 3); 6257 case BuiltinType::LongLong: 6258 case BuiltinType::ULongLong: 6259 return 6 + (getIntWidth(LongLongTy) << 3); 6260 case BuiltinType::Int128: 6261 case BuiltinType::UInt128: 6262 return 7 + (getIntWidth(Int128Ty) << 3); 6263 } 6264 } 6265 6266 /// Whether this is a promotable bitfield reference according 6267 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions). 6268 /// 6269 /// \returns the type this bit-field will promote to, or NULL if no 6270 /// promotion occurs. 6271 QualType ASTContext::isPromotableBitField(Expr *E) const { 6272 if (E->isTypeDependent() || E->isValueDependent()) 6273 return {}; 6274 6275 // C++ [conv.prom]p5: 6276 // If the bit-field has an enumerated type, it is treated as any other 6277 // value of that type for promotion purposes. 6278 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType()) 6279 return {}; 6280 6281 // FIXME: We should not do this unless E->refersToBitField() is true. This 6282 // matters in C where getSourceBitField() will find bit-fields for various 6283 // cases where the source expression is not a bit-field designator. 6284 6285 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields? 6286 if (!Field) 6287 return {}; 6288 6289 QualType FT = Field->getType(); 6290 6291 uint64_t BitWidth = Field->getBitWidthValue(*this); 6292 uint64_t IntSize = getTypeSize(IntTy); 6293 // C++ [conv.prom]p5: 6294 // A prvalue for an integral bit-field can be converted to a prvalue of type 6295 // int if int can represent all the values of the bit-field; otherwise, it 6296 // can be converted to unsigned int if unsigned int can represent all the 6297 // values of the bit-field. If the bit-field is larger yet, no integral 6298 // promotion applies to it. 6299 // C11 6.3.1.1/2: 6300 // [For a bit-field of type _Bool, int, signed int, or unsigned int:] 6301 // If an int can represent all values of the original type (as restricted by 6302 // the width, for a bit-field), the value is converted to an int; otherwise, 6303 // it is converted to an unsigned int. 6304 // 6305 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int. 6306 // We perform that promotion here to match GCC and C++. 6307 // FIXME: C does not permit promotion of an enum bit-field whose rank is 6308 // greater than that of 'int'. We perform that promotion to match GCC. 6309 if (BitWidth < IntSize) 6310 return IntTy; 6311 6312 if (BitWidth == IntSize) 6313 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy; 6314 6315 // Bit-fields wider than int are not subject to promotions, and therefore act 6316 // like the base type. GCC has some weird bugs in this area that we 6317 // deliberately do not follow (GCC follows a pre-standard resolution to 6318 // C's DR315 which treats bit-width as being part of the type, and this leaks 6319 // into their semantics in some cases). 6320 return {}; 6321 } 6322 6323 /// getPromotedIntegerType - Returns the type that Promotable will 6324 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable 6325 /// integer type. 6326 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const { 6327 assert(!Promotable.isNull()); 6328 assert(Promotable->isPromotableIntegerType()); 6329 if (const auto *ET = Promotable->getAs<EnumType>()) 6330 return ET->getDecl()->getPromotionType(); 6331 6332 if (const auto *BT = Promotable->getAs<BuiltinType>()) { 6333 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t 6334 // (3.9.1) can be converted to a prvalue of the first of the following 6335 // types that can represent all the values of its underlying type: 6336 // int, unsigned int, long int, unsigned long int, long long int, or 6337 // unsigned long long int [...] 6338 // FIXME: Is there some better way to compute this? 6339 if (BT->getKind() == BuiltinType::WChar_S || 6340 BT->getKind() == BuiltinType::WChar_U || 6341 BT->getKind() == BuiltinType::Char8 || 6342 BT->getKind() == BuiltinType::Char16 || 6343 BT->getKind() == BuiltinType::Char32) { 6344 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S; 6345 uint64_t FromSize = getTypeSize(BT); 6346 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy, 6347 LongLongTy, UnsignedLongLongTy }; 6348 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) { 6349 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]); 6350 if (FromSize < ToSize || 6351 (FromSize == ToSize && 6352 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) 6353 return PromoteTypes[Idx]; 6354 } 6355 llvm_unreachable("char type should fit into long long"); 6356 } 6357 } 6358 6359 // At this point, we should have a signed or unsigned integer type. 6360 if (Promotable->isSignedIntegerType()) 6361 return IntTy; 6362 uint64_t PromotableSize = getIntWidth(Promotable); 6363 uint64_t IntSize = getIntWidth(IntTy); 6364 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize); 6365 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy; 6366 } 6367 6368 /// Recurses in pointer/array types until it finds an objc retainable 6369 /// type and returns its ownership. 6370 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const { 6371 while (!T.isNull()) { 6372 if (T.getObjCLifetime() != Qualifiers::OCL_None) 6373 return T.getObjCLifetime(); 6374 if (T->isArrayType()) 6375 T = getBaseElementType(T); 6376 else if (const auto *PT = T->getAs<PointerType>()) 6377 T = PT->getPointeeType(); 6378 else if (const auto *RT = T->getAs<ReferenceType>()) 6379 T = RT->getPointeeType(); 6380 else 6381 break; 6382 } 6383 6384 return Qualifiers::OCL_None; 6385 } 6386 6387 static const Type *getIntegerTypeForEnum(const EnumType *ET) { 6388 // Incomplete enum types are not treated as integer types. 6389 // FIXME: In C++, enum types are never integer types. 6390 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped()) 6391 return ET->getDecl()->getIntegerType().getTypePtr(); 6392 return nullptr; 6393 } 6394 6395 /// getIntegerTypeOrder - Returns the highest ranked integer type: 6396 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If 6397 /// LHS < RHS, return -1. 6398 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const { 6399 const Type *LHSC = getCanonicalType(LHS).getTypePtr(); 6400 const Type *RHSC = getCanonicalType(RHS).getTypePtr(); 6401 6402 // Unwrap enums to their underlying type. 6403 if (const auto *ET = dyn_cast<EnumType>(LHSC)) 6404 LHSC = getIntegerTypeForEnum(ET); 6405 if (const auto *ET = dyn_cast<EnumType>(RHSC)) 6406 RHSC = getIntegerTypeForEnum(ET); 6407 6408 if (LHSC == RHSC) return 0; 6409 6410 bool LHSUnsigned = LHSC->isUnsignedIntegerType(); 6411 bool RHSUnsigned = RHSC->isUnsignedIntegerType(); 6412 6413 unsigned LHSRank = getIntegerRank(LHSC); 6414 unsigned RHSRank = getIntegerRank(RHSC); 6415 6416 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned. 6417 if (LHSRank == RHSRank) return 0; 6418 return LHSRank > RHSRank ? 1 : -1; 6419 } 6420 6421 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa. 6422 if (LHSUnsigned) { 6423 // If the unsigned [LHS] type is larger, return it. 6424 if (LHSRank >= RHSRank) 6425 return 1; 6426 6427 // If the signed type can represent all values of the unsigned type, it 6428 // wins. Because we are dealing with 2's complement and types that are 6429 // powers of two larger than each other, this is always safe. 6430 return -1; 6431 } 6432 6433 // If the unsigned [RHS] type is larger, return it. 6434 if (RHSRank >= LHSRank) 6435 return -1; 6436 6437 // If the signed type can represent all values of the unsigned type, it 6438 // wins. Because we are dealing with 2's complement and types that are 6439 // powers of two larger than each other, this is always safe. 6440 return 1; 6441 } 6442 6443 TypedefDecl *ASTContext::getCFConstantStringDecl() const { 6444 if (CFConstantStringTypeDecl) 6445 return CFConstantStringTypeDecl; 6446 6447 assert(!CFConstantStringTagDecl && 6448 "tag and typedef should be initialized together"); 6449 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag"); 6450 CFConstantStringTagDecl->startDefinition(); 6451 6452 struct { 6453 QualType Type; 6454 const char *Name; 6455 } Fields[5]; 6456 unsigned Count = 0; 6457 6458 /// Objective-C ABI 6459 /// 6460 /// typedef struct __NSConstantString_tag { 6461 /// const int *isa; 6462 /// int flags; 6463 /// const char *str; 6464 /// long length; 6465 /// } __NSConstantString; 6466 /// 6467 /// Swift ABI (4.1, 4.2) 6468 /// 6469 /// typedef struct __NSConstantString_tag { 6470 /// uintptr_t _cfisa; 6471 /// uintptr_t _swift_rc; 6472 /// _Atomic(uint64_t) _cfinfoa; 6473 /// const char *_ptr; 6474 /// uint32_t _length; 6475 /// } __NSConstantString; 6476 /// 6477 /// Swift ABI (5.0) 6478 /// 6479 /// typedef struct __NSConstantString_tag { 6480 /// uintptr_t _cfisa; 6481 /// uintptr_t _swift_rc; 6482 /// _Atomic(uint64_t) _cfinfoa; 6483 /// const char *_ptr; 6484 /// uintptr_t _length; 6485 /// } __NSConstantString; 6486 6487 const auto CFRuntime = getLangOpts().CFRuntime; 6488 if (static_cast<unsigned>(CFRuntime) < 6489 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) { 6490 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" }; 6491 Fields[Count++] = { IntTy, "flags" }; 6492 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" }; 6493 Fields[Count++] = { LongTy, "length" }; 6494 } else { 6495 Fields[Count++] = { getUIntPtrType(), "_cfisa" }; 6496 Fields[Count++] = { getUIntPtrType(), "_swift_rc" }; 6497 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" }; 6498 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" }; 6499 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 || 6500 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2) 6501 Fields[Count++] = { IntTy, "_ptr" }; 6502 else 6503 Fields[Count++] = { getUIntPtrType(), "_ptr" }; 6504 } 6505 6506 // Create fields 6507 for (unsigned i = 0; i < Count; ++i) { 6508 FieldDecl *Field = 6509 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(), 6510 SourceLocation(), &Idents.get(Fields[i].Name), 6511 Fields[i].Type, /*TInfo=*/nullptr, 6512 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); 6513 Field->setAccess(AS_public); 6514 CFConstantStringTagDecl->addDecl(Field); 6515 } 6516 6517 CFConstantStringTagDecl->completeDefinition(); 6518 // This type is designed to be compatible with NSConstantString, but cannot 6519 // use the same name, since NSConstantString is an interface. 6520 auto tagType = getTagDeclType(CFConstantStringTagDecl); 6521 CFConstantStringTypeDecl = 6522 buildImplicitTypedef(tagType, "__NSConstantString"); 6523 6524 return CFConstantStringTypeDecl; 6525 } 6526 6527 RecordDecl *ASTContext::getCFConstantStringTagDecl() const { 6528 if (!CFConstantStringTagDecl) 6529 getCFConstantStringDecl(); // Build the tag and the typedef. 6530 return CFConstantStringTagDecl; 6531 } 6532 6533 // getCFConstantStringType - Return the type used for constant CFStrings. 6534 QualType ASTContext::getCFConstantStringType() const { 6535 return getTypedefType(getCFConstantStringDecl()); 6536 } 6537 6538 QualType ASTContext::getObjCSuperType() const { 6539 if (ObjCSuperType.isNull()) { 6540 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super"); 6541 TUDecl->addDecl(ObjCSuperTypeDecl); 6542 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl); 6543 } 6544 return ObjCSuperType; 6545 } 6546 6547 void ASTContext::setCFConstantStringType(QualType T) { 6548 const auto *TD = T->castAs<TypedefType>(); 6549 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl()); 6550 const auto *TagType = 6551 CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>(); 6552 CFConstantStringTagDecl = TagType->getDecl(); 6553 } 6554 6555 QualType ASTContext::getBlockDescriptorType() const { 6556 if (BlockDescriptorType) 6557 return getTagDeclType(BlockDescriptorType); 6558 6559 RecordDecl *RD; 6560 // FIXME: Needs the FlagAppleBlock bit. 6561 RD = buildImplicitRecord("__block_descriptor"); 6562 RD->startDefinition(); 6563 6564 QualType FieldTypes[] = { 6565 UnsignedLongTy, 6566 UnsignedLongTy, 6567 }; 6568 6569 static const char *const FieldNames[] = { 6570 "reserved", 6571 "Size" 6572 }; 6573 6574 for (size_t i = 0; i < 2; ++i) { 6575 FieldDecl *Field = FieldDecl::Create( 6576 *this, RD, SourceLocation(), SourceLocation(), 6577 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, 6578 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); 6579 Field->setAccess(AS_public); 6580 RD->addDecl(Field); 6581 } 6582 6583 RD->completeDefinition(); 6584 6585 BlockDescriptorType = RD; 6586 6587 return getTagDeclType(BlockDescriptorType); 6588 } 6589 6590 QualType ASTContext::getBlockDescriptorExtendedType() const { 6591 if (BlockDescriptorExtendedType) 6592 return getTagDeclType(BlockDescriptorExtendedType); 6593 6594 RecordDecl *RD; 6595 // FIXME: Needs the FlagAppleBlock bit. 6596 RD = buildImplicitRecord("__block_descriptor_withcopydispose"); 6597 RD->startDefinition(); 6598 6599 QualType FieldTypes[] = { 6600 UnsignedLongTy, 6601 UnsignedLongTy, 6602 getPointerType(VoidPtrTy), 6603 getPointerType(VoidPtrTy) 6604 }; 6605 6606 static const char *const FieldNames[] = { 6607 "reserved", 6608 "Size", 6609 "CopyFuncPtr", 6610 "DestroyFuncPtr" 6611 }; 6612 6613 for (size_t i = 0; i < 4; ++i) { 6614 FieldDecl *Field = FieldDecl::Create( 6615 *this, RD, SourceLocation(), SourceLocation(), 6616 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, 6617 /*BitWidth=*/nullptr, 6618 /*Mutable=*/false, ICIS_NoInit); 6619 Field->setAccess(AS_public); 6620 RD->addDecl(Field); 6621 } 6622 6623 RD->completeDefinition(); 6624 6625 BlockDescriptorExtendedType = RD; 6626 return getTagDeclType(BlockDescriptorExtendedType); 6627 } 6628 6629 OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const { 6630 const auto *BT = dyn_cast<BuiltinType>(T); 6631 6632 if (!BT) { 6633 if (isa<PipeType>(T)) 6634 return OCLTK_Pipe; 6635 6636 return OCLTK_Default; 6637 } 6638 6639 switch (BT->getKind()) { 6640 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6641 case BuiltinType::Id: \ 6642 return OCLTK_Image; 6643 #include "clang/Basic/OpenCLImageTypes.def" 6644 6645 case BuiltinType::OCLClkEvent: 6646 return OCLTK_ClkEvent; 6647 6648 case BuiltinType::OCLEvent: 6649 return OCLTK_Event; 6650 6651 case BuiltinType::OCLQueue: 6652 return OCLTK_Queue; 6653 6654 case BuiltinType::OCLReserveID: 6655 return OCLTK_ReserveID; 6656 6657 case BuiltinType::OCLSampler: 6658 return OCLTK_Sampler; 6659 6660 default: 6661 return OCLTK_Default; 6662 } 6663 } 6664 6665 LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const { 6666 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)); 6667 } 6668 6669 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty" 6670 /// requires copy/dispose. Note that this must match the logic 6671 /// in buildByrefHelpers. 6672 bool ASTContext::BlockRequiresCopying(QualType Ty, 6673 const VarDecl *D) { 6674 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) { 6675 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr(); 6676 if (!copyExpr && record->hasTrivialDestructor()) return false; 6677 6678 return true; 6679 } 6680 6681 // The block needs copy/destroy helpers if Ty is non-trivial to destructively 6682 // move or destroy. 6683 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType()) 6684 return true; 6685 6686 if (!Ty->isObjCRetainableType()) return false; 6687 6688 Qualifiers qs = Ty.getQualifiers(); 6689 6690 // If we have lifetime, that dominates. 6691 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) { 6692 switch (lifetime) { 6693 case Qualifiers::OCL_None: llvm_unreachable("impossible"); 6694 6695 // These are just bits as far as the runtime is concerned. 6696 case Qualifiers::OCL_ExplicitNone: 6697 case Qualifiers::OCL_Autoreleasing: 6698 return false; 6699 6700 // These cases should have been taken care of when checking the type's 6701 // non-triviality. 6702 case Qualifiers::OCL_Weak: 6703 case Qualifiers::OCL_Strong: 6704 llvm_unreachable("impossible"); 6705 } 6706 llvm_unreachable("fell out of lifetime switch!"); 6707 } 6708 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) || 6709 Ty->isObjCObjectPointerType()); 6710 } 6711 6712 bool ASTContext::getByrefLifetime(QualType Ty, 6713 Qualifiers::ObjCLifetime &LifeTime, 6714 bool &HasByrefExtendedLayout) const { 6715 if (!getLangOpts().ObjC || 6716 getLangOpts().getGC() != LangOptions::NonGC) 6717 return false; 6718 6719 HasByrefExtendedLayout = false; 6720 if (Ty->isRecordType()) { 6721 HasByrefExtendedLayout = true; 6722 LifeTime = Qualifiers::OCL_None; 6723 } else if ((LifeTime = Ty.getObjCLifetime())) { 6724 // Honor the ARC qualifiers. 6725 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) { 6726 // The MRR rule. 6727 LifeTime = Qualifiers::OCL_ExplicitNone; 6728 } else { 6729 LifeTime = Qualifiers::OCL_None; 6730 } 6731 return true; 6732 } 6733 6734 CanQualType ASTContext::getNSUIntegerType() const { 6735 assert(Target && "Expected target to be initialized"); 6736 const llvm::Triple &T = Target->getTriple(); 6737 // Windows is LLP64 rather than LP64 6738 if (T.isOSWindows() && T.isArch64Bit()) 6739 return UnsignedLongLongTy; 6740 return UnsignedLongTy; 6741 } 6742 6743 CanQualType ASTContext::getNSIntegerType() const { 6744 assert(Target && "Expected target to be initialized"); 6745 const llvm::Triple &T = Target->getTriple(); 6746 // Windows is LLP64 rather than LP64 6747 if (T.isOSWindows() && T.isArch64Bit()) 6748 return LongLongTy; 6749 return LongTy; 6750 } 6751 6752 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() { 6753 if (!ObjCInstanceTypeDecl) 6754 ObjCInstanceTypeDecl = 6755 buildImplicitTypedef(getObjCIdType(), "instancetype"); 6756 return ObjCInstanceTypeDecl; 6757 } 6758 6759 // This returns true if a type has been typedefed to BOOL: 6760 // typedef <type> BOOL; 6761 static bool isTypeTypedefedAsBOOL(QualType T) { 6762 if (const auto *TT = dyn_cast<TypedefType>(T)) 6763 if (IdentifierInfo *II = TT->getDecl()->getIdentifier()) 6764 return II->isStr("BOOL"); 6765 6766 return false; 6767 } 6768 6769 /// getObjCEncodingTypeSize returns size of type for objective-c encoding 6770 /// purpose. 6771 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const { 6772 if (!type->isIncompleteArrayType() && type->isIncompleteType()) 6773 return CharUnits::Zero(); 6774 6775 CharUnits sz = getTypeSizeInChars(type); 6776 6777 // Make all integer and enum types at least as large as an int 6778 if (sz.isPositive() && type->isIntegralOrEnumerationType()) 6779 sz = std::max(sz, getTypeSizeInChars(IntTy)); 6780 // Treat arrays as pointers, since that's how they're passed in. 6781 else if (type->isArrayType()) 6782 sz = getTypeSizeInChars(VoidPtrTy); 6783 return sz; 6784 } 6785 6786 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const { 6787 return getTargetInfo().getCXXABI().isMicrosoft() && 6788 VD->isStaticDataMember() && 6789 VD->getType()->isIntegralOrEnumerationType() && 6790 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit(); 6791 } 6792 6793 ASTContext::InlineVariableDefinitionKind 6794 ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const { 6795 if (!VD->isInline()) 6796 return InlineVariableDefinitionKind::None; 6797 6798 // In almost all cases, it's a weak definition. 6799 auto *First = VD->getFirstDecl(); 6800 if (First->isInlineSpecified() || !First->isStaticDataMember()) 6801 return InlineVariableDefinitionKind::Weak; 6802 6803 // If there's a file-context declaration in this translation unit, it's a 6804 // non-discardable definition. 6805 for (auto *D : VD->redecls()) 6806 if (D->getLexicalDeclContext()->isFileContext() && 6807 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr())) 6808 return InlineVariableDefinitionKind::Strong; 6809 6810 // If we've not seen one yet, we don't know. 6811 return InlineVariableDefinitionKind::WeakUnknown; 6812 } 6813 6814 static std::string charUnitsToString(const CharUnits &CU) { 6815 return llvm::itostr(CU.getQuantity()); 6816 } 6817 6818 /// getObjCEncodingForBlock - Return the encoded type for this block 6819 /// declaration. 6820 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const { 6821 std::string S; 6822 6823 const BlockDecl *Decl = Expr->getBlockDecl(); 6824 QualType BlockTy = 6825 Expr->getType()->castAs<BlockPointerType>()->getPointeeType(); 6826 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType(); 6827 // Encode result type. 6828 if (getLangOpts().EncodeExtendedBlockSig) 6829 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, BlockReturnTy, S, 6830 true /*Extended*/); 6831 else 6832 getObjCEncodingForType(BlockReturnTy, S); 6833 // Compute size of all parameters. 6834 // Start with computing size of a pointer in number of bytes. 6835 // FIXME: There might(should) be a better way of doing this computation! 6836 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 6837 CharUnits ParmOffset = PtrSize; 6838 for (auto PI : Decl->parameters()) { 6839 QualType PType = PI->getType(); 6840 CharUnits sz = getObjCEncodingTypeSize(PType); 6841 if (sz.isZero()) 6842 continue; 6843 assert(sz.isPositive() && "BlockExpr - Incomplete param type"); 6844 ParmOffset += sz; 6845 } 6846 // Size of the argument frame 6847 S += charUnitsToString(ParmOffset); 6848 // Block pointer and offset. 6849 S += "@?0"; 6850 6851 // Argument types. 6852 ParmOffset = PtrSize; 6853 for (auto PVDecl : Decl->parameters()) { 6854 QualType PType = PVDecl->getOriginalType(); 6855 if (const auto *AT = 6856 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 6857 // Use array's original type only if it has known number of 6858 // elements. 6859 if (!isa<ConstantArrayType>(AT)) 6860 PType = PVDecl->getType(); 6861 } else if (PType->isFunctionType()) 6862 PType = PVDecl->getType(); 6863 if (getLangOpts().EncodeExtendedBlockSig) 6864 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType, 6865 S, true /*Extended*/); 6866 else 6867 getObjCEncodingForType(PType, S); 6868 S += charUnitsToString(ParmOffset); 6869 ParmOffset += getObjCEncodingTypeSize(PType); 6870 } 6871 6872 return S; 6873 } 6874 6875 std::string 6876 ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const { 6877 std::string S; 6878 // Encode result type. 6879 getObjCEncodingForType(Decl->getReturnType(), S); 6880 CharUnits ParmOffset; 6881 // Compute size of all parameters. 6882 for (auto PI : Decl->parameters()) { 6883 QualType PType = PI->getType(); 6884 CharUnits sz = getObjCEncodingTypeSize(PType); 6885 if (sz.isZero()) 6886 continue; 6887 6888 assert(sz.isPositive() && 6889 "getObjCEncodingForFunctionDecl - Incomplete param type"); 6890 ParmOffset += sz; 6891 } 6892 S += charUnitsToString(ParmOffset); 6893 ParmOffset = CharUnits::Zero(); 6894 6895 // Argument types. 6896 for (auto PVDecl : Decl->parameters()) { 6897 QualType PType = PVDecl->getOriginalType(); 6898 if (const auto *AT = 6899 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 6900 // Use array's original type only if it has known number of 6901 // elements. 6902 if (!isa<ConstantArrayType>(AT)) 6903 PType = PVDecl->getType(); 6904 } else if (PType->isFunctionType()) 6905 PType = PVDecl->getType(); 6906 getObjCEncodingForType(PType, S); 6907 S += charUnitsToString(ParmOffset); 6908 ParmOffset += getObjCEncodingTypeSize(PType); 6909 } 6910 6911 return S; 6912 } 6913 6914 /// getObjCEncodingForMethodParameter - Return the encoded type for a single 6915 /// method parameter or return type. If Extended, include class names and 6916 /// block object types. 6917 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, 6918 QualType T, std::string& S, 6919 bool Extended) const { 6920 // Encode type qualifer, 'in', 'inout', etc. for the parameter. 6921 getObjCEncodingForTypeQualifier(QT, S); 6922 // Encode parameter type. 6923 ObjCEncOptions Options = ObjCEncOptions() 6924 .setExpandPointedToStructures() 6925 .setExpandStructures() 6926 .setIsOutermostType(); 6927 if (Extended) 6928 Options.setEncodeBlockParameters().setEncodeClassNames(); 6929 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr); 6930 } 6931 6932 /// getObjCEncodingForMethodDecl - Return the encoded type for this method 6933 /// declaration. 6934 std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, 6935 bool Extended) const { 6936 // FIXME: This is not very efficient. 6937 // Encode return type. 6938 std::string S; 6939 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(), 6940 Decl->getReturnType(), S, Extended); 6941 // Compute size of all parameters. 6942 // Start with computing size of a pointer in number of bytes. 6943 // FIXME: There might(should) be a better way of doing this computation! 6944 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 6945 // The first two arguments (self and _cmd) are pointers; account for 6946 // their size. 6947 CharUnits ParmOffset = 2 * PtrSize; 6948 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 6949 E = Decl->sel_param_end(); PI != E; ++PI) { 6950 QualType PType = (*PI)->getType(); 6951 CharUnits sz = getObjCEncodingTypeSize(PType); 6952 if (sz.isZero()) 6953 continue; 6954 6955 assert(sz.isPositive() && 6956 "getObjCEncodingForMethodDecl - Incomplete param type"); 6957 ParmOffset += sz; 6958 } 6959 S += charUnitsToString(ParmOffset); 6960 S += "@0:"; 6961 S += charUnitsToString(PtrSize); 6962 6963 // Argument types. 6964 ParmOffset = 2 * PtrSize; 6965 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 6966 E = Decl->sel_param_end(); PI != E; ++PI) { 6967 const ParmVarDecl *PVDecl = *PI; 6968 QualType PType = PVDecl->getOriginalType(); 6969 if (const auto *AT = 6970 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 6971 // Use array's original type only if it has known number of 6972 // elements. 6973 if (!isa<ConstantArrayType>(AT)) 6974 PType = PVDecl->getType(); 6975 } else if (PType->isFunctionType()) 6976 PType = PVDecl->getType(); 6977 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(), 6978 PType, S, Extended); 6979 S += charUnitsToString(ParmOffset); 6980 ParmOffset += getObjCEncodingTypeSize(PType); 6981 } 6982 6983 return S; 6984 } 6985 6986 ObjCPropertyImplDecl * 6987 ASTContext::getObjCPropertyImplDeclForPropertyDecl( 6988 const ObjCPropertyDecl *PD, 6989 const Decl *Container) const { 6990 if (!Container) 6991 return nullptr; 6992 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) { 6993 for (auto *PID : CID->property_impls()) 6994 if (PID->getPropertyDecl() == PD) 6995 return PID; 6996 } else { 6997 const auto *OID = cast<ObjCImplementationDecl>(Container); 6998 for (auto *PID : OID->property_impls()) 6999 if (PID->getPropertyDecl() == PD) 7000 return PID; 7001 } 7002 return nullptr; 7003 } 7004 7005 /// getObjCEncodingForPropertyDecl - Return the encoded type for this 7006 /// property declaration. If non-NULL, Container must be either an 7007 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be 7008 /// NULL when getting encodings for protocol properties. 7009 /// Property attributes are stored as a comma-delimited C string. The simple 7010 /// attributes readonly and bycopy are encoded as single characters. The 7011 /// parametrized attributes, getter=name, setter=name, and ivar=name, are 7012 /// encoded as single characters, followed by an identifier. Property types 7013 /// are also encoded as a parametrized attribute. The characters used to encode 7014 /// these attributes are defined by the following enumeration: 7015 /// @code 7016 /// enum PropertyAttributes { 7017 /// kPropertyReadOnly = 'R', // property is read-only. 7018 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned 7019 /// kPropertyByref = '&', // property is a reference to the value last assigned 7020 /// kPropertyDynamic = 'D', // property is dynamic 7021 /// kPropertyGetter = 'G', // followed by getter selector name 7022 /// kPropertySetter = 'S', // followed by setter selector name 7023 /// kPropertyInstanceVariable = 'V' // followed by instance variable name 7024 /// kPropertyType = 'T' // followed by old-style type encoding. 7025 /// kPropertyWeak = 'W' // 'weak' property 7026 /// kPropertyStrong = 'P' // property GC'able 7027 /// kPropertyNonAtomic = 'N' // property non-atomic 7028 /// }; 7029 /// @endcode 7030 std::string 7031 ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, 7032 const Decl *Container) const { 7033 // Collect information from the property implementation decl(s). 7034 bool Dynamic = false; 7035 ObjCPropertyImplDecl *SynthesizePID = nullptr; 7036 7037 if (ObjCPropertyImplDecl *PropertyImpDecl = 7038 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) { 7039 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) 7040 Dynamic = true; 7041 else 7042 SynthesizePID = PropertyImpDecl; 7043 } 7044 7045 // FIXME: This is not very efficient. 7046 std::string S = "T"; 7047 7048 // Encode result type. 7049 // GCC has some special rules regarding encoding of properties which 7050 // closely resembles encoding of ivars. 7051 getObjCEncodingForPropertyType(PD->getType(), S); 7052 7053 if (PD->isReadOnly()) { 7054 S += ",R"; 7055 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy) 7056 S += ",C"; 7057 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain) 7058 S += ",&"; 7059 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak) 7060 S += ",W"; 7061 } else { 7062 switch (PD->getSetterKind()) { 7063 case ObjCPropertyDecl::Assign: break; 7064 case ObjCPropertyDecl::Copy: S += ",C"; break; 7065 case ObjCPropertyDecl::Retain: S += ",&"; break; 7066 case ObjCPropertyDecl::Weak: S += ",W"; break; 7067 } 7068 } 7069 7070 // It really isn't clear at all what this means, since properties 7071 // are "dynamic by default". 7072 if (Dynamic) 7073 S += ",D"; 7074 7075 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_nonatomic) 7076 S += ",N"; 7077 7078 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) { 7079 S += ",G"; 7080 S += PD->getGetterName().getAsString(); 7081 } 7082 7083 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) { 7084 S += ",S"; 7085 S += PD->getSetterName().getAsString(); 7086 } 7087 7088 if (SynthesizePID) { 7089 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl(); 7090 S += ",V"; 7091 S += OID->getNameAsString(); 7092 } 7093 7094 // FIXME: OBJCGC: weak & strong 7095 return S; 7096 } 7097 7098 /// getLegacyIntegralTypeEncoding - 7099 /// Another legacy compatibility encoding: 32-bit longs are encoded as 7100 /// 'l' or 'L' , but not always. For typedefs, we need to use 7101 /// 'i' or 'I' instead if encoding a struct field, or a pointer! 7102 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const { 7103 if (isa<TypedefType>(PointeeTy.getTypePtr())) { 7104 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) { 7105 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32) 7106 PointeeTy = UnsignedIntTy; 7107 else 7108 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32) 7109 PointeeTy = IntTy; 7110 } 7111 } 7112 } 7113 7114 void ASTContext::getObjCEncodingForType(QualType T, std::string& S, 7115 const FieldDecl *Field, 7116 QualType *NotEncodedT) const { 7117 // We follow the behavior of gcc, expanding structures which are 7118 // directly pointed to, and expanding embedded structures. Note that 7119 // these rules are sufficient to prevent recursive encoding of the 7120 // same type. 7121 getObjCEncodingForTypeImpl(T, S, 7122 ObjCEncOptions() 7123 .setExpandPointedToStructures() 7124 .setExpandStructures() 7125 .setIsOutermostType(), 7126 Field, NotEncodedT); 7127 } 7128 7129 void ASTContext::getObjCEncodingForPropertyType(QualType T, 7130 std::string& S) const { 7131 // Encode result type. 7132 // GCC has some special rules regarding encoding of properties which 7133 // closely resembles encoding of ivars. 7134 getObjCEncodingForTypeImpl(T, S, 7135 ObjCEncOptions() 7136 .setExpandPointedToStructures() 7137 .setExpandStructures() 7138 .setIsOutermostType() 7139 .setEncodingProperty(), 7140 /*Field=*/nullptr); 7141 } 7142 7143 static char getObjCEncodingForPrimitiveType(const ASTContext *C, 7144 const BuiltinType *BT) { 7145 BuiltinType::Kind kind = BT->getKind(); 7146 switch (kind) { 7147 case BuiltinType::Void: return 'v'; 7148 case BuiltinType::Bool: return 'B'; 7149 case BuiltinType::Char8: 7150 case BuiltinType::Char_U: 7151 case BuiltinType::UChar: return 'C'; 7152 case BuiltinType::Char16: 7153 case BuiltinType::UShort: return 'S'; 7154 case BuiltinType::Char32: 7155 case BuiltinType::UInt: return 'I'; 7156 case BuiltinType::ULong: 7157 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q'; 7158 case BuiltinType::UInt128: return 'T'; 7159 case BuiltinType::ULongLong: return 'Q'; 7160 case BuiltinType::Char_S: 7161 case BuiltinType::SChar: return 'c'; 7162 case BuiltinType::Short: return 's'; 7163 case BuiltinType::WChar_S: 7164 case BuiltinType::WChar_U: 7165 case BuiltinType::Int: return 'i'; 7166 case BuiltinType::Long: 7167 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q'; 7168 case BuiltinType::LongLong: return 'q'; 7169 case BuiltinType::Int128: return 't'; 7170 case BuiltinType::Float: return 'f'; 7171 case BuiltinType::Double: return 'd'; 7172 case BuiltinType::LongDouble: return 'D'; 7173 case BuiltinType::NullPtr: return '*'; // like char* 7174 7175 case BuiltinType::BFloat16: 7176 case BuiltinType::Float16: 7177 case BuiltinType::Float128: 7178 case BuiltinType::Half: 7179 case BuiltinType::ShortAccum: 7180 case BuiltinType::Accum: 7181 case BuiltinType::LongAccum: 7182 case BuiltinType::UShortAccum: 7183 case BuiltinType::UAccum: 7184 case BuiltinType::ULongAccum: 7185 case BuiltinType::ShortFract: 7186 case BuiltinType::Fract: 7187 case BuiltinType::LongFract: 7188 case BuiltinType::UShortFract: 7189 case BuiltinType::UFract: 7190 case BuiltinType::ULongFract: 7191 case BuiltinType::SatShortAccum: 7192 case BuiltinType::SatAccum: 7193 case BuiltinType::SatLongAccum: 7194 case BuiltinType::SatUShortAccum: 7195 case BuiltinType::SatUAccum: 7196 case BuiltinType::SatULongAccum: 7197 case BuiltinType::SatShortFract: 7198 case BuiltinType::SatFract: 7199 case BuiltinType::SatLongFract: 7200 case BuiltinType::SatUShortFract: 7201 case BuiltinType::SatUFract: 7202 case BuiltinType::SatULongFract: 7203 // FIXME: potentially need @encodes for these! 7204 return ' '; 7205 7206 #define SVE_TYPE(Name, Id, SingletonId) \ 7207 case BuiltinType::Id: 7208 #include "clang/Basic/AArch64SVEACLETypes.def" 7209 { 7210 DiagnosticsEngine &Diags = C->getDiagnostics(); 7211 unsigned DiagID = Diags.getCustomDiagID( 7212 DiagnosticsEngine::Error, "cannot yet @encode type %0"); 7213 Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy()); 7214 return ' '; 7215 } 7216 7217 case BuiltinType::ObjCId: 7218 case BuiltinType::ObjCClass: 7219 case BuiltinType::ObjCSel: 7220 llvm_unreachable("@encoding ObjC primitive type"); 7221 7222 // OpenCL and placeholder types don't need @encodings. 7223 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 7224 case BuiltinType::Id: 7225 #include "clang/Basic/OpenCLImageTypes.def" 7226 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 7227 case BuiltinType::Id: 7228 #include "clang/Basic/OpenCLExtensionTypes.def" 7229 case BuiltinType::OCLEvent: 7230 case BuiltinType::OCLClkEvent: 7231 case BuiltinType::OCLQueue: 7232 case BuiltinType::OCLReserveID: 7233 case BuiltinType::OCLSampler: 7234 case BuiltinType::Dependent: 7235 #define PPC_MMA_VECTOR_TYPE(Name, Id, Size) \ 7236 case BuiltinType::Id: 7237 #include "clang/Basic/PPCTypes.def" 7238 #define BUILTIN_TYPE(KIND, ID) 7239 #define PLACEHOLDER_TYPE(KIND, ID) \ 7240 case BuiltinType::KIND: 7241 #include "clang/AST/BuiltinTypes.def" 7242 llvm_unreachable("invalid builtin type for @encode"); 7243 } 7244 llvm_unreachable("invalid BuiltinType::Kind value"); 7245 } 7246 7247 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) { 7248 EnumDecl *Enum = ET->getDecl(); 7249 7250 // The encoding of an non-fixed enum type is always 'i', regardless of size. 7251 if (!Enum->isFixed()) 7252 return 'i'; 7253 7254 // The encoding of a fixed enum type matches its fixed underlying type. 7255 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>(); 7256 return getObjCEncodingForPrimitiveType(C, BT); 7257 } 7258 7259 static void EncodeBitField(const ASTContext *Ctx, std::string& S, 7260 QualType T, const FieldDecl *FD) { 7261 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl"); 7262 S += 'b'; 7263 // The NeXT runtime encodes bit fields as b followed by the number of bits. 7264 // The GNU runtime requires more information; bitfields are encoded as b, 7265 // then the offset (in bits) of the first element, then the type of the 7266 // bitfield, then the size in bits. For example, in this structure: 7267 // 7268 // struct 7269 // { 7270 // int integer; 7271 // int flags:2; 7272 // }; 7273 // On a 32-bit system, the encoding for flags would be b2 for the NeXT 7274 // runtime, but b32i2 for the GNU runtime. The reason for this extra 7275 // information is not especially sensible, but we're stuck with it for 7276 // compatibility with GCC, although providing it breaks anything that 7277 // actually uses runtime introspection and wants to work on both runtimes... 7278 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) { 7279 uint64_t Offset; 7280 7281 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) { 7282 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr, 7283 IVD); 7284 } else { 7285 const RecordDecl *RD = FD->getParent(); 7286 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD); 7287 Offset = RL.getFieldOffset(FD->getFieldIndex()); 7288 } 7289 7290 S += llvm::utostr(Offset); 7291 7292 if (const auto *ET = T->getAs<EnumType>()) 7293 S += ObjCEncodingForEnumType(Ctx, ET); 7294 else { 7295 const auto *BT = T->castAs<BuiltinType>(); 7296 S += getObjCEncodingForPrimitiveType(Ctx, BT); 7297 } 7298 } 7299 S += llvm::utostr(FD->getBitWidthValue(*Ctx)); 7300 } 7301 7302 // FIXME: Use SmallString for accumulating string. 7303 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S, 7304 const ObjCEncOptions Options, 7305 const FieldDecl *FD, 7306 QualType *NotEncodedT) const { 7307 CanQualType CT = getCanonicalType(T); 7308 switch (CT->getTypeClass()) { 7309 case Type::Builtin: 7310 case Type::Enum: 7311 if (FD && FD->isBitField()) 7312 return EncodeBitField(this, S, T, FD); 7313 if (const auto *BT = dyn_cast<BuiltinType>(CT)) 7314 S += getObjCEncodingForPrimitiveType(this, BT); 7315 else 7316 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT)); 7317 return; 7318 7319 case Type::Complex: 7320 S += 'j'; 7321 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S, 7322 ObjCEncOptions(), 7323 /*Field=*/nullptr); 7324 return; 7325 7326 case Type::Atomic: 7327 S += 'A'; 7328 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S, 7329 ObjCEncOptions(), 7330 /*Field=*/nullptr); 7331 return; 7332 7333 // encoding for pointer or reference types. 7334 case Type::Pointer: 7335 case Type::LValueReference: 7336 case Type::RValueReference: { 7337 QualType PointeeTy; 7338 if (isa<PointerType>(CT)) { 7339 const auto *PT = T->castAs<PointerType>(); 7340 if (PT->isObjCSelType()) { 7341 S += ':'; 7342 return; 7343 } 7344 PointeeTy = PT->getPointeeType(); 7345 } else { 7346 PointeeTy = T->castAs<ReferenceType>()->getPointeeType(); 7347 } 7348 7349 bool isReadOnly = false; 7350 // For historical/compatibility reasons, the read-only qualifier of the 7351 // pointee gets emitted _before_ the '^'. The read-only qualifier of 7352 // the pointer itself gets ignored, _unless_ we are looking at a typedef! 7353 // Also, do not emit the 'r' for anything but the outermost type! 7354 if (isa<TypedefType>(T.getTypePtr())) { 7355 if (Options.IsOutermostType() && T.isConstQualified()) { 7356 isReadOnly = true; 7357 S += 'r'; 7358 } 7359 } else if (Options.IsOutermostType()) { 7360 QualType P = PointeeTy; 7361 while (auto PT = P->getAs<PointerType>()) 7362 P = PT->getPointeeType(); 7363 if (P.isConstQualified()) { 7364 isReadOnly = true; 7365 S += 'r'; 7366 } 7367 } 7368 if (isReadOnly) { 7369 // Another legacy compatibility encoding. Some ObjC qualifier and type 7370 // combinations need to be rearranged. 7371 // Rewrite "in const" from "nr" to "rn" 7372 if (StringRef(S).endswith("nr")) 7373 S.replace(S.end()-2, S.end(), "rn"); 7374 } 7375 7376 if (PointeeTy->isCharType()) { 7377 // char pointer types should be encoded as '*' unless it is a 7378 // type that has been typedef'd to 'BOOL'. 7379 if (!isTypeTypedefedAsBOOL(PointeeTy)) { 7380 S += '*'; 7381 return; 7382 } 7383 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) { 7384 // GCC binary compat: Need to convert "struct objc_class *" to "#". 7385 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) { 7386 S += '#'; 7387 return; 7388 } 7389 // GCC binary compat: Need to convert "struct objc_object *" to "@". 7390 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) { 7391 S += '@'; 7392 return; 7393 } 7394 // fall through... 7395 } 7396 S += '^'; 7397 getLegacyIntegralTypeEncoding(PointeeTy); 7398 7399 ObjCEncOptions NewOptions; 7400 if (Options.ExpandPointedToStructures()) 7401 NewOptions.setExpandStructures(); 7402 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions, 7403 /*Field=*/nullptr, NotEncodedT); 7404 return; 7405 } 7406 7407 case Type::ConstantArray: 7408 case Type::IncompleteArray: 7409 case Type::VariableArray: { 7410 const auto *AT = cast<ArrayType>(CT); 7411 7412 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) { 7413 // Incomplete arrays are encoded as a pointer to the array element. 7414 S += '^'; 7415 7416 getObjCEncodingForTypeImpl( 7417 AT->getElementType(), S, 7418 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD); 7419 } else { 7420 S += '['; 7421 7422 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) 7423 S += llvm::utostr(CAT->getSize().getZExtValue()); 7424 else { 7425 //Variable length arrays are encoded as a regular array with 0 elements. 7426 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) && 7427 "Unknown array type!"); 7428 S += '0'; 7429 } 7430 7431 getObjCEncodingForTypeImpl( 7432 AT->getElementType(), S, 7433 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD, 7434 NotEncodedT); 7435 S += ']'; 7436 } 7437 return; 7438 } 7439 7440 case Type::FunctionNoProto: 7441 case Type::FunctionProto: 7442 S += '?'; 7443 return; 7444 7445 case Type::Record: { 7446 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl(); 7447 S += RDecl->isUnion() ? '(' : '{'; 7448 // Anonymous structures print as '?' 7449 if (const IdentifierInfo *II = RDecl->getIdentifier()) { 7450 S += II->getName(); 7451 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) { 7452 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 7453 llvm::raw_string_ostream OS(S); 7454 printTemplateArgumentList(OS, TemplateArgs.asArray(), 7455 getPrintingPolicy()); 7456 } 7457 } else { 7458 S += '?'; 7459 } 7460 if (Options.ExpandStructures()) { 7461 S += '='; 7462 if (!RDecl->isUnion()) { 7463 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT); 7464 } else { 7465 for (const auto *Field : RDecl->fields()) { 7466 if (FD) { 7467 S += '"'; 7468 S += Field->getNameAsString(); 7469 S += '"'; 7470 } 7471 7472 // Special case bit-fields. 7473 if (Field->isBitField()) { 7474 getObjCEncodingForTypeImpl(Field->getType(), S, 7475 ObjCEncOptions().setExpandStructures(), 7476 Field); 7477 } else { 7478 QualType qt = Field->getType(); 7479 getLegacyIntegralTypeEncoding(qt); 7480 getObjCEncodingForTypeImpl( 7481 qt, S, 7482 ObjCEncOptions().setExpandStructures().setIsStructField(), FD, 7483 NotEncodedT); 7484 } 7485 } 7486 } 7487 } 7488 S += RDecl->isUnion() ? ')' : '}'; 7489 return; 7490 } 7491 7492 case Type::BlockPointer: { 7493 const auto *BT = T->castAs<BlockPointerType>(); 7494 S += "@?"; // Unlike a pointer-to-function, which is "^?". 7495 if (Options.EncodeBlockParameters()) { 7496 const auto *FT = BT->getPointeeType()->castAs<FunctionType>(); 7497 7498 S += '<'; 7499 // Block return type 7500 getObjCEncodingForTypeImpl(FT->getReturnType(), S, 7501 Options.forComponentType(), FD, NotEncodedT); 7502 // Block self 7503 S += "@?"; 7504 // Block parameters 7505 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) { 7506 for (const auto &I : FPT->param_types()) 7507 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD, 7508 NotEncodedT); 7509 } 7510 S += '>'; 7511 } 7512 return; 7513 } 7514 7515 case Type::ObjCObject: { 7516 // hack to match legacy encoding of *id and *Class 7517 QualType Ty = getObjCObjectPointerType(CT); 7518 if (Ty->isObjCIdType()) { 7519 S += "{objc_object=}"; 7520 return; 7521 } 7522 else if (Ty->isObjCClassType()) { 7523 S += "{objc_class=}"; 7524 return; 7525 } 7526 // TODO: Double check to make sure this intentionally falls through. 7527 LLVM_FALLTHROUGH; 7528 } 7529 7530 case Type::ObjCInterface: { 7531 // Ignore protocol qualifiers when mangling at this level. 7532 // @encode(class_name) 7533 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface(); 7534 S += '{'; 7535 S += OI->getObjCRuntimeNameAsString(); 7536 if (Options.ExpandStructures()) { 7537 S += '='; 7538 SmallVector<const ObjCIvarDecl*, 32> Ivars; 7539 DeepCollectObjCIvars(OI, true, Ivars); 7540 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) { 7541 const FieldDecl *Field = Ivars[i]; 7542 if (Field->isBitField()) 7543 getObjCEncodingForTypeImpl(Field->getType(), S, 7544 ObjCEncOptions().setExpandStructures(), 7545 Field); 7546 else 7547 getObjCEncodingForTypeImpl(Field->getType(), S, 7548 ObjCEncOptions().setExpandStructures(), FD, 7549 NotEncodedT); 7550 } 7551 } 7552 S += '}'; 7553 return; 7554 } 7555 7556 case Type::ObjCObjectPointer: { 7557 const auto *OPT = T->castAs<ObjCObjectPointerType>(); 7558 if (OPT->isObjCIdType()) { 7559 S += '@'; 7560 return; 7561 } 7562 7563 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) { 7564 // FIXME: Consider if we need to output qualifiers for 'Class<p>'. 7565 // Since this is a binary compatibility issue, need to consult with 7566 // runtime folks. Fortunately, this is a *very* obscure construct. 7567 S += '#'; 7568 return; 7569 } 7570 7571 if (OPT->isObjCQualifiedIdType()) { 7572 getObjCEncodingForTypeImpl( 7573 getObjCIdType(), S, 7574 Options.keepingOnly(ObjCEncOptions() 7575 .setExpandPointedToStructures() 7576 .setExpandStructures()), 7577 FD); 7578 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) { 7579 // Note that we do extended encoding of protocol qualifer list 7580 // Only when doing ivar or property encoding. 7581 S += '"'; 7582 for (const auto *I : OPT->quals()) { 7583 S += '<'; 7584 S += I->getObjCRuntimeNameAsString(); 7585 S += '>'; 7586 } 7587 S += '"'; 7588 } 7589 return; 7590 } 7591 7592 S += '@'; 7593 if (OPT->getInterfaceDecl() && 7594 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) { 7595 S += '"'; 7596 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString(); 7597 for (const auto *I : OPT->quals()) { 7598 S += '<'; 7599 S += I->getObjCRuntimeNameAsString(); 7600 S += '>'; 7601 } 7602 S += '"'; 7603 } 7604 return; 7605 } 7606 7607 // gcc just blithely ignores member pointers. 7608 // FIXME: we should do better than that. 'M' is available. 7609 case Type::MemberPointer: 7610 // This matches gcc's encoding, even though technically it is insufficient. 7611 //FIXME. We should do a better job than gcc. 7612 case Type::Vector: 7613 case Type::ExtVector: 7614 // Until we have a coherent encoding of these three types, issue warning. 7615 if (NotEncodedT) 7616 *NotEncodedT = T; 7617 return; 7618 7619 case Type::ConstantMatrix: 7620 if (NotEncodedT) 7621 *NotEncodedT = T; 7622 return; 7623 7624 // We could see an undeduced auto type here during error recovery. 7625 // Just ignore it. 7626 case Type::Auto: 7627 case Type::DeducedTemplateSpecialization: 7628 return; 7629 7630 case Type::Pipe: 7631 case Type::ExtInt: 7632 #define ABSTRACT_TYPE(KIND, BASE) 7633 #define TYPE(KIND, BASE) 7634 #define DEPENDENT_TYPE(KIND, BASE) \ 7635 case Type::KIND: 7636 #define NON_CANONICAL_TYPE(KIND, BASE) \ 7637 case Type::KIND: 7638 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \ 7639 case Type::KIND: 7640 #include "clang/AST/TypeNodes.inc" 7641 llvm_unreachable("@encode for dependent type!"); 7642 } 7643 llvm_unreachable("bad type kind!"); 7644 } 7645 7646 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl, 7647 std::string &S, 7648 const FieldDecl *FD, 7649 bool includeVBases, 7650 QualType *NotEncodedT) const { 7651 assert(RDecl && "Expected non-null RecordDecl"); 7652 assert(!RDecl->isUnion() && "Should not be called for unions"); 7653 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl()) 7654 return; 7655 7656 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl); 7657 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets; 7658 const ASTRecordLayout &layout = getASTRecordLayout(RDecl); 7659 7660 if (CXXRec) { 7661 for (const auto &BI : CXXRec->bases()) { 7662 if (!BI.isVirtual()) { 7663 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); 7664 if (base->isEmpty()) 7665 continue; 7666 uint64_t offs = toBits(layout.getBaseClassOffset(base)); 7667 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 7668 std::make_pair(offs, base)); 7669 } 7670 } 7671 } 7672 7673 unsigned i = 0; 7674 for (FieldDecl *Field : RDecl->fields()) { 7675 if (!Field->isZeroLengthBitField(*this) && Field->isZeroSize(*this)) 7676 continue; 7677 uint64_t offs = layout.getFieldOffset(i); 7678 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 7679 std::make_pair(offs, Field)); 7680 ++i; 7681 } 7682 7683 if (CXXRec && includeVBases) { 7684 for (const auto &BI : CXXRec->vbases()) { 7685 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); 7686 if (base->isEmpty()) 7687 continue; 7688 uint64_t offs = toBits(layout.getVBaseClassOffset(base)); 7689 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) && 7690 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end()) 7691 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(), 7692 std::make_pair(offs, base)); 7693 } 7694 } 7695 7696 CharUnits size; 7697 if (CXXRec) { 7698 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize(); 7699 } else { 7700 size = layout.getSize(); 7701 } 7702 7703 #ifndef NDEBUG 7704 uint64_t CurOffs = 0; 7705 #endif 7706 std::multimap<uint64_t, NamedDecl *>::iterator 7707 CurLayObj = FieldOrBaseOffsets.begin(); 7708 7709 if (CXXRec && CXXRec->isDynamicClass() && 7710 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) { 7711 if (FD) { 7712 S += "\"_vptr$"; 7713 std::string recname = CXXRec->getNameAsString(); 7714 if (recname.empty()) recname = "?"; 7715 S += recname; 7716 S += '"'; 7717 } 7718 S += "^^?"; 7719 #ifndef NDEBUG 7720 CurOffs += getTypeSize(VoidPtrTy); 7721 #endif 7722 } 7723 7724 if (!RDecl->hasFlexibleArrayMember()) { 7725 // Mark the end of the structure. 7726 uint64_t offs = toBits(size); 7727 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 7728 std::make_pair(offs, nullptr)); 7729 } 7730 7731 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) { 7732 #ifndef NDEBUG 7733 assert(CurOffs <= CurLayObj->first); 7734 if (CurOffs < CurLayObj->first) { 7735 uint64_t padding = CurLayObj->first - CurOffs; 7736 // FIXME: There doesn't seem to be a way to indicate in the encoding that 7737 // packing/alignment of members is different that normal, in which case 7738 // the encoding will be out-of-sync with the real layout. 7739 // If the runtime switches to just consider the size of types without 7740 // taking into account alignment, we could make padding explicit in the 7741 // encoding (e.g. using arrays of chars). The encoding strings would be 7742 // longer then though. 7743 CurOffs += padding; 7744 } 7745 #endif 7746 7747 NamedDecl *dcl = CurLayObj->second; 7748 if (!dcl) 7749 break; // reached end of structure. 7750 7751 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) { 7752 // We expand the bases without their virtual bases since those are going 7753 // in the initial structure. Note that this differs from gcc which 7754 // expands virtual bases each time one is encountered in the hierarchy, 7755 // making the encoding type bigger than it really is. 7756 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false, 7757 NotEncodedT); 7758 assert(!base->isEmpty()); 7759 #ifndef NDEBUG 7760 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize()); 7761 #endif 7762 } else { 7763 const auto *field = cast<FieldDecl>(dcl); 7764 if (FD) { 7765 S += '"'; 7766 S += field->getNameAsString(); 7767 S += '"'; 7768 } 7769 7770 if (field->isBitField()) { 7771 EncodeBitField(this, S, field->getType(), field); 7772 #ifndef NDEBUG 7773 CurOffs += field->getBitWidthValue(*this); 7774 #endif 7775 } else { 7776 QualType qt = field->getType(); 7777 getLegacyIntegralTypeEncoding(qt); 7778 getObjCEncodingForTypeImpl( 7779 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(), 7780 FD, NotEncodedT); 7781 #ifndef NDEBUG 7782 CurOffs += getTypeSize(field->getType()); 7783 #endif 7784 } 7785 } 7786 } 7787 } 7788 7789 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, 7790 std::string& S) const { 7791 if (QT & Decl::OBJC_TQ_In) 7792 S += 'n'; 7793 if (QT & Decl::OBJC_TQ_Inout) 7794 S += 'N'; 7795 if (QT & Decl::OBJC_TQ_Out) 7796 S += 'o'; 7797 if (QT & Decl::OBJC_TQ_Bycopy) 7798 S += 'O'; 7799 if (QT & Decl::OBJC_TQ_Byref) 7800 S += 'R'; 7801 if (QT & Decl::OBJC_TQ_Oneway) 7802 S += 'V'; 7803 } 7804 7805 TypedefDecl *ASTContext::getObjCIdDecl() const { 7806 if (!ObjCIdDecl) { 7807 QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {}); 7808 T = getObjCObjectPointerType(T); 7809 ObjCIdDecl = buildImplicitTypedef(T, "id"); 7810 } 7811 return ObjCIdDecl; 7812 } 7813 7814 TypedefDecl *ASTContext::getObjCSelDecl() const { 7815 if (!ObjCSelDecl) { 7816 QualType T = getPointerType(ObjCBuiltinSelTy); 7817 ObjCSelDecl = buildImplicitTypedef(T, "SEL"); 7818 } 7819 return ObjCSelDecl; 7820 } 7821 7822 TypedefDecl *ASTContext::getObjCClassDecl() const { 7823 if (!ObjCClassDecl) { 7824 QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {}); 7825 T = getObjCObjectPointerType(T); 7826 ObjCClassDecl = buildImplicitTypedef(T, "Class"); 7827 } 7828 return ObjCClassDecl; 7829 } 7830 7831 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const { 7832 if (!ObjCProtocolClassDecl) { 7833 ObjCProtocolClassDecl 7834 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(), 7835 SourceLocation(), 7836 &Idents.get("Protocol"), 7837 /*typeParamList=*/nullptr, 7838 /*PrevDecl=*/nullptr, 7839 SourceLocation(), true); 7840 } 7841 7842 return ObjCProtocolClassDecl; 7843 } 7844 7845 //===----------------------------------------------------------------------===// 7846 // __builtin_va_list Construction Functions 7847 //===----------------------------------------------------------------------===// 7848 7849 static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context, 7850 StringRef Name) { 7851 // typedef char* __builtin[_ms]_va_list; 7852 QualType T = Context->getPointerType(Context->CharTy); 7853 return Context->buildImplicitTypedef(T, Name); 7854 } 7855 7856 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) { 7857 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list"); 7858 } 7859 7860 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) { 7861 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list"); 7862 } 7863 7864 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) { 7865 // typedef void* __builtin_va_list; 7866 QualType T = Context->getPointerType(Context->VoidTy); 7867 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 7868 } 7869 7870 static TypedefDecl * 7871 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) { 7872 // struct __va_list 7873 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list"); 7874 if (Context->getLangOpts().CPlusPlus) { 7875 // namespace std { struct __va_list { 7876 NamespaceDecl *NS; 7877 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context), 7878 Context->getTranslationUnitDecl(), 7879 /*Inline*/ false, SourceLocation(), 7880 SourceLocation(), &Context->Idents.get("std"), 7881 /*PrevDecl*/ nullptr); 7882 NS->setImplicit(); 7883 VaListTagDecl->setDeclContext(NS); 7884 } 7885 7886 VaListTagDecl->startDefinition(); 7887 7888 const size_t NumFields = 5; 7889 QualType FieldTypes[NumFields]; 7890 const char *FieldNames[NumFields]; 7891 7892 // void *__stack; 7893 FieldTypes[0] = Context->getPointerType(Context->VoidTy); 7894 FieldNames[0] = "__stack"; 7895 7896 // void *__gr_top; 7897 FieldTypes[1] = Context->getPointerType(Context->VoidTy); 7898 FieldNames[1] = "__gr_top"; 7899 7900 // void *__vr_top; 7901 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 7902 FieldNames[2] = "__vr_top"; 7903 7904 // int __gr_offs; 7905 FieldTypes[3] = Context->IntTy; 7906 FieldNames[3] = "__gr_offs"; 7907 7908 // int __vr_offs; 7909 FieldTypes[4] = Context->IntTy; 7910 FieldNames[4] = "__vr_offs"; 7911 7912 // Create fields 7913 for (unsigned i = 0; i < NumFields; ++i) { 7914 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 7915 VaListTagDecl, 7916 SourceLocation(), 7917 SourceLocation(), 7918 &Context->Idents.get(FieldNames[i]), 7919 FieldTypes[i], /*TInfo=*/nullptr, 7920 /*BitWidth=*/nullptr, 7921 /*Mutable=*/false, 7922 ICIS_NoInit); 7923 Field->setAccess(AS_public); 7924 VaListTagDecl->addDecl(Field); 7925 } 7926 VaListTagDecl->completeDefinition(); 7927 Context->VaListTagDecl = VaListTagDecl; 7928 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 7929 7930 // } __builtin_va_list; 7931 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list"); 7932 } 7933 7934 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) { 7935 // typedef struct __va_list_tag { 7936 RecordDecl *VaListTagDecl; 7937 7938 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 7939 VaListTagDecl->startDefinition(); 7940 7941 const size_t NumFields = 5; 7942 QualType FieldTypes[NumFields]; 7943 const char *FieldNames[NumFields]; 7944 7945 // unsigned char gpr; 7946 FieldTypes[0] = Context->UnsignedCharTy; 7947 FieldNames[0] = "gpr"; 7948 7949 // unsigned char fpr; 7950 FieldTypes[1] = Context->UnsignedCharTy; 7951 FieldNames[1] = "fpr"; 7952 7953 // unsigned short reserved; 7954 FieldTypes[2] = Context->UnsignedShortTy; 7955 FieldNames[2] = "reserved"; 7956 7957 // void* overflow_arg_area; 7958 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 7959 FieldNames[3] = "overflow_arg_area"; 7960 7961 // void* reg_save_area; 7962 FieldTypes[4] = Context->getPointerType(Context->VoidTy); 7963 FieldNames[4] = "reg_save_area"; 7964 7965 // Create fields 7966 for (unsigned i = 0; i < NumFields; ++i) { 7967 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl, 7968 SourceLocation(), 7969 SourceLocation(), 7970 &Context->Idents.get(FieldNames[i]), 7971 FieldTypes[i], /*TInfo=*/nullptr, 7972 /*BitWidth=*/nullptr, 7973 /*Mutable=*/false, 7974 ICIS_NoInit); 7975 Field->setAccess(AS_public); 7976 VaListTagDecl->addDecl(Field); 7977 } 7978 VaListTagDecl->completeDefinition(); 7979 Context->VaListTagDecl = VaListTagDecl; 7980 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 7981 7982 // } __va_list_tag; 7983 TypedefDecl *VaListTagTypedefDecl = 7984 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); 7985 7986 QualType VaListTagTypedefType = 7987 Context->getTypedefType(VaListTagTypedefDecl); 7988 7989 // typedef __va_list_tag __builtin_va_list[1]; 7990 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 7991 QualType VaListTagArrayType 7992 = Context->getConstantArrayType(VaListTagTypedefType, 7993 Size, nullptr, ArrayType::Normal, 0); 7994 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 7995 } 7996 7997 static TypedefDecl * 7998 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) { 7999 // struct __va_list_tag { 8000 RecordDecl *VaListTagDecl; 8001 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8002 VaListTagDecl->startDefinition(); 8003 8004 const size_t NumFields = 4; 8005 QualType FieldTypes[NumFields]; 8006 const char *FieldNames[NumFields]; 8007 8008 // unsigned gp_offset; 8009 FieldTypes[0] = Context->UnsignedIntTy; 8010 FieldNames[0] = "gp_offset"; 8011 8012 // unsigned fp_offset; 8013 FieldTypes[1] = Context->UnsignedIntTy; 8014 FieldNames[1] = "fp_offset"; 8015 8016 // void* overflow_arg_area; 8017 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8018 FieldNames[2] = "overflow_arg_area"; 8019 8020 // void* reg_save_area; 8021 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 8022 FieldNames[3] = "reg_save_area"; 8023 8024 // Create fields 8025 for (unsigned i = 0; i < NumFields; ++i) { 8026 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8027 VaListTagDecl, 8028 SourceLocation(), 8029 SourceLocation(), 8030 &Context->Idents.get(FieldNames[i]), 8031 FieldTypes[i], /*TInfo=*/nullptr, 8032 /*BitWidth=*/nullptr, 8033 /*Mutable=*/false, 8034 ICIS_NoInit); 8035 Field->setAccess(AS_public); 8036 VaListTagDecl->addDecl(Field); 8037 } 8038 VaListTagDecl->completeDefinition(); 8039 Context->VaListTagDecl = VaListTagDecl; 8040 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8041 8042 // }; 8043 8044 // typedef struct __va_list_tag __builtin_va_list[1]; 8045 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8046 QualType VaListTagArrayType = Context->getConstantArrayType( 8047 VaListTagType, Size, nullptr, ArrayType::Normal, 0); 8048 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8049 } 8050 8051 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) { 8052 // typedef int __builtin_va_list[4]; 8053 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4); 8054 QualType IntArrayType = Context->getConstantArrayType( 8055 Context->IntTy, Size, nullptr, ArrayType::Normal, 0); 8056 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list"); 8057 } 8058 8059 static TypedefDecl * 8060 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) { 8061 // struct __va_list 8062 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list"); 8063 if (Context->getLangOpts().CPlusPlus) { 8064 // namespace std { struct __va_list { 8065 NamespaceDecl *NS; 8066 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context), 8067 Context->getTranslationUnitDecl(), 8068 /*Inline*/false, SourceLocation(), 8069 SourceLocation(), &Context->Idents.get("std"), 8070 /*PrevDecl*/ nullptr); 8071 NS->setImplicit(); 8072 VaListDecl->setDeclContext(NS); 8073 } 8074 8075 VaListDecl->startDefinition(); 8076 8077 // void * __ap; 8078 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8079 VaListDecl, 8080 SourceLocation(), 8081 SourceLocation(), 8082 &Context->Idents.get("__ap"), 8083 Context->getPointerType(Context->VoidTy), 8084 /*TInfo=*/nullptr, 8085 /*BitWidth=*/nullptr, 8086 /*Mutable=*/false, 8087 ICIS_NoInit); 8088 Field->setAccess(AS_public); 8089 VaListDecl->addDecl(Field); 8090 8091 // }; 8092 VaListDecl->completeDefinition(); 8093 Context->VaListTagDecl = VaListDecl; 8094 8095 // typedef struct __va_list __builtin_va_list; 8096 QualType T = Context->getRecordType(VaListDecl); 8097 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 8098 } 8099 8100 static TypedefDecl * 8101 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) { 8102 // struct __va_list_tag { 8103 RecordDecl *VaListTagDecl; 8104 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8105 VaListTagDecl->startDefinition(); 8106 8107 const size_t NumFields = 4; 8108 QualType FieldTypes[NumFields]; 8109 const char *FieldNames[NumFields]; 8110 8111 // long __gpr; 8112 FieldTypes[0] = Context->LongTy; 8113 FieldNames[0] = "__gpr"; 8114 8115 // long __fpr; 8116 FieldTypes[1] = Context->LongTy; 8117 FieldNames[1] = "__fpr"; 8118 8119 // void *__overflow_arg_area; 8120 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8121 FieldNames[2] = "__overflow_arg_area"; 8122 8123 // void *__reg_save_area; 8124 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 8125 FieldNames[3] = "__reg_save_area"; 8126 8127 // Create fields 8128 for (unsigned i = 0; i < NumFields; ++i) { 8129 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8130 VaListTagDecl, 8131 SourceLocation(), 8132 SourceLocation(), 8133 &Context->Idents.get(FieldNames[i]), 8134 FieldTypes[i], /*TInfo=*/nullptr, 8135 /*BitWidth=*/nullptr, 8136 /*Mutable=*/false, 8137 ICIS_NoInit); 8138 Field->setAccess(AS_public); 8139 VaListTagDecl->addDecl(Field); 8140 } 8141 VaListTagDecl->completeDefinition(); 8142 Context->VaListTagDecl = VaListTagDecl; 8143 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8144 8145 // }; 8146 8147 // typedef __va_list_tag __builtin_va_list[1]; 8148 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8149 QualType VaListTagArrayType = Context->getConstantArrayType( 8150 VaListTagType, Size, nullptr, ArrayType::Normal, 0); 8151 8152 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8153 } 8154 8155 static TypedefDecl *CreateHexagonBuiltinVaListDecl(const ASTContext *Context) { 8156 // typedef struct __va_list_tag { 8157 RecordDecl *VaListTagDecl; 8158 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8159 VaListTagDecl->startDefinition(); 8160 8161 const size_t NumFields = 3; 8162 QualType FieldTypes[NumFields]; 8163 const char *FieldNames[NumFields]; 8164 8165 // void *CurrentSavedRegisterArea; 8166 FieldTypes[0] = Context->getPointerType(Context->VoidTy); 8167 FieldNames[0] = "__current_saved_reg_area_pointer"; 8168 8169 // void *SavedRegAreaEnd; 8170 FieldTypes[1] = Context->getPointerType(Context->VoidTy); 8171 FieldNames[1] = "__saved_reg_area_end_pointer"; 8172 8173 // void *OverflowArea; 8174 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8175 FieldNames[2] = "__overflow_area_pointer"; 8176 8177 // Create fields 8178 for (unsigned i = 0; i < NumFields; ++i) { 8179 FieldDecl *Field = FieldDecl::Create( 8180 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(), 8181 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i], 8182 /*TInfo=*/0, 8183 /*BitWidth=*/0, 8184 /*Mutable=*/false, ICIS_NoInit); 8185 Field->setAccess(AS_public); 8186 VaListTagDecl->addDecl(Field); 8187 } 8188 VaListTagDecl->completeDefinition(); 8189 Context->VaListTagDecl = VaListTagDecl; 8190 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8191 8192 // } __va_list_tag; 8193 TypedefDecl *VaListTagTypedefDecl = 8194 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); 8195 8196 QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl); 8197 8198 // typedef __va_list_tag __builtin_va_list[1]; 8199 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8200 QualType VaListTagArrayType = Context->getConstantArrayType( 8201 VaListTagTypedefType, Size, nullptr, ArrayType::Normal, 0); 8202 8203 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8204 } 8205 8206 static TypedefDecl *CreateVaListDecl(const ASTContext *Context, 8207 TargetInfo::BuiltinVaListKind Kind) { 8208 switch (Kind) { 8209 case TargetInfo::CharPtrBuiltinVaList: 8210 return CreateCharPtrBuiltinVaListDecl(Context); 8211 case TargetInfo::VoidPtrBuiltinVaList: 8212 return CreateVoidPtrBuiltinVaListDecl(Context); 8213 case TargetInfo::AArch64ABIBuiltinVaList: 8214 return CreateAArch64ABIBuiltinVaListDecl(Context); 8215 case TargetInfo::PowerABIBuiltinVaList: 8216 return CreatePowerABIBuiltinVaListDecl(Context); 8217 case TargetInfo::X86_64ABIBuiltinVaList: 8218 return CreateX86_64ABIBuiltinVaListDecl(Context); 8219 case TargetInfo::PNaClABIBuiltinVaList: 8220 return CreatePNaClABIBuiltinVaListDecl(Context); 8221 case TargetInfo::AAPCSABIBuiltinVaList: 8222 return CreateAAPCSABIBuiltinVaListDecl(Context); 8223 case TargetInfo::SystemZBuiltinVaList: 8224 return CreateSystemZBuiltinVaListDecl(Context); 8225 case TargetInfo::HexagonBuiltinVaList: 8226 return CreateHexagonBuiltinVaListDecl(Context); 8227 } 8228 8229 llvm_unreachable("Unhandled __builtin_va_list type kind"); 8230 } 8231 8232 TypedefDecl *ASTContext::getBuiltinVaListDecl() const { 8233 if (!BuiltinVaListDecl) { 8234 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind()); 8235 assert(BuiltinVaListDecl->isImplicit()); 8236 } 8237 8238 return BuiltinVaListDecl; 8239 } 8240 8241 Decl *ASTContext::getVaListTagDecl() const { 8242 // Force the creation of VaListTagDecl by building the __builtin_va_list 8243 // declaration. 8244 if (!VaListTagDecl) 8245 (void)getBuiltinVaListDecl(); 8246 8247 return VaListTagDecl; 8248 } 8249 8250 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const { 8251 if (!BuiltinMSVaListDecl) 8252 BuiltinMSVaListDecl = CreateMSVaListDecl(this); 8253 8254 return BuiltinMSVaListDecl; 8255 } 8256 8257 bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const { 8258 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID()); 8259 } 8260 8261 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) { 8262 assert(ObjCConstantStringType.isNull() && 8263 "'NSConstantString' type already set!"); 8264 8265 ObjCConstantStringType = getObjCInterfaceType(Decl); 8266 } 8267 8268 /// Retrieve the template name that corresponds to a non-empty 8269 /// lookup. 8270 TemplateName 8271 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin, 8272 UnresolvedSetIterator End) const { 8273 unsigned size = End - Begin; 8274 assert(size > 1 && "set is not overloaded!"); 8275 8276 void *memory = Allocate(sizeof(OverloadedTemplateStorage) + 8277 size * sizeof(FunctionTemplateDecl*)); 8278 auto *OT = new (memory) OverloadedTemplateStorage(size); 8279 8280 NamedDecl **Storage = OT->getStorage(); 8281 for (UnresolvedSetIterator I = Begin; I != End; ++I) { 8282 NamedDecl *D = *I; 8283 assert(isa<FunctionTemplateDecl>(D) || 8284 isa<UnresolvedUsingValueDecl>(D) || 8285 (isa<UsingShadowDecl>(D) && 8286 isa<FunctionTemplateDecl>(D->getUnderlyingDecl()))); 8287 *Storage++ = D; 8288 } 8289 8290 return TemplateName(OT); 8291 } 8292 8293 /// Retrieve a template name representing an unqualified-id that has been 8294 /// assumed to name a template for ADL purposes. 8295 TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const { 8296 auto *OT = new (*this) AssumedTemplateStorage(Name); 8297 return TemplateName(OT); 8298 } 8299 8300 /// Retrieve the template name that represents a qualified 8301 /// template name such as \c std::vector. 8302 TemplateName 8303 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, 8304 bool TemplateKeyword, 8305 TemplateDecl *Template) const { 8306 assert(NNS && "Missing nested-name-specifier in qualified template name"); 8307 8308 // FIXME: Canonicalization? 8309 llvm::FoldingSetNodeID ID; 8310 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template); 8311 8312 void *InsertPos = nullptr; 8313 QualifiedTemplateName *QTN = 8314 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 8315 if (!QTN) { 8316 QTN = new (*this, alignof(QualifiedTemplateName)) 8317 QualifiedTemplateName(NNS, TemplateKeyword, Template); 8318 QualifiedTemplateNames.InsertNode(QTN, InsertPos); 8319 } 8320 8321 return TemplateName(QTN); 8322 } 8323 8324 /// Retrieve the template name that represents a dependent 8325 /// template name such as \c MetaFun::template apply. 8326 TemplateName 8327 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 8328 const IdentifierInfo *Name) const { 8329 assert((!NNS || NNS->isDependent()) && 8330 "Nested name specifier must be dependent"); 8331 8332 llvm::FoldingSetNodeID ID; 8333 DependentTemplateName::Profile(ID, NNS, Name); 8334 8335 void *InsertPos = nullptr; 8336 DependentTemplateName *QTN = 8337 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 8338 8339 if (QTN) 8340 return TemplateName(QTN); 8341 8342 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 8343 if (CanonNNS == NNS) { 8344 QTN = new (*this, alignof(DependentTemplateName)) 8345 DependentTemplateName(NNS, Name); 8346 } else { 8347 TemplateName Canon = getDependentTemplateName(CanonNNS, Name); 8348 QTN = new (*this, alignof(DependentTemplateName)) 8349 DependentTemplateName(NNS, Name, Canon); 8350 DependentTemplateName *CheckQTN = 8351 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 8352 assert(!CheckQTN && "Dependent type name canonicalization broken"); 8353 (void)CheckQTN; 8354 } 8355 8356 DependentTemplateNames.InsertNode(QTN, InsertPos); 8357 return TemplateName(QTN); 8358 } 8359 8360 /// Retrieve the template name that represents a dependent 8361 /// template name such as \c MetaFun::template operator+. 8362 TemplateName 8363 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 8364 OverloadedOperatorKind Operator) const { 8365 assert((!NNS || NNS->isDependent()) && 8366 "Nested name specifier must be dependent"); 8367 8368 llvm::FoldingSetNodeID ID; 8369 DependentTemplateName::Profile(ID, NNS, Operator); 8370 8371 void *InsertPos = nullptr; 8372 DependentTemplateName *QTN 8373 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 8374 8375 if (QTN) 8376 return TemplateName(QTN); 8377 8378 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 8379 if (CanonNNS == NNS) { 8380 QTN = new (*this, alignof(DependentTemplateName)) 8381 DependentTemplateName(NNS, Operator); 8382 } else { 8383 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator); 8384 QTN = new (*this, alignof(DependentTemplateName)) 8385 DependentTemplateName(NNS, Operator, Canon); 8386 8387 DependentTemplateName *CheckQTN 8388 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 8389 assert(!CheckQTN && "Dependent template name canonicalization broken"); 8390 (void)CheckQTN; 8391 } 8392 8393 DependentTemplateNames.InsertNode(QTN, InsertPos); 8394 return TemplateName(QTN); 8395 } 8396 8397 TemplateName 8398 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param, 8399 TemplateName replacement) const { 8400 llvm::FoldingSetNodeID ID; 8401 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement); 8402 8403 void *insertPos = nullptr; 8404 SubstTemplateTemplateParmStorage *subst 8405 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos); 8406 8407 if (!subst) { 8408 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement); 8409 SubstTemplateTemplateParms.InsertNode(subst, insertPos); 8410 } 8411 8412 return TemplateName(subst); 8413 } 8414 8415 TemplateName 8416 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param, 8417 const TemplateArgument &ArgPack) const { 8418 auto &Self = const_cast<ASTContext &>(*this); 8419 llvm::FoldingSetNodeID ID; 8420 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack); 8421 8422 void *InsertPos = nullptr; 8423 SubstTemplateTemplateParmPackStorage *Subst 8424 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos); 8425 8426 if (!Subst) { 8427 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param, 8428 ArgPack.pack_size(), 8429 ArgPack.pack_begin()); 8430 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos); 8431 } 8432 8433 return TemplateName(Subst); 8434 } 8435 8436 /// getFromTargetType - Given one of the integer types provided by 8437 /// TargetInfo, produce the corresponding type. The unsigned @p Type 8438 /// is actually a value of type @c TargetInfo::IntType. 8439 CanQualType ASTContext::getFromTargetType(unsigned Type) const { 8440 switch (Type) { 8441 case TargetInfo::NoInt: return {}; 8442 case TargetInfo::SignedChar: return SignedCharTy; 8443 case TargetInfo::UnsignedChar: return UnsignedCharTy; 8444 case TargetInfo::SignedShort: return ShortTy; 8445 case TargetInfo::UnsignedShort: return UnsignedShortTy; 8446 case TargetInfo::SignedInt: return IntTy; 8447 case TargetInfo::UnsignedInt: return UnsignedIntTy; 8448 case TargetInfo::SignedLong: return LongTy; 8449 case TargetInfo::UnsignedLong: return UnsignedLongTy; 8450 case TargetInfo::SignedLongLong: return LongLongTy; 8451 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy; 8452 } 8453 8454 llvm_unreachable("Unhandled TargetInfo::IntType value"); 8455 } 8456 8457 //===----------------------------------------------------------------------===// 8458 // Type Predicates. 8459 //===----------------------------------------------------------------------===// 8460 8461 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's 8462 /// garbage collection attribute. 8463 /// 8464 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const { 8465 if (getLangOpts().getGC() == LangOptions::NonGC) 8466 return Qualifiers::GCNone; 8467 8468 assert(getLangOpts().ObjC); 8469 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr(); 8470 8471 // Default behaviour under objective-C's gc is for ObjC pointers 8472 // (or pointers to them) be treated as though they were declared 8473 // as __strong. 8474 if (GCAttrs == Qualifiers::GCNone) { 8475 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) 8476 return Qualifiers::Strong; 8477 else if (Ty->isPointerType()) 8478 return getObjCGCAttrKind(Ty->castAs<PointerType>()->getPointeeType()); 8479 } else { 8480 // It's not valid to set GC attributes on anything that isn't a 8481 // pointer. 8482 #ifndef NDEBUG 8483 QualType CT = Ty->getCanonicalTypeInternal(); 8484 while (const auto *AT = dyn_cast<ArrayType>(CT)) 8485 CT = AT->getElementType(); 8486 assert(CT->isAnyPointerType() || CT->isBlockPointerType()); 8487 #endif 8488 } 8489 return GCAttrs; 8490 } 8491 8492 //===----------------------------------------------------------------------===// 8493 // Type Compatibility Testing 8494 //===----------------------------------------------------------------------===// 8495 8496 /// areCompatVectorTypes - Return true if the two specified vector types are 8497 /// compatible. 8498 static bool areCompatVectorTypes(const VectorType *LHS, 8499 const VectorType *RHS) { 8500 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 8501 return LHS->getElementType() == RHS->getElementType() && 8502 LHS->getNumElements() == RHS->getNumElements(); 8503 } 8504 8505 /// areCompatMatrixTypes - Return true if the two specified matrix types are 8506 /// compatible. 8507 static bool areCompatMatrixTypes(const ConstantMatrixType *LHS, 8508 const ConstantMatrixType *RHS) { 8509 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 8510 return LHS->getElementType() == RHS->getElementType() && 8511 LHS->getNumRows() == RHS->getNumRows() && 8512 LHS->getNumColumns() == RHS->getNumColumns(); 8513 } 8514 8515 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec, 8516 QualType SecondVec) { 8517 assert(FirstVec->isVectorType() && "FirstVec should be a vector type"); 8518 assert(SecondVec->isVectorType() && "SecondVec should be a vector type"); 8519 8520 if (hasSameUnqualifiedType(FirstVec, SecondVec)) 8521 return true; 8522 8523 // Treat Neon vector types and most AltiVec vector types as if they are the 8524 // equivalent GCC vector types. 8525 const auto *First = FirstVec->castAs<VectorType>(); 8526 const auto *Second = SecondVec->castAs<VectorType>(); 8527 if (First->getNumElements() == Second->getNumElements() && 8528 hasSameType(First->getElementType(), Second->getElementType()) && 8529 First->getVectorKind() != VectorType::AltiVecPixel && 8530 First->getVectorKind() != VectorType::AltiVecBool && 8531 Second->getVectorKind() != VectorType::AltiVecPixel && 8532 Second->getVectorKind() != VectorType::AltiVecBool && 8533 First->getVectorKind() != VectorType::SveFixedLengthDataVector && 8534 First->getVectorKind() != VectorType::SveFixedLengthPredicateVector && 8535 Second->getVectorKind() != VectorType::SveFixedLengthDataVector && 8536 Second->getVectorKind() != VectorType::SveFixedLengthPredicateVector) 8537 return true; 8538 8539 return false; 8540 } 8541 8542 bool ASTContext::areCompatibleSveTypes(QualType FirstType, 8543 QualType SecondType) { 8544 assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) || 8545 (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) && 8546 "Expected SVE builtin type and vector type!"); 8547 8548 auto IsValidCast = [this](QualType FirstType, QualType SecondType) { 8549 if (const auto *BT = FirstType->getAs<BuiltinType>()) { 8550 if (const auto *VT = SecondType->getAs<VectorType>()) { 8551 // Predicates have the same representation as uint8 so we also have to 8552 // check the kind to make these types incompatible. 8553 if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 8554 return BT->getKind() == BuiltinType::SveBool; 8555 else if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) 8556 return VT->getElementType().getCanonicalType() == 8557 FirstType->getSveEltType(*this); 8558 else if (VT->getVectorKind() == VectorType::GenericVector) 8559 return getTypeSize(SecondType) == getLangOpts().ArmSveVectorBits && 8560 hasSameType(VT->getElementType(), 8561 getBuiltinVectorTypeInfo(BT).ElementType); 8562 } 8563 } 8564 return false; 8565 }; 8566 8567 return IsValidCast(FirstType, SecondType) || 8568 IsValidCast(SecondType, FirstType); 8569 } 8570 8571 bool ASTContext::areLaxCompatibleSveTypes(QualType FirstType, 8572 QualType SecondType) { 8573 assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) || 8574 (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) && 8575 "Expected SVE builtin type and vector type!"); 8576 8577 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) { 8578 if (!FirstType->getAs<BuiltinType>()) 8579 return false; 8580 8581 const auto *VecTy = SecondType->getAs<VectorType>(); 8582 if (VecTy && 8583 (VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector || 8584 VecTy->getVectorKind() == VectorType::GenericVector)) { 8585 const LangOptions::LaxVectorConversionKind LVCKind = 8586 getLangOpts().getLaxVectorConversions(); 8587 8588 // If __ARM_FEATURE_SVE_BITS != N do not allow GNU vector lax conversion. 8589 // "Whenever __ARM_FEATURE_SVE_BITS==N, GNUT implicitly 8590 // converts to VLAT and VLAT implicitly converts to GNUT." 8591 // ACLE Spec Version 00bet6, 3.7.3.2. Behavior common to vectors and 8592 // predicates. 8593 if (VecTy->getVectorKind() == VectorType::GenericVector && 8594 getTypeSize(SecondType) != getLangOpts().ArmSveVectorBits) 8595 return false; 8596 8597 // If -flax-vector-conversions=all is specified, the types are 8598 // certainly compatible. 8599 if (LVCKind == LangOptions::LaxVectorConversionKind::All) 8600 return true; 8601 8602 // If -flax-vector-conversions=integer is specified, the types are 8603 // compatible if the elements are integer types. 8604 if (LVCKind == LangOptions::LaxVectorConversionKind::Integer) 8605 return VecTy->getElementType().getCanonicalType()->isIntegerType() && 8606 FirstType->getSveEltType(*this)->isIntegerType(); 8607 } 8608 8609 return false; 8610 }; 8611 8612 return IsLaxCompatible(FirstType, SecondType) || 8613 IsLaxCompatible(SecondType, FirstType); 8614 } 8615 8616 bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const { 8617 while (true) { 8618 // __strong id 8619 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) { 8620 if (Attr->getAttrKind() == attr::ObjCOwnership) 8621 return true; 8622 8623 Ty = Attr->getModifiedType(); 8624 8625 // X *__strong (...) 8626 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) { 8627 Ty = Paren->getInnerType(); 8628 8629 // We do not want to look through typedefs, typeof(expr), 8630 // typeof(type), or any other way that the type is somehow 8631 // abstracted. 8632 } else { 8633 return false; 8634 } 8635 } 8636 } 8637 8638 //===----------------------------------------------------------------------===// 8639 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's. 8640 //===----------------------------------------------------------------------===// 8641 8642 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the 8643 /// inheritance hierarchy of 'rProto'. 8644 bool 8645 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, 8646 ObjCProtocolDecl *rProto) const { 8647 if (declaresSameEntity(lProto, rProto)) 8648 return true; 8649 for (auto *PI : rProto->protocols()) 8650 if (ProtocolCompatibleWithProtocol(lProto, PI)) 8651 return true; 8652 return false; 8653 } 8654 8655 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and 8656 /// Class<pr1, ...>. 8657 bool ASTContext::ObjCQualifiedClassTypesAreCompatible( 8658 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) { 8659 for (auto *lhsProto : lhs->quals()) { 8660 bool match = false; 8661 for (auto *rhsProto : rhs->quals()) { 8662 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) { 8663 match = true; 8664 break; 8665 } 8666 } 8667 if (!match) 8668 return false; 8669 } 8670 return true; 8671 } 8672 8673 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an 8674 /// ObjCQualifiedIDType. 8675 bool ASTContext::ObjCQualifiedIdTypesAreCompatible( 8676 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs, 8677 bool compare) { 8678 // Allow id<P..> and an 'id' in all cases. 8679 if (lhs->isObjCIdType() || rhs->isObjCIdType()) 8680 return true; 8681 8682 // Don't allow id<P..> to convert to Class or Class<P..> in either direction. 8683 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() || 8684 rhs->isObjCClassType() || rhs->isObjCQualifiedClassType()) 8685 return false; 8686 8687 if (lhs->isObjCQualifiedIdType()) { 8688 if (rhs->qual_empty()) { 8689 // If the RHS is a unqualified interface pointer "NSString*", 8690 // make sure we check the class hierarchy. 8691 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) { 8692 for (auto *I : lhs->quals()) { 8693 // when comparing an id<P> on lhs with a static type on rhs, 8694 // see if static class implements all of id's protocols, directly or 8695 // through its super class and categories. 8696 if (!rhsID->ClassImplementsProtocol(I, true)) 8697 return false; 8698 } 8699 } 8700 // If there are no qualifiers and no interface, we have an 'id'. 8701 return true; 8702 } 8703 // Both the right and left sides have qualifiers. 8704 for (auto *lhsProto : lhs->quals()) { 8705 bool match = false; 8706 8707 // when comparing an id<P> on lhs with a static type on rhs, 8708 // see if static class implements all of id's protocols, directly or 8709 // through its super class and categories. 8710 for (auto *rhsProto : rhs->quals()) { 8711 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 8712 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 8713 match = true; 8714 break; 8715 } 8716 } 8717 // If the RHS is a qualified interface pointer "NSString<P>*", 8718 // make sure we check the class hierarchy. 8719 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) { 8720 for (auto *I : lhs->quals()) { 8721 // when comparing an id<P> on lhs with a static type on rhs, 8722 // see if static class implements all of id's protocols, directly or 8723 // through its super class and categories. 8724 if (rhsID->ClassImplementsProtocol(I, true)) { 8725 match = true; 8726 break; 8727 } 8728 } 8729 } 8730 if (!match) 8731 return false; 8732 } 8733 8734 return true; 8735 } 8736 8737 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>"); 8738 8739 if (lhs->getInterfaceType()) { 8740 // If both the right and left sides have qualifiers. 8741 for (auto *lhsProto : lhs->quals()) { 8742 bool match = false; 8743 8744 // when comparing an id<P> on rhs with a static type on lhs, 8745 // see if static class implements all of id's protocols, directly or 8746 // through its super class and categories. 8747 // First, lhs protocols in the qualifier list must be found, direct 8748 // or indirect in rhs's qualifier list or it is a mismatch. 8749 for (auto *rhsProto : rhs->quals()) { 8750 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 8751 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 8752 match = true; 8753 break; 8754 } 8755 } 8756 if (!match) 8757 return false; 8758 } 8759 8760 // Static class's protocols, or its super class or category protocols 8761 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch. 8762 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) { 8763 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols; 8764 CollectInheritedProtocols(lhsID, LHSInheritedProtocols); 8765 // This is rather dubious but matches gcc's behavior. If lhs has 8766 // no type qualifier and its class has no static protocol(s) 8767 // assume that it is mismatch. 8768 if (LHSInheritedProtocols.empty() && lhs->qual_empty()) 8769 return false; 8770 for (auto *lhsProto : LHSInheritedProtocols) { 8771 bool match = false; 8772 for (auto *rhsProto : rhs->quals()) { 8773 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 8774 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 8775 match = true; 8776 break; 8777 } 8778 } 8779 if (!match) 8780 return false; 8781 } 8782 } 8783 return true; 8784 } 8785 return false; 8786 } 8787 8788 /// canAssignObjCInterfaces - Return true if the two interface types are 8789 /// compatible for assignment from RHS to LHS. This handles validation of any 8790 /// protocol qualifiers on the LHS or RHS. 8791 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, 8792 const ObjCObjectPointerType *RHSOPT) { 8793 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 8794 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 8795 8796 // If either type represents the built-in 'id' type, return true. 8797 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId()) 8798 return true; 8799 8800 // Function object that propagates a successful result or handles 8801 // __kindof types. 8802 auto finish = [&](bool succeeded) -> bool { 8803 if (succeeded) 8804 return true; 8805 8806 if (!RHS->isKindOfType()) 8807 return false; 8808 8809 // Strip off __kindof and protocol qualifiers, then check whether 8810 // we can assign the other way. 8811 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this), 8812 LHSOPT->stripObjCKindOfTypeAndQuals(*this)); 8813 }; 8814 8815 // Casts from or to id<P> are allowed when the other side has compatible 8816 // protocols. 8817 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) { 8818 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false)); 8819 } 8820 8821 // Verify protocol compatibility for casts from Class<P1> to Class<P2>. 8822 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) { 8823 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT)); 8824 } 8825 8826 // Casts from Class to Class<Foo>, or vice-versa, are allowed. 8827 if (LHS->isObjCClass() && RHS->isObjCClass()) { 8828 return true; 8829 } 8830 8831 // If we have 2 user-defined types, fall into that path. 8832 if (LHS->getInterface() && RHS->getInterface()) { 8833 return finish(canAssignObjCInterfaces(LHS, RHS)); 8834 } 8835 8836 return false; 8837 } 8838 8839 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written 8840 /// for providing type-safety for objective-c pointers used to pass/return 8841 /// arguments in block literals. When passed as arguments, passing 'A*' where 8842 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is 8843 /// not OK. For the return type, the opposite is not OK. 8844 bool ASTContext::canAssignObjCInterfacesInBlockPointer( 8845 const ObjCObjectPointerType *LHSOPT, 8846 const ObjCObjectPointerType *RHSOPT, 8847 bool BlockReturnType) { 8848 8849 // Function object that propagates a successful result or handles 8850 // __kindof types. 8851 auto finish = [&](bool succeeded) -> bool { 8852 if (succeeded) 8853 return true; 8854 8855 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT; 8856 if (!Expected->isKindOfType()) 8857 return false; 8858 8859 // Strip off __kindof and protocol qualifiers, then check whether 8860 // we can assign the other way. 8861 return canAssignObjCInterfacesInBlockPointer( 8862 RHSOPT->stripObjCKindOfTypeAndQuals(*this), 8863 LHSOPT->stripObjCKindOfTypeAndQuals(*this), 8864 BlockReturnType); 8865 }; 8866 8867 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType()) 8868 return true; 8869 8870 if (LHSOPT->isObjCBuiltinType()) { 8871 return finish(RHSOPT->isObjCBuiltinType() || 8872 RHSOPT->isObjCQualifiedIdType()); 8873 } 8874 8875 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) { 8876 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking) 8877 // Use for block parameters previous type checking for compatibility. 8878 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) || 8879 // Or corrected type checking as in non-compat mode. 8880 (!BlockReturnType && 8881 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false))); 8882 else 8883 return finish(ObjCQualifiedIdTypesAreCompatible( 8884 (BlockReturnType ? LHSOPT : RHSOPT), 8885 (BlockReturnType ? RHSOPT : LHSOPT), false)); 8886 } 8887 8888 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType(); 8889 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType(); 8890 if (LHS && RHS) { // We have 2 user-defined types. 8891 if (LHS != RHS) { 8892 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl())) 8893 return finish(BlockReturnType); 8894 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl())) 8895 return finish(!BlockReturnType); 8896 } 8897 else 8898 return true; 8899 } 8900 return false; 8901 } 8902 8903 /// Comparison routine for Objective-C protocols to be used with 8904 /// llvm::array_pod_sort. 8905 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs, 8906 ObjCProtocolDecl * const *rhs) { 8907 return (*lhs)->getName().compare((*rhs)->getName()); 8908 } 8909 8910 /// getIntersectionOfProtocols - This routine finds the intersection of set 8911 /// of protocols inherited from two distinct objective-c pointer objects with 8912 /// the given common base. 8913 /// It is used to build composite qualifier list of the composite type of 8914 /// the conditional expression involving two objective-c pointer objects. 8915 static 8916 void getIntersectionOfProtocols(ASTContext &Context, 8917 const ObjCInterfaceDecl *CommonBase, 8918 const ObjCObjectPointerType *LHSOPT, 8919 const ObjCObjectPointerType *RHSOPT, 8920 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) { 8921 8922 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 8923 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 8924 assert(LHS->getInterface() && "LHS must have an interface base"); 8925 assert(RHS->getInterface() && "RHS must have an interface base"); 8926 8927 // Add all of the protocols for the LHS. 8928 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet; 8929 8930 // Start with the protocol qualifiers. 8931 for (auto proto : LHS->quals()) { 8932 Context.CollectInheritedProtocols(proto, LHSProtocolSet); 8933 } 8934 8935 // Also add the protocols associated with the LHS interface. 8936 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet); 8937 8938 // Add all of the protocols for the RHS. 8939 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet; 8940 8941 // Start with the protocol qualifiers. 8942 for (auto proto : RHS->quals()) { 8943 Context.CollectInheritedProtocols(proto, RHSProtocolSet); 8944 } 8945 8946 // Also add the protocols associated with the RHS interface. 8947 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet); 8948 8949 // Compute the intersection of the collected protocol sets. 8950 for (auto proto : LHSProtocolSet) { 8951 if (RHSProtocolSet.count(proto)) 8952 IntersectionSet.push_back(proto); 8953 } 8954 8955 // Compute the set of protocols that is implied by either the common type or 8956 // the protocols within the intersection. 8957 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols; 8958 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols); 8959 8960 // Remove any implied protocols from the list of inherited protocols. 8961 if (!ImpliedProtocols.empty()) { 8962 IntersectionSet.erase( 8963 std::remove_if(IntersectionSet.begin(), 8964 IntersectionSet.end(), 8965 [&](ObjCProtocolDecl *proto) -> bool { 8966 return ImpliedProtocols.count(proto) > 0; 8967 }), 8968 IntersectionSet.end()); 8969 } 8970 8971 // Sort the remaining protocols by name. 8972 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(), 8973 compareObjCProtocolsByName); 8974 } 8975 8976 /// Determine whether the first type is a subtype of the second. 8977 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs, 8978 QualType rhs) { 8979 // Common case: two object pointers. 8980 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>(); 8981 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 8982 if (lhsOPT && rhsOPT) 8983 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT); 8984 8985 // Two block pointers. 8986 const auto *lhsBlock = lhs->getAs<BlockPointerType>(); 8987 const auto *rhsBlock = rhs->getAs<BlockPointerType>(); 8988 if (lhsBlock && rhsBlock) 8989 return ctx.typesAreBlockPointerCompatible(lhs, rhs); 8990 8991 // If either is an unqualified 'id' and the other is a block, it's 8992 // acceptable. 8993 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) || 8994 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock)) 8995 return true; 8996 8997 return false; 8998 } 8999 9000 // Check that the given Objective-C type argument lists are equivalent. 9001 static bool sameObjCTypeArgs(ASTContext &ctx, 9002 const ObjCInterfaceDecl *iface, 9003 ArrayRef<QualType> lhsArgs, 9004 ArrayRef<QualType> rhsArgs, 9005 bool stripKindOf) { 9006 if (lhsArgs.size() != rhsArgs.size()) 9007 return false; 9008 9009 ObjCTypeParamList *typeParams = iface->getTypeParamList(); 9010 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) { 9011 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i])) 9012 continue; 9013 9014 switch (typeParams->begin()[i]->getVariance()) { 9015 case ObjCTypeParamVariance::Invariant: 9016 if (!stripKindOf || 9017 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx), 9018 rhsArgs[i].stripObjCKindOfType(ctx))) { 9019 return false; 9020 } 9021 break; 9022 9023 case ObjCTypeParamVariance::Covariant: 9024 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i])) 9025 return false; 9026 break; 9027 9028 case ObjCTypeParamVariance::Contravariant: 9029 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i])) 9030 return false; 9031 break; 9032 } 9033 } 9034 9035 return true; 9036 } 9037 9038 QualType ASTContext::areCommonBaseCompatible( 9039 const ObjCObjectPointerType *Lptr, 9040 const ObjCObjectPointerType *Rptr) { 9041 const ObjCObjectType *LHS = Lptr->getObjectType(); 9042 const ObjCObjectType *RHS = Rptr->getObjectType(); 9043 const ObjCInterfaceDecl* LDecl = LHS->getInterface(); 9044 const ObjCInterfaceDecl* RDecl = RHS->getInterface(); 9045 9046 if (!LDecl || !RDecl) 9047 return {}; 9048 9049 // When either LHS or RHS is a kindof type, we should return a kindof type. 9050 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return 9051 // kindof(A). 9052 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType(); 9053 9054 // Follow the left-hand side up the class hierarchy until we either hit a 9055 // root or find the RHS. Record the ancestors in case we don't find it. 9056 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4> 9057 LHSAncestors; 9058 while (true) { 9059 // Record this ancestor. We'll need this if the common type isn't in the 9060 // path from the LHS to the root. 9061 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS; 9062 9063 if (declaresSameEntity(LHS->getInterface(), RDecl)) { 9064 // Get the type arguments. 9065 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten(); 9066 bool anyChanges = false; 9067 if (LHS->isSpecialized() && RHS->isSpecialized()) { 9068 // Both have type arguments, compare them. 9069 if (!sameObjCTypeArgs(*this, LHS->getInterface(), 9070 LHS->getTypeArgs(), RHS->getTypeArgs(), 9071 /*stripKindOf=*/true)) 9072 return {}; 9073 } else if (LHS->isSpecialized() != RHS->isSpecialized()) { 9074 // If only one has type arguments, the result will not have type 9075 // arguments. 9076 LHSTypeArgs = {}; 9077 anyChanges = true; 9078 } 9079 9080 // Compute the intersection of protocols. 9081 SmallVector<ObjCProtocolDecl *, 8> Protocols; 9082 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr, 9083 Protocols); 9084 if (!Protocols.empty()) 9085 anyChanges = true; 9086 9087 // If anything in the LHS will have changed, build a new result type. 9088 // If we need to return a kindof type but LHS is not a kindof type, we 9089 // build a new result type. 9090 if (anyChanges || LHS->isKindOfType() != anyKindOf) { 9091 QualType Result = getObjCInterfaceType(LHS->getInterface()); 9092 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols, 9093 anyKindOf || LHS->isKindOfType()); 9094 return getObjCObjectPointerType(Result); 9095 } 9096 9097 return getObjCObjectPointerType(QualType(LHS, 0)); 9098 } 9099 9100 // Find the superclass. 9101 QualType LHSSuperType = LHS->getSuperClassType(); 9102 if (LHSSuperType.isNull()) 9103 break; 9104 9105 LHS = LHSSuperType->castAs<ObjCObjectType>(); 9106 } 9107 9108 // We didn't find anything by following the LHS to its root; now check 9109 // the RHS against the cached set of ancestors. 9110 while (true) { 9111 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl()); 9112 if (KnownLHS != LHSAncestors.end()) { 9113 LHS = KnownLHS->second; 9114 9115 // Get the type arguments. 9116 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten(); 9117 bool anyChanges = false; 9118 if (LHS->isSpecialized() && RHS->isSpecialized()) { 9119 // Both have type arguments, compare them. 9120 if (!sameObjCTypeArgs(*this, LHS->getInterface(), 9121 LHS->getTypeArgs(), RHS->getTypeArgs(), 9122 /*stripKindOf=*/true)) 9123 return {}; 9124 } else if (LHS->isSpecialized() != RHS->isSpecialized()) { 9125 // If only one has type arguments, the result will not have type 9126 // arguments. 9127 RHSTypeArgs = {}; 9128 anyChanges = true; 9129 } 9130 9131 // Compute the intersection of protocols. 9132 SmallVector<ObjCProtocolDecl *, 8> Protocols; 9133 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr, 9134 Protocols); 9135 if (!Protocols.empty()) 9136 anyChanges = true; 9137 9138 // If we need to return a kindof type but RHS is not a kindof type, we 9139 // build a new result type. 9140 if (anyChanges || RHS->isKindOfType() != anyKindOf) { 9141 QualType Result = getObjCInterfaceType(RHS->getInterface()); 9142 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols, 9143 anyKindOf || RHS->isKindOfType()); 9144 return getObjCObjectPointerType(Result); 9145 } 9146 9147 return getObjCObjectPointerType(QualType(RHS, 0)); 9148 } 9149 9150 // Find the superclass of the RHS. 9151 QualType RHSSuperType = RHS->getSuperClassType(); 9152 if (RHSSuperType.isNull()) 9153 break; 9154 9155 RHS = RHSSuperType->castAs<ObjCObjectType>(); 9156 } 9157 9158 return {}; 9159 } 9160 9161 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS, 9162 const ObjCObjectType *RHS) { 9163 assert(LHS->getInterface() && "LHS is not an interface type"); 9164 assert(RHS->getInterface() && "RHS is not an interface type"); 9165 9166 // Verify that the base decls are compatible: the RHS must be a subclass of 9167 // the LHS. 9168 ObjCInterfaceDecl *LHSInterface = LHS->getInterface(); 9169 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface()); 9170 if (!IsSuperClass) 9171 return false; 9172 9173 // If the LHS has protocol qualifiers, determine whether all of them are 9174 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the 9175 // LHS). 9176 if (LHS->getNumProtocols() > 0) { 9177 // OK if conversion of LHS to SuperClass results in narrowing of types 9178 // ; i.e., SuperClass may implement at least one of the protocols 9179 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok. 9180 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>. 9181 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols; 9182 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols); 9183 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's 9184 // qualifiers. 9185 for (auto *RHSPI : RHS->quals()) 9186 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols); 9187 // If there is no protocols associated with RHS, it is not a match. 9188 if (SuperClassInheritedProtocols.empty()) 9189 return false; 9190 9191 for (const auto *LHSProto : LHS->quals()) { 9192 bool SuperImplementsProtocol = false; 9193 for (auto *SuperClassProto : SuperClassInheritedProtocols) 9194 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) { 9195 SuperImplementsProtocol = true; 9196 break; 9197 } 9198 if (!SuperImplementsProtocol) 9199 return false; 9200 } 9201 } 9202 9203 // If the LHS is specialized, we may need to check type arguments. 9204 if (LHS->isSpecialized()) { 9205 // Follow the superclass chain until we've matched the LHS class in the 9206 // hierarchy. This substitutes type arguments through. 9207 const ObjCObjectType *RHSSuper = RHS; 9208 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface)) 9209 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>(); 9210 9211 // If the RHS is specializd, compare type arguments. 9212 if (RHSSuper->isSpecialized() && 9213 !sameObjCTypeArgs(*this, LHS->getInterface(), 9214 LHS->getTypeArgs(), RHSSuper->getTypeArgs(), 9215 /*stripKindOf=*/true)) { 9216 return false; 9217 } 9218 } 9219 9220 return true; 9221 } 9222 9223 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) { 9224 // get the "pointed to" types 9225 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>(); 9226 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>(); 9227 9228 if (!LHSOPT || !RHSOPT) 9229 return false; 9230 9231 return canAssignObjCInterfaces(LHSOPT, RHSOPT) || 9232 canAssignObjCInterfaces(RHSOPT, LHSOPT); 9233 } 9234 9235 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) { 9236 return canAssignObjCInterfaces( 9237 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(), 9238 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>()); 9239 } 9240 9241 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible, 9242 /// both shall have the identically qualified version of a compatible type. 9243 /// C99 6.2.7p1: Two types have compatible types if their types are the 9244 /// same. See 6.7.[2,3,5] for additional rules. 9245 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS, 9246 bool CompareUnqualified) { 9247 if (getLangOpts().CPlusPlus) 9248 return hasSameType(LHS, RHS); 9249 9250 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull(); 9251 } 9252 9253 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) { 9254 return typesAreCompatible(LHS, RHS); 9255 } 9256 9257 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) { 9258 return !mergeTypes(LHS, RHS, true).isNull(); 9259 } 9260 9261 /// mergeTransparentUnionType - if T is a transparent union type and a member 9262 /// of T is compatible with SubType, return the merged type, else return 9263 /// QualType() 9264 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType, 9265 bool OfBlockPointer, 9266 bool Unqualified) { 9267 if (const RecordType *UT = T->getAsUnionType()) { 9268 RecordDecl *UD = UT->getDecl(); 9269 if (UD->hasAttr<TransparentUnionAttr>()) { 9270 for (const auto *I : UD->fields()) { 9271 QualType ET = I->getType().getUnqualifiedType(); 9272 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified); 9273 if (!MT.isNull()) 9274 return MT; 9275 } 9276 } 9277 } 9278 9279 return {}; 9280 } 9281 9282 /// mergeFunctionParameterTypes - merge two types which appear as function 9283 /// parameter types 9284 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs, 9285 bool OfBlockPointer, 9286 bool Unqualified) { 9287 // GNU extension: two types are compatible if they appear as a function 9288 // argument, one of the types is a transparent union type and the other 9289 // type is compatible with a union member 9290 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer, 9291 Unqualified); 9292 if (!lmerge.isNull()) 9293 return lmerge; 9294 9295 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer, 9296 Unqualified); 9297 if (!rmerge.isNull()) 9298 return rmerge; 9299 9300 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified); 9301 } 9302 9303 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, 9304 bool OfBlockPointer, bool Unqualified, 9305 bool AllowCXX) { 9306 const auto *lbase = lhs->castAs<FunctionType>(); 9307 const auto *rbase = rhs->castAs<FunctionType>(); 9308 const auto *lproto = dyn_cast<FunctionProtoType>(lbase); 9309 const auto *rproto = dyn_cast<FunctionProtoType>(rbase); 9310 bool allLTypes = true; 9311 bool allRTypes = true; 9312 9313 // Check return type 9314 QualType retType; 9315 if (OfBlockPointer) { 9316 QualType RHS = rbase->getReturnType(); 9317 QualType LHS = lbase->getReturnType(); 9318 bool UnqualifiedResult = Unqualified; 9319 if (!UnqualifiedResult) 9320 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers()); 9321 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true); 9322 } 9323 else 9324 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false, 9325 Unqualified); 9326 if (retType.isNull()) 9327 return {}; 9328 9329 if (Unqualified) 9330 retType = retType.getUnqualifiedType(); 9331 9332 CanQualType LRetType = getCanonicalType(lbase->getReturnType()); 9333 CanQualType RRetType = getCanonicalType(rbase->getReturnType()); 9334 if (Unqualified) { 9335 LRetType = LRetType.getUnqualifiedType(); 9336 RRetType = RRetType.getUnqualifiedType(); 9337 } 9338 9339 if (getCanonicalType(retType) != LRetType) 9340 allLTypes = false; 9341 if (getCanonicalType(retType) != RRetType) 9342 allRTypes = false; 9343 9344 // FIXME: double check this 9345 // FIXME: should we error if lbase->getRegParmAttr() != 0 && 9346 // rbase->getRegParmAttr() != 0 && 9347 // lbase->getRegParmAttr() != rbase->getRegParmAttr()? 9348 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo(); 9349 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo(); 9350 9351 // Compatible functions must have compatible calling conventions 9352 if (lbaseInfo.getCC() != rbaseInfo.getCC()) 9353 return {}; 9354 9355 // Regparm is part of the calling convention. 9356 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm()) 9357 return {}; 9358 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm()) 9359 return {}; 9360 9361 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult()) 9362 return {}; 9363 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs()) 9364 return {}; 9365 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck()) 9366 return {}; 9367 9368 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'. 9369 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn(); 9370 9371 if (lbaseInfo.getNoReturn() != NoReturn) 9372 allLTypes = false; 9373 if (rbaseInfo.getNoReturn() != NoReturn) 9374 allRTypes = false; 9375 9376 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn); 9377 9378 if (lproto && rproto) { // two C99 style function prototypes 9379 assert((AllowCXX || 9380 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) && 9381 "C++ shouldn't be here"); 9382 // Compatible functions must have the same number of parameters 9383 if (lproto->getNumParams() != rproto->getNumParams()) 9384 return {}; 9385 9386 // Variadic and non-variadic functions aren't compatible 9387 if (lproto->isVariadic() != rproto->isVariadic()) 9388 return {}; 9389 9390 if (lproto->getMethodQuals() != rproto->getMethodQuals()) 9391 return {}; 9392 9393 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos; 9394 bool canUseLeft, canUseRight; 9395 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight, 9396 newParamInfos)) 9397 return {}; 9398 9399 if (!canUseLeft) 9400 allLTypes = false; 9401 if (!canUseRight) 9402 allRTypes = false; 9403 9404 // Check parameter type compatibility 9405 SmallVector<QualType, 10> types; 9406 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) { 9407 QualType lParamType = lproto->getParamType(i).getUnqualifiedType(); 9408 QualType rParamType = rproto->getParamType(i).getUnqualifiedType(); 9409 QualType paramType = mergeFunctionParameterTypes( 9410 lParamType, rParamType, OfBlockPointer, Unqualified); 9411 if (paramType.isNull()) 9412 return {}; 9413 9414 if (Unqualified) 9415 paramType = paramType.getUnqualifiedType(); 9416 9417 types.push_back(paramType); 9418 if (Unqualified) { 9419 lParamType = lParamType.getUnqualifiedType(); 9420 rParamType = rParamType.getUnqualifiedType(); 9421 } 9422 9423 if (getCanonicalType(paramType) != getCanonicalType(lParamType)) 9424 allLTypes = false; 9425 if (getCanonicalType(paramType) != getCanonicalType(rParamType)) 9426 allRTypes = false; 9427 } 9428 9429 if (allLTypes) return lhs; 9430 if (allRTypes) return rhs; 9431 9432 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo(); 9433 EPI.ExtInfo = einfo; 9434 EPI.ExtParameterInfos = 9435 newParamInfos.empty() ? nullptr : newParamInfos.data(); 9436 return getFunctionType(retType, types, EPI); 9437 } 9438 9439 if (lproto) allRTypes = false; 9440 if (rproto) allLTypes = false; 9441 9442 const FunctionProtoType *proto = lproto ? lproto : rproto; 9443 if (proto) { 9444 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here"); 9445 if (proto->isVariadic()) 9446 return {}; 9447 // Check that the types are compatible with the types that 9448 // would result from default argument promotions (C99 6.7.5.3p15). 9449 // The only types actually affected are promotable integer 9450 // types and floats, which would be passed as a different 9451 // type depending on whether the prototype is visible. 9452 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) { 9453 QualType paramTy = proto->getParamType(i); 9454 9455 // Look at the converted type of enum types, since that is the type used 9456 // to pass enum values. 9457 if (const auto *Enum = paramTy->getAs<EnumType>()) { 9458 paramTy = Enum->getDecl()->getIntegerType(); 9459 if (paramTy.isNull()) 9460 return {}; 9461 } 9462 9463 if (paramTy->isPromotableIntegerType() || 9464 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy) 9465 return {}; 9466 } 9467 9468 if (allLTypes) return lhs; 9469 if (allRTypes) return rhs; 9470 9471 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo(); 9472 EPI.ExtInfo = einfo; 9473 return getFunctionType(retType, proto->getParamTypes(), EPI); 9474 } 9475 9476 if (allLTypes) return lhs; 9477 if (allRTypes) return rhs; 9478 return getFunctionNoProtoType(retType, einfo); 9479 } 9480 9481 /// Given that we have an enum type and a non-enum type, try to merge them. 9482 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET, 9483 QualType other, bool isBlockReturnType) { 9484 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char, 9485 // a signed integer type, or an unsigned integer type. 9486 // Compatibility is based on the underlying type, not the promotion 9487 // type. 9488 QualType underlyingType = ET->getDecl()->getIntegerType(); 9489 if (underlyingType.isNull()) 9490 return {}; 9491 if (Context.hasSameType(underlyingType, other)) 9492 return other; 9493 9494 // In block return types, we're more permissive and accept any 9495 // integral type of the same size. 9496 if (isBlockReturnType && other->isIntegerType() && 9497 Context.getTypeSize(underlyingType) == Context.getTypeSize(other)) 9498 return other; 9499 9500 return {}; 9501 } 9502 9503 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, 9504 bool OfBlockPointer, 9505 bool Unqualified, bool BlockReturnType) { 9506 // C++ [expr]: If an expression initially has the type "reference to T", the 9507 // type is adjusted to "T" prior to any further analysis, the expression 9508 // designates the object or function denoted by the reference, and the 9509 // expression is an lvalue unless the reference is an rvalue reference and 9510 // the expression is a function call (possibly inside parentheses). 9511 if (LHS->getAs<ReferenceType>() || RHS->getAs<ReferenceType>()) 9512 return {}; 9513 9514 if (Unqualified) { 9515 LHS = LHS.getUnqualifiedType(); 9516 RHS = RHS.getUnqualifiedType(); 9517 } 9518 9519 QualType LHSCan = getCanonicalType(LHS), 9520 RHSCan = getCanonicalType(RHS); 9521 9522 // If two types are identical, they are compatible. 9523 if (LHSCan == RHSCan) 9524 return LHS; 9525 9526 // If the qualifiers are different, the types aren't compatible... mostly. 9527 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 9528 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 9529 if (LQuals != RQuals) { 9530 // If any of these qualifiers are different, we have a type 9531 // mismatch. 9532 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 9533 LQuals.getAddressSpace() != RQuals.getAddressSpace() || 9534 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() || 9535 LQuals.hasUnaligned() != RQuals.hasUnaligned()) 9536 return {}; 9537 9538 // Exactly one GC qualifier difference is allowed: __strong is 9539 // okay if the other type has no GC qualifier but is an Objective 9540 // C object pointer (i.e. implicitly strong by default). We fix 9541 // this by pretending that the unqualified type was actually 9542 // qualified __strong. 9543 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 9544 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 9545 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 9546 9547 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 9548 return {}; 9549 9550 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) { 9551 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong)); 9552 } 9553 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) { 9554 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS); 9555 } 9556 return {}; 9557 } 9558 9559 // Okay, qualifiers are equal. 9560 9561 Type::TypeClass LHSClass = LHSCan->getTypeClass(); 9562 Type::TypeClass RHSClass = RHSCan->getTypeClass(); 9563 9564 // We want to consider the two function types to be the same for these 9565 // comparisons, just force one to the other. 9566 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto; 9567 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto; 9568 9569 // Same as above for arrays 9570 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray) 9571 LHSClass = Type::ConstantArray; 9572 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray) 9573 RHSClass = Type::ConstantArray; 9574 9575 // ObjCInterfaces are just specialized ObjCObjects. 9576 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject; 9577 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject; 9578 9579 // Canonicalize ExtVector -> Vector. 9580 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector; 9581 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector; 9582 9583 // If the canonical type classes don't match. 9584 if (LHSClass != RHSClass) { 9585 // Note that we only have special rules for turning block enum 9586 // returns into block int returns, not vice-versa. 9587 if (const auto *ETy = LHS->getAs<EnumType>()) { 9588 return mergeEnumWithInteger(*this, ETy, RHS, false); 9589 } 9590 if (const EnumType* ETy = RHS->getAs<EnumType>()) { 9591 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType); 9592 } 9593 // allow block pointer type to match an 'id' type. 9594 if (OfBlockPointer && !BlockReturnType) { 9595 if (LHS->isObjCIdType() && RHS->isBlockPointerType()) 9596 return LHS; 9597 if (RHS->isObjCIdType() && LHS->isBlockPointerType()) 9598 return RHS; 9599 } 9600 9601 return {}; 9602 } 9603 9604 // The canonical type classes match. 9605 switch (LHSClass) { 9606 #define TYPE(Class, Base) 9607 #define ABSTRACT_TYPE(Class, Base) 9608 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 9609 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 9610 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 9611 #include "clang/AST/TypeNodes.inc" 9612 llvm_unreachable("Non-canonical and dependent types shouldn't get here"); 9613 9614 case Type::Auto: 9615 case Type::DeducedTemplateSpecialization: 9616 case Type::LValueReference: 9617 case Type::RValueReference: 9618 case Type::MemberPointer: 9619 llvm_unreachable("C++ should never be in mergeTypes"); 9620 9621 case Type::ObjCInterface: 9622 case Type::IncompleteArray: 9623 case Type::VariableArray: 9624 case Type::FunctionProto: 9625 case Type::ExtVector: 9626 llvm_unreachable("Types are eliminated above"); 9627 9628 case Type::Pointer: 9629 { 9630 // Merge two pointer types, while trying to preserve typedef info 9631 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType(); 9632 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType(); 9633 if (Unqualified) { 9634 LHSPointee = LHSPointee.getUnqualifiedType(); 9635 RHSPointee = RHSPointee.getUnqualifiedType(); 9636 } 9637 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false, 9638 Unqualified); 9639 if (ResultType.isNull()) 9640 return {}; 9641 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 9642 return LHS; 9643 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 9644 return RHS; 9645 return getPointerType(ResultType); 9646 } 9647 case Type::BlockPointer: 9648 { 9649 // Merge two block pointer types, while trying to preserve typedef info 9650 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType(); 9651 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType(); 9652 if (Unqualified) { 9653 LHSPointee = LHSPointee.getUnqualifiedType(); 9654 RHSPointee = RHSPointee.getUnqualifiedType(); 9655 } 9656 if (getLangOpts().OpenCL) { 9657 Qualifiers LHSPteeQual = LHSPointee.getQualifiers(); 9658 Qualifiers RHSPteeQual = RHSPointee.getQualifiers(); 9659 // Blocks can't be an expression in a ternary operator (OpenCL v2.0 9660 // 6.12.5) thus the following check is asymmetric. 9661 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual)) 9662 return {}; 9663 LHSPteeQual.removeAddressSpace(); 9664 RHSPteeQual.removeAddressSpace(); 9665 LHSPointee = 9666 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue()); 9667 RHSPointee = 9668 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue()); 9669 } 9670 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer, 9671 Unqualified); 9672 if (ResultType.isNull()) 9673 return {}; 9674 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 9675 return LHS; 9676 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 9677 return RHS; 9678 return getBlockPointerType(ResultType); 9679 } 9680 case Type::Atomic: 9681 { 9682 // Merge two pointer types, while trying to preserve typedef info 9683 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType(); 9684 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType(); 9685 if (Unqualified) { 9686 LHSValue = LHSValue.getUnqualifiedType(); 9687 RHSValue = RHSValue.getUnqualifiedType(); 9688 } 9689 QualType ResultType = mergeTypes(LHSValue, RHSValue, false, 9690 Unqualified); 9691 if (ResultType.isNull()) 9692 return {}; 9693 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType)) 9694 return LHS; 9695 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType)) 9696 return RHS; 9697 return getAtomicType(ResultType); 9698 } 9699 case Type::ConstantArray: 9700 { 9701 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS); 9702 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS); 9703 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize()) 9704 return {}; 9705 9706 QualType LHSElem = getAsArrayType(LHS)->getElementType(); 9707 QualType RHSElem = getAsArrayType(RHS)->getElementType(); 9708 if (Unqualified) { 9709 LHSElem = LHSElem.getUnqualifiedType(); 9710 RHSElem = RHSElem.getUnqualifiedType(); 9711 } 9712 9713 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified); 9714 if (ResultType.isNull()) 9715 return {}; 9716 9717 const VariableArrayType* LVAT = getAsVariableArrayType(LHS); 9718 const VariableArrayType* RVAT = getAsVariableArrayType(RHS); 9719 9720 // If either side is a variable array, and both are complete, check whether 9721 // the current dimension is definite. 9722 if (LVAT || RVAT) { 9723 auto SizeFetch = [this](const VariableArrayType* VAT, 9724 const ConstantArrayType* CAT) 9725 -> std::pair<bool,llvm::APInt> { 9726 if (VAT) { 9727 Optional<llvm::APSInt> TheInt; 9728 Expr *E = VAT->getSizeExpr(); 9729 if (E && (TheInt = E->getIntegerConstantExpr(*this))) 9730 return std::make_pair(true, *TheInt); 9731 return std::make_pair(false, llvm::APSInt()); 9732 } 9733 if (CAT) 9734 return std::make_pair(true, CAT->getSize()); 9735 return std::make_pair(false, llvm::APInt()); 9736 }; 9737 9738 bool HaveLSize, HaveRSize; 9739 llvm::APInt LSize, RSize; 9740 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT); 9741 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT); 9742 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize)) 9743 return {}; // Definite, but unequal, array dimension 9744 } 9745 9746 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 9747 return LHS; 9748 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 9749 return RHS; 9750 if (LCAT) 9751 return getConstantArrayType(ResultType, LCAT->getSize(), 9752 LCAT->getSizeExpr(), 9753 ArrayType::ArraySizeModifier(), 0); 9754 if (RCAT) 9755 return getConstantArrayType(ResultType, RCAT->getSize(), 9756 RCAT->getSizeExpr(), 9757 ArrayType::ArraySizeModifier(), 0); 9758 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 9759 return LHS; 9760 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 9761 return RHS; 9762 if (LVAT) { 9763 // FIXME: This isn't correct! But tricky to implement because 9764 // the array's size has to be the size of LHS, but the type 9765 // has to be different. 9766 return LHS; 9767 } 9768 if (RVAT) { 9769 // FIXME: This isn't correct! But tricky to implement because 9770 // the array's size has to be the size of RHS, but the type 9771 // has to be different. 9772 return RHS; 9773 } 9774 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS; 9775 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS; 9776 return getIncompleteArrayType(ResultType, 9777 ArrayType::ArraySizeModifier(), 0); 9778 } 9779 case Type::FunctionNoProto: 9780 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified); 9781 case Type::Record: 9782 case Type::Enum: 9783 return {}; 9784 case Type::Builtin: 9785 // Only exactly equal builtin types are compatible, which is tested above. 9786 return {}; 9787 case Type::Complex: 9788 // Distinct complex types are incompatible. 9789 return {}; 9790 case Type::Vector: 9791 // FIXME: The merged type should be an ExtVector! 9792 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(), 9793 RHSCan->castAs<VectorType>())) 9794 return LHS; 9795 return {}; 9796 case Type::ConstantMatrix: 9797 if (areCompatMatrixTypes(LHSCan->castAs<ConstantMatrixType>(), 9798 RHSCan->castAs<ConstantMatrixType>())) 9799 return LHS; 9800 return {}; 9801 case Type::ObjCObject: { 9802 // Check if the types are assignment compatible. 9803 // FIXME: This should be type compatibility, e.g. whether 9804 // "LHS x; RHS x;" at global scope is legal. 9805 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectType>(), 9806 RHS->castAs<ObjCObjectType>())) 9807 return LHS; 9808 return {}; 9809 } 9810 case Type::ObjCObjectPointer: 9811 if (OfBlockPointer) { 9812 if (canAssignObjCInterfacesInBlockPointer( 9813 LHS->castAs<ObjCObjectPointerType>(), 9814 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType)) 9815 return LHS; 9816 return {}; 9817 } 9818 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectPointerType>(), 9819 RHS->castAs<ObjCObjectPointerType>())) 9820 return LHS; 9821 return {}; 9822 case Type::Pipe: 9823 assert(LHS != RHS && 9824 "Equivalent pipe types should have already been handled!"); 9825 return {}; 9826 case Type::ExtInt: { 9827 // Merge two ext-int types, while trying to preserve typedef info. 9828 bool LHSUnsigned = LHS->castAs<ExtIntType>()->isUnsigned(); 9829 bool RHSUnsigned = RHS->castAs<ExtIntType>()->isUnsigned(); 9830 unsigned LHSBits = LHS->castAs<ExtIntType>()->getNumBits(); 9831 unsigned RHSBits = RHS->castAs<ExtIntType>()->getNumBits(); 9832 9833 // Like unsigned/int, shouldn't have a type if they dont match. 9834 if (LHSUnsigned != RHSUnsigned) 9835 return {}; 9836 9837 if (LHSBits != RHSBits) 9838 return {}; 9839 return LHS; 9840 } 9841 } 9842 9843 llvm_unreachable("Invalid Type::Class!"); 9844 } 9845 9846 bool ASTContext::mergeExtParameterInfo( 9847 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType, 9848 bool &CanUseFirst, bool &CanUseSecond, 9849 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) { 9850 assert(NewParamInfos.empty() && "param info list not empty"); 9851 CanUseFirst = CanUseSecond = true; 9852 bool FirstHasInfo = FirstFnType->hasExtParameterInfos(); 9853 bool SecondHasInfo = SecondFnType->hasExtParameterInfos(); 9854 9855 // Fast path: if the first type doesn't have ext parameter infos, 9856 // we match if and only if the second type also doesn't have them. 9857 if (!FirstHasInfo && !SecondHasInfo) 9858 return true; 9859 9860 bool NeedParamInfo = false; 9861 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size() 9862 : SecondFnType->getExtParameterInfos().size(); 9863 9864 for (size_t I = 0; I < E; ++I) { 9865 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam; 9866 if (FirstHasInfo) 9867 FirstParam = FirstFnType->getExtParameterInfo(I); 9868 if (SecondHasInfo) 9869 SecondParam = SecondFnType->getExtParameterInfo(I); 9870 9871 // Cannot merge unless everything except the noescape flag matches. 9872 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false)) 9873 return false; 9874 9875 bool FirstNoEscape = FirstParam.isNoEscape(); 9876 bool SecondNoEscape = SecondParam.isNoEscape(); 9877 bool IsNoEscape = FirstNoEscape && SecondNoEscape; 9878 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape)); 9879 if (NewParamInfos.back().getOpaqueValue()) 9880 NeedParamInfo = true; 9881 if (FirstNoEscape != IsNoEscape) 9882 CanUseFirst = false; 9883 if (SecondNoEscape != IsNoEscape) 9884 CanUseSecond = false; 9885 } 9886 9887 if (!NeedParamInfo) 9888 NewParamInfos.clear(); 9889 9890 return true; 9891 } 9892 9893 void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) { 9894 ObjCLayouts[CD] = nullptr; 9895 } 9896 9897 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 9898 /// 'RHS' attributes and returns the merged version; including for function 9899 /// return types. 9900 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) { 9901 QualType LHSCan = getCanonicalType(LHS), 9902 RHSCan = getCanonicalType(RHS); 9903 // If two types are identical, they are compatible. 9904 if (LHSCan == RHSCan) 9905 return LHS; 9906 if (RHSCan->isFunctionType()) { 9907 if (!LHSCan->isFunctionType()) 9908 return {}; 9909 QualType OldReturnType = 9910 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType(); 9911 QualType NewReturnType = 9912 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType(); 9913 QualType ResReturnType = 9914 mergeObjCGCQualifiers(NewReturnType, OldReturnType); 9915 if (ResReturnType.isNull()) 9916 return {}; 9917 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) { 9918 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo(); 9919 // In either case, use OldReturnType to build the new function type. 9920 const auto *F = LHS->castAs<FunctionType>(); 9921 if (const auto *FPT = cast<FunctionProtoType>(F)) { 9922 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9923 EPI.ExtInfo = getFunctionExtInfo(LHS); 9924 QualType ResultType = 9925 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI); 9926 return ResultType; 9927 } 9928 } 9929 return {}; 9930 } 9931 9932 // If the qualifiers are different, the types can still be merged. 9933 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 9934 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 9935 if (LQuals != RQuals) { 9936 // If any of these qualifiers are different, we have a type mismatch. 9937 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 9938 LQuals.getAddressSpace() != RQuals.getAddressSpace()) 9939 return {}; 9940 9941 // Exactly one GC qualifier difference is allowed: __strong is 9942 // okay if the other type has no GC qualifier but is an Objective 9943 // C object pointer (i.e. implicitly strong by default). We fix 9944 // this by pretending that the unqualified type was actually 9945 // qualified __strong. 9946 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 9947 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 9948 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 9949 9950 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 9951 return {}; 9952 9953 if (GC_L == Qualifiers::Strong) 9954 return LHS; 9955 if (GC_R == Qualifiers::Strong) 9956 return RHS; 9957 return {}; 9958 } 9959 9960 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) { 9961 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType(); 9962 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType(); 9963 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT); 9964 if (ResQT == LHSBaseQT) 9965 return LHS; 9966 if (ResQT == RHSBaseQT) 9967 return RHS; 9968 } 9969 return {}; 9970 } 9971 9972 //===----------------------------------------------------------------------===// 9973 // Integer Predicates 9974 //===----------------------------------------------------------------------===// 9975 9976 unsigned ASTContext::getIntWidth(QualType T) const { 9977 if (const auto *ET = T->getAs<EnumType>()) 9978 T = ET->getDecl()->getIntegerType(); 9979 if (T->isBooleanType()) 9980 return 1; 9981 if(const auto *EIT = T->getAs<ExtIntType>()) 9982 return EIT->getNumBits(); 9983 // For builtin types, just use the standard type sizing method 9984 return (unsigned)getTypeSize(T); 9985 } 9986 9987 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const { 9988 assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) && 9989 "Unexpected type"); 9990 9991 // Turn <4 x signed int> -> <4 x unsigned int> 9992 if (const auto *VTy = T->getAs<VectorType>()) 9993 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()), 9994 VTy->getNumElements(), VTy->getVectorKind()); 9995 9996 // For enums, we return the unsigned version of the base type. 9997 if (const auto *ETy = T->getAs<EnumType>()) 9998 T = ETy->getDecl()->getIntegerType(); 9999 10000 switch (T->castAs<BuiltinType>()->getKind()) { 10001 case BuiltinType::Char_S: 10002 case BuiltinType::SChar: 10003 return UnsignedCharTy; 10004 case BuiltinType::Short: 10005 return UnsignedShortTy; 10006 case BuiltinType::Int: 10007 return UnsignedIntTy; 10008 case BuiltinType::Long: 10009 return UnsignedLongTy; 10010 case BuiltinType::LongLong: 10011 return UnsignedLongLongTy; 10012 case BuiltinType::Int128: 10013 return UnsignedInt128Ty; 10014 // wchar_t is special. It is either signed or not, but when it's signed, 10015 // there's no matching "unsigned wchar_t". Therefore we return the unsigned 10016 // version of it's underlying type instead. 10017 case BuiltinType::WChar_S: 10018 return getUnsignedWCharType(); 10019 10020 case BuiltinType::ShortAccum: 10021 return UnsignedShortAccumTy; 10022 case BuiltinType::Accum: 10023 return UnsignedAccumTy; 10024 case BuiltinType::LongAccum: 10025 return UnsignedLongAccumTy; 10026 case BuiltinType::SatShortAccum: 10027 return SatUnsignedShortAccumTy; 10028 case BuiltinType::SatAccum: 10029 return SatUnsignedAccumTy; 10030 case BuiltinType::SatLongAccum: 10031 return SatUnsignedLongAccumTy; 10032 case BuiltinType::ShortFract: 10033 return UnsignedShortFractTy; 10034 case BuiltinType::Fract: 10035 return UnsignedFractTy; 10036 case BuiltinType::LongFract: 10037 return UnsignedLongFractTy; 10038 case BuiltinType::SatShortFract: 10039 return SatUnsignedShortFractTy; 10040 case BuiltinType::SatFract: 10041 return SatUnsignedFractTy; 10042 case BuiltinType::SatLongFract: 10043 return SatUnsignedLongFractTy; 10044 default: 10045 llvm_unreachable("Unexpected signed integer or fixed point type"); 10046 } 10047 } 10048 10049 ASTMutationListener::~ASTMutationListener() = default; 10050 10051 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD, 10052 QualType ReturnType) {} 10053 10054 //===----------------------------------------------------------------------===// 10055 // Builtin Type Computation 10056 //===----------------------------------------------------------------------===// 10057 10058 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the 10059 /// pointer over the consumed characters. This returns the resultant type. If 10060 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic 10061 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of 10062 /// a vector of "i*". 10063 /// 10064 /// RequiresICE is filled in on return to indicate whether the value is required 10065 /// to be an Integer Constant Expression. 10066 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, 10067 ASTContext::GetBuiltinTypeError &Error, 10068 bool &RequiresICE, 10069 bool AllowTypeModifiers) { 10070 // Modifiers. 10071 int HowLong = 0; 10072 bool Signed = false, Unsigned = false; 10073 RequiresICE = false; 10074 10075 // Read the prefixed modifiers first. 10076 bool Done = false; 10077 #ifndef NDEBUG 10078 bool IsSpecial = false; 10079 #endif 10080 while (!Done) { 10081 switch (*Str++) { 10082 default: Done = true; --Str; break; 10083 case 'I': 10084 RequiresICE = true; 10085 break; 10086 case 'S': 10087 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!"); 10088 assert(!Signed && "Can't use 'S' modifier multiple times!"); 10089 Signed = true; 10090 break; 10091 case 'U': 10092 assert(!Signed && "Can't use both 'S' and 'U' modifiers!"); 10093 assert(!Unsigned && "Can't use 'U' modifier multiple times!"); 10094 Unsigned = true; 10095 break; 10096 case 'L': 10097 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers"); 10098 assert(HowLong <= 2 && "Can't have LLLL modifier"); 10099 ++HowLong; 10100 break; 10101 case 'N': 10102 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise. 10103 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10104 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!"); 10105 #ifndef NDEBUG 10106 IsSpecial = true; 10107 #endif 10108 if (Context.getTargetInfo().getLongWidth() == 32) 10109 ++HowLong; 10110 break; 10111 case 'W': 10112 // This modifier represents int64 type. 10113 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10114 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!"); 10115 #ifndef NDEBUG 10116 IsSpecial = true; 10117 #endif 10118 switch (Context.getTargetInfo().getInt64Type()) { 10119 default: 10120 llvm_unreachable("Unexpected integer type"); 10121 case TargetInfo::SignedLong: 10122 HowLong = 1; 10123 break; 10124 case TargetInfo::SignedLongLong: 10125 HowLong = 2; 10126 break; 10127 } 10128 break; 10129 case 'Z': 10130 // This modifier represents int32 type. 10131 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10132 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!"); 10133 #ifndef NDEBUG 10134 IsSpecial = true; 10135 #endif 10136 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) { 10137 default: 10138 llvm_unreachable("Unexpected integer type"); 10139 case TargetInfo::SignedInt: 10140 HowLong = 0; 10141 break; 10142 case TargetInfo::SignedLong: 10143 HowLong = 1; 10144 break; 10145 case TargetInfo::SignedLongLong: 10146 HowLong = 2; 10147 break; 10148 } 10149 break; 10150 case 'O': 10151 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10152 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!"); 10153 #ifndef NDEBUG 10154 IsSpecial = true; 10155 #endif 10156 if (Context.getLangOpts().OpenCL) 10157 HowLong = 1; 10158 else 10159 HowLong = 2; 10160 break; 10161 } 10162 } 10163 10164 QualType Type; 10165 10166 // Read the base type. 10167 switch (*Str++) { 10168 default: llvm_unreachable("Unknown builtin type letter!"); 10169 case 'y': 10170 assert(HowLong == 0 && !Signed && !Unsigned && 10171 "Bad modifiers used with 'y'!"); 10172 Type = Context.BFloat16Ty; 10173 break; 10174 case 'v': 10175 assert(HowLong == 0 && !Signed && !Unsigned && 10176 "Bad modifiers used with 'v'!"); 10177 Type = Context.VoidTy; 10178 break; 10179 case 'h': 10180 assert(HowLong == 0 && !Signed && !Unsigned && 10181 "Bad modifiers used with 'h'!"); 10182 Type = Context.HalfTy; 10183 break; 10184 case 'f': 10185 assert(HowLong == 0 && !Signed && !Unsigned && 10186 "Bad modifiers used with 'f'!"); 10187 Type = Context.FloatTy; 10188 break; 10189 case 'd': 10190 assert(HowLong < 3 && !Signed && !Unsigned && 10191 "Bad modifiers used with 'd'!"); 10192 if (HowLong == 1) 10193 Type = Context.LongDoubleTy; 10194 else if (HowLong == 2) 10195 Type = Context.Float128Ty; 10196 else 10197 Type = Context.DoubleTy; 10198 break; 10199 case 's': 10200 assert(HowLong == 0 && "Bad modifiers used with 's'!"); 10201 if (Unsigned) 10202 Type = Context.UnsignedShortTy; 10203 else 10204 Type = Context.ShortTy; 10205 break; 10206 case 'i': 10207 if (HowLong == 3) 10208 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty; 10209 else if (HowLong == 2) 10210 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy; 10211 else if (HowLong == 1) 10212 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy; 10213 else 10214 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy; 10215 break; 10216 case 'c': 10217 assert(HowLong == 0 && "Bad modifiers used with 'c'!"); 10218 if (Signed) 10219 Type = Context.SignedCharTy; 10220 else if (Unsigned) 10221 Type = Context.UnsignedCharTy; 10222 else 10223 Type = Context.CharTy; 10224 break; 10225 case 'b': // boolean 10226 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!"); 10227 Type = Context.BoolTy; 10228 break; 10229 case 'z': // size_t. 10230 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!"); 10231 Type = Context.getSizeType(); 10232 break; 10233 case 'w': // wchar_t. 10234 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!"); 10235 Type = Context.getWideCharType(); 10236 break; 10237 case 'F': 10238 Type = Context.getCFConstantStringType(); 10239 break; 10240 case 'G': 10241 Type = Context.getObjCIdType(); 10242 break; 10243 case 'H': 10244 Type = Context.getObjCSelType(); 10245 break; 10246 case 'M': 10247 Type = Context.getObjCSuperType(); 10248 break; 10249 case 'a': 10250 Type = Context.getBuiltinVaListType(); 10251 assert(!Type.isNull() && "builtin va list type not initialized!"); 10252 break; 10253 case 'A': 10254 // This is a "reference" to a va_list; however, what exactly 10255 // this means depends on how va_list is defined. There are two 10256 // different kinds of va_list: ones passed by value, and ones 10257 // passed by reference. An example of a by-value va_list is 10258 // x86, where va_list is a char*. An example of by-ref va_list 10259 // is x86-64, where va_list is a __va_list_tag[1]. For x86, 10260 // we want this argument to be a char*&; for x86-64, we want 10261 // it to be a __va_list_tag*. 10262 Type = Context.getBuiltinVaListType(); 10263 assert(!Type.isNull() && "builtin va list type not initialized!"); 10264 if (Type->isArrayType()) 10265 Type = Context.getArrayDecayedType(Type); 10266 else 10267 Type = Context.getLValueReferenceType(Type); 10268 break; 10269 case 'q': { 10270 char *End; 10271 unsigned NumElements = strtoul(Str, &End, 10); 10272 assert(End != Str && "Missing vector size"); 10273 Str = End; 10274 10275 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 10276 RequiresICE, false); 10277 assert(!RequiresICE && "Can't require vector ICE"); 10278 10279 Type = Context.getScalableVectorType(ElementType, NumElements); 10280 break; 10281 } 10282 case 'V': { 10283 char *End; 10284 unsigned NumElements = strtoul(Str, &End, 10); 10285 assert(End != Str && "Missing vector size"); 10286 Str = End; 10287 10288 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 10289 RequiresICE, false); 10290 assert(!RequiresICE && "Can't require vector ICE"); 10291 10292 // TODO: No way to make AltiVec vectors in builtins yet. 10293 Type = Context.getVectorType(ElementType, NumElements, 10294 VectorType::GenericVector); 10295 break; 10296 } 10297 case 'E': { 10298 char *End; 10299 10300 unsigned NumElements = strtoul(Str, &End, 10); 10301 assert(End != Str && "Missing vector size"); 10302 10303 Str = End; 10304 10305 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 10306 false); 10307 Type = Context.getExtVectorType(ElementType, NumElements); 10308 break; 10309 } 10310 case 'X': { 10311 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 10312 false); 10313 assert(!RequiresICE && "Can't require complex ICE"); 10314 Type = Context.getComplexType(ElementType); 10315 break; 10316 } 10317 case 'Y': 10318 Type = Context.getPointerDiffType(); 10319 break; 10320 case 'P': 10321 Type = Context.getFILEType(); 10322 if (Type.isNull()) { 10323 Error = ASTContext::GE_Missing_stdio; 10324 return {}; 10325 } 10326 break; 10327 case 'J': 10328 if (Signed) 10329 Type = Context.getsigjmp_bufType(); 10330 else 10331 Type = Context.getjmp_bufType(); 10332 10333 if (Type.isNull()) { 10334 Error = ASTContext::GE_Missing_setjmp; 10335 return {}; 10336 } 10337 break; 10338 case 'K': 10339 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!"); 10340 Type = Context.getucontext_tType(); 10341 10342 if (Type.isNull()) { 10343 Error = ASTContext::GE_Missing_ucontext; 10344 return {}; 10345 } 10346 break; 10347 case 'p': 10348 Type = Context.getProcessIDType(); 10349 break; 10350 } 10351 10352 // If there are modifiers and if we're allowed to parse them, go for it. 10353 Done = !AllowTypeModifiers; 10354 while (!Done) { 10355 switch (char c = *Str++) { 10356 default: Done = true; --Str; break; 10357 case '*': 10358 case '&': { 10359 // Both pointers and references can have their pointee types 10360 // qualified with an address space. 10361 char *End; 10362 unsigned AddrSpace = strtoul(Str, &End, 10); 10363 if (End != Str) { 10364 // Note AddrSpace == 0 is not the same as an unspecified address space. 10365 Type = Context.getAddrSpaceQualType( 10366 Type, 10367 Context.getLangASForBuiltinAddressSpace(AddrSpace)); 10368 Str = End; 10369 } 10370 if (c == '*') 10371 Type = Context.getPointerType(Type); 10372 else 10373 Type = Context.getLValueReferenceType(Type); 10374 break; 10375 } 10376 // FIXME: There's no way to have a built-in with an rvalue ref arg. 10377 case 'C': 10378 Type = Type.withConst(); 10379 break; 10380 case 'D': 10381 Type = Context.getVolatileType(Type); 10382 break; 10383 case 'R': 10384 Type = Type.withRestrict(); 10385 break; 10386 } 10387 } 10388 10389 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) && 10390 "Integer constant 'I' type must be an integer"); 10391 10392 return Type; 10393 } 10394 10395 // On some targets such as PowerPC, some of the builtins are defined with custom 10396 // type decriptors for target-dependent types. These descriptors are decoded in 10397 // other functions, but it may be useful to be able to fall back to default 10398 // descriptor decoding to define builtins mixing target-dependent and target- 10399 // independent types. This function allows decoding one type descriptor with 10400 // default decoding. 10401 QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context, 10402 GetBuiltinTypeError &Error, bool &RequireICE, 10403 bool AllowTypeModifiers) const { 10404 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers); 10405 } 10406 10407 /// GetBuiltinType - Return the type for the specified builtin. 10408 QualType ASTContext::GetBuiltinType(unsigned Id, 10409 GetBuiltinTypeError &Error, 10410 unsigned *IntegerConstantArgs) const { 10411 const char *TypeStr = BuiltinInfo.getTypeString(Id); 10412 if (TypeStr[0] == '\0') { 10413 Error = GE_Missing_type; 10414 return {}; 10415 } 10416 10417 SmallVector<QualType, 8> ArgTypes; 10418 10419 bool RequiresICE = false; 10420 Error = GE_None; 10421 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error, 10422 RequiresICE, true); 10423 if (Error != GE_None) 10424 return {}; 10425 10426 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE"); 10427 10428 while (TypeStr[0] && TypeStr[0] != '.') { 10429 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true); 10430 if (Error != GE_None) 10431 return {}; 10432 10433 // If this argument is required to be an IntegerConstantExpression and the 10434 // caller cares, fill in the bitmask we return. 10435 if (RequiresICE && IntegerConstantArgs) 10436 *IntegerConstantArgs |= 1 << ArgTypes.size(); 10437 10438 // Do array -> pointer decay. The builtin should use the decayed type. 10439 if (Ty->isArrayType()) 10440 Ty = getArrayDecayedType(Ty); 10441 10442 ArgTypes.push_back(Ty); 10443 } 10444 10445 if (Id == Builtin::BI__GetExceptionInfo) 10446 return {}; 10447 10448 assert((TypeStr[0] != '.' || TypeStr[1] == 0) && 10449 "'.' should only occur at end of builtin type list!"); 10450 10451 bool Variadic = (TypeStr[0] == '.'); 10452 10453 FunctionType::ExtInfo EI(getDefaultCallingConvention( 10454 Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true)); 10455 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true); 10456 10457 10458 // We really shouldn't be making a no-proto type here. 10459 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus) 10460 return getFunctionNoProtoType(ResType, EI); 10461 10462 FunctionProtoType::ExtProtoInfo EPI; 10463 EPI.ExtInfo = EI; 10464 EPI.Variadic = Variadic; 10465 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id)) 10466 EPI.ExceptionSpec.Type = 10467 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone; 10468 10469 return getFunctionType(ResType, ArgTypes, EPI); 10470 } 10471 10472 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, 10473 const FunctionDecl *FD) { 10474 if (!FD->isExternallyVisible()) 10475 return GVA_Internal; 10476 10477 // Non-user-provided functions get emitted as weak definitions with every 10478 // use, no matter whether they've been explicitly instantiated etc. 10479 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 10480 if (!MD->isUserProvided()) 10481 return GVA_DiscardableODR; 10482 10483 GVALinkage External; 10484 switch (FD->getTemplateSpecializationKind()) { 10485 case TSK_Undeclared: 10486 case TSK_ExplicitSpecialization: 10487 External = GVA_StrongExternal; 10488 break; 10489 10490 case TSK_ExplicitInstantiationDefinition: 10491 return GVA_StrongODR; 10492 10493 // C++11 [temp.explicit]p10: 10494 // [ Note: The intent is that an inline function that is the subject of 10495 // an explicit instantiation declaration will still be implicitly 10496 // instantiated when used so that the body can be considered for 10497 // inlining, but that no out-of-line copy of the inline function would be 10498 // generated in the translation unit. -- end note ] 10499 case TSK_ExplicitInstantiationDeclaration: 10500 return GVA_AvailableExternally; 10501 10502 case TSK_ImplicitInstantiation: 10503 External = GVA_DiscardableODR; 10504 break; 10505 } 10506 10507 if (!FD->isInlined()) 10508 return External; 10509 10510 if ((!Context.getLangOpts().CPlusPlus && 10511 !Context.getTargetInfo().getCXXABI().isMicrosoft() && 10512 !FD->hasAttr<DLLExportAttr>()) || 10513 FD->hasAttr<GNUInlineAttr>()) { 10514 // FIXME: This doesn't match gcc's behavior for dllexport inline functions. 10515 10516 // GNU or C99 inline semantics. Determine whether this symbol should be 10517 // externally visible. 10518 if (FD->isInlineDefinitionExternallyVisible()) 10519 return External; 10520 10521 // C99 inline semantics, where the symbol is not externally visible. 10522 return GVA_AvailableExternally; 10523 } 10524 10525 // Functions specified with extern and inline in -fms-compatibility mode 10526 // forcibly get emitted. While the body of the function cannot be later 10527 // replaced, the function definition cannot be discarded. 10528 if (FD->isMSExternInline()) 10529 return GVA_StrongODR; 10530 10531 return GVA_DiscardableODR; 10532 } 10533 10534 static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context, 10535 const Decl *D, GVALinkage L) { 10536 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx 10537 // dllexport/dllimport on inline functions. 10538 if (D->hasAttr<DLLImportAttr>()) { 10539 if (L == GVA_DiscardableODR || L == GVA_StrongODR) 10540 return GVA_AvailableExternally; 10541 } else if (D->hasAttr<DLLExportAttr>()) { 10542 if (L == GVA_DiscardableODR) 10543 return GVA_StrongODR; 10544 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) { 10545 // Device-side functions with __global__ attribute must always be 10546 // visible externally so they can be launched from host. 10547 if (D->hasAttr<CUDAGlobalAttr>() && 10548 (L == GVA_DiscardableODR || L == GVA_Internal)) 10549 return GVA_StrongODR; 10550 // Single source offloading languages like CUDA/HIP need to be able to 10551 // access static device variables from host code of the same compilation 10552 // unit. This is done by externalizing the static variable. 10553 if (Context.shouldExternalizeStaticVar(D)) 10554 return GVA_StrongExternal; 10555 } 10556 return L; 10557 } 10558 10559 /// Adjust the GVALinkage for a declaration based on what an external AST source 10560 /// knows about whether there can be other definitions of this declaration. 10561 static GVALinkage 10562 adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D, 10563 GVALinkage L) { 10564 ExternalASTSource *Source = Ctx.getExternalSource(); 10565 if (!Source) 10566 return L; 10567 10568 switch (Source->hasExternalDefinitions(D)) { 10569 case ExternalASTSource::EK_Never: 10570 // Other translation units rely on us to provide the definition. 10571 if (L == GVA_DiscardableODR) 10572 return GVA_StrongODR; 10573 break; 10574 10575 case ExternalASTSource::EK_Always: 10576 return GVA_AvailableExternally; 10577 10578 case ExternalASTSource::EK_ReplyHazy: 10579 break; 10580 } 10581 return L; 10582 } 10583 10584 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const { 10585 return adjustGVALinkageForExternalDefinitionKind(*this, FD, 10586 adjustGVALinkageForAttributes(*this, FD, 10587 basicGVALinkageForFunction(*this, FD))); 10588 } 10589 10590 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context, 10591 const VarDecl *VD) { 10592 if (!VD->isExternallyVisible()) 10593 return GVA_Internal; 10594 10595 if (VD->isStaticLocal()) { 10596 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod(); 10597 while (LexicalContext && !isa<FunctionDecl>(LexicalContext)) 10598 LexicalContext = LexicalContext->getLexicalParent(); 10599 10600 // ObjC Blocks can create local variables that don't have a FunctionDecl 10601 // LexicalContext. 10602 if (!LexicalContext) 10603 return GVA_DiscardableODR; 10604 10605 // Otherwise, let the static local variable inherit its linkage from the 10606 // nearest enclosing function. 10607 auto StaticLocalLinkage = 10608 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext)); 10609 10610 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must 10611 // be emitted in any object with references to the symbol for the object it 10612 // contains, whether inline or out-of-line." 10613 // Similar behavior is observed with MSVC. An alternative ABI could use 10614 // StrongODR/AvailableExternally to match the function, but none are 10615 // known/supported currently. 10616 if (StaticLocalLinkage == GVA_StrongODR || 10617 StaticLocalLinkage == GVA_AvailableExternally) 10618 return GVA_DiscardableODR; 10619 return StaticLocalLinkage; 10620 } 10621 10622 // MSVC treats in-class initialized static data members as definitions. 10623 // By giving them non-strong linkage, out-of-line definitions won't 10624 // cause link errors. 10625 if (Context.isMSStaticDataMemberInlineDefinition(VD)) 10626 return GVA_DiscardableODR; 10627 10628 // Most non-template variables have strong linkage; inline variables are 10629 // linkonce_odr or (occasionally, for compatibility) weak_odr. 10630 GVALinkage StrongLinkage; 10631 switch (Context.getInlineVariableDefinitionKind(VD)) { 10632 case ASTContext::InlineVariableDefinitionKind::None: 10633 StrongLinkage = GVA_StrongExternal; 10634 break; 10635 case ASTContext::InlineVariableDefinitionKind::Weak: 10636 case ASTContext::InlineVariableDefinitionKind::WeakUnknown: 10637 StrongLinkage = GVA_DiscardableODR; 10638 break; 10639 case ASTContext::InlineVariableDefinitionKind::Strong: 10640 StrongLinkage = GVA_StrongODR; 10641 break; 10642 } 10643 10644 switch (VD->getTemplateSpecializationKind()) { 10645 case TSK_Undeclared: 10646 return StrongLinkage; 10647 10648 case TSK_ExplicitSpecialization: 10649 return Context.getTargetInfo().getCXXABI().isMicrosoft() && 10650 VD->isStaticDataMember() 10651 ? GVA_StrongODR 10652 : StrongLinkage; 10653 10654 case TSK_ExplicitInstantiationDefinition: 10655 return GVA_StrongODR; 10656 10657 case TSK_ExplicitInstantiationDeclaration: 10658 return GVA_AvailableExternally; 10659 10660 case TSK_ImplicitInstantiation: 10661 return GVA_DiscardableODR; 10662 } 10663 10664 llvm_unreachable("Invalid Linkage!"); 10665 } 10666 10667 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) { 10668 return adjustGVALinkageForExternalDefinitionKind(*this, VD, 10669 adjustGVALinkageForAttributes(*this, VD, 10670 basicGVALinkageForVariable(*this, VD))); 10671 } 10672 10673 bool ASTContext::DeclMustBeEmitted(const Decl *D) { 10674 if (const auto *VD = dyn_cast<VarDecl>(D)) { 10675 if (!VD->isFileVarDecl()) 10676 return false; 10677 // Global named register variables (GNU extension) are never emitted. 10678 if (VD->getStorageClass() == SC_Register) 10679 return false; 10680 if (VD->getDescribedVarTemplate() || 10681 isa<VarTemplatePartialSpecializationDecl>(VD)) 10682 return false; 10683 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 10684 // We never need to emit an uninstantiated function template. 10685 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10686 return false; 10687 } else if (isa<PragmaCommentDecl>(D)) 10688 return true; 10689 else if (isa<PragmaDetectMismatchDecl>(D)) 10690 return true; 10691 else if (isa<OMPRequiresDecl>(D)) 10692 return true; 10693 else if (isa<OMPThreadPrivateDecl>(D)) 10694 return !D->getDeclContext()->isDependentContext(); 10695 else if (isa<OMPAllocateDecl>(D)) 10696 return !D->getDeclContext()->isDependentContext(); 10697 else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D)) 10698 return !D->getDeclContext()->isDependentContext(); 10699 else if (isa<ImportDecl>(D)) 10700 return true; 10701 else 10702 return false; 10703 10704 // If this is a member of a class template, we do not need to emit it. 10705 if (D->getDeclContext()->isDependentContext()) 10706 return false; 10707 10708 // Weak references don't produce any output by themselves. 10709 if (D->hasAttr<WeakRefAttr>()) 10710 return false; 10711 10712 // Aliases and used decls are required. 10713 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>()) 10714 return true; 10715 10716 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 10717 // Forward declarations aren't required. 10718 if (!FD->doesThisDeclarationHaveABody()) 10719 return FD->doesDeclarationForceExternallyVisibleDefinition(); 10720 10721 // Constructors and destructors are required. 10722 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>()) 10723 return true; 10724 10725 // The key function for a class is required. This rule only comes 10726 // into play when inline functions can be key functions, though. 10727 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 10728 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 10729 const CXXRecordDecl *RD = MD->getParent(); 10730 if (MD->isOutOfLine() && RD->isDynamicClass()) { 10731 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD); 10732 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl()) 10733 return true; 10734 } 10735 } 10736 } 10737 10738 GVALinkage Linkage = GetGVALinkageForFunction(FD); 10739 10740 // static, static inline, always_inline, and extern inline functions can 10741 // always be deferred. Normal inline functions can be deferred in C99/C++. 10742 // Implicit template instantiations can also be deferred in C++. 10743 return !isDiscardableGVALinkage(Linkage); 10744 } 10745 10746 const auto *VD = cast<VarDecl>(D); 10747 assert(VD->isFileVarDecl() && "Expected file scoped var"); 10748 10749 // If the decl is marked as `declare target to`, it should be emitted for the 10750 // host and for the device. 10751 if (LangOpts.OpenMP && 10752 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 10753 return true; 10754 10755 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly && 10756 !isMSStaticDataMemberInlineDefinition(VD)) 10757 return false; 10758 10759 // Variables that can be needed in other TUs are required. 10760 auto Linkage = GetGVALinkageForVariable(VD); 10761 if (!isDiscardableGVALinkage(Linkage)) 10762 return true; 10763 10764 // We never need to emit a variable that is available in another TU. 10765 if (Linkage == GVA_AvailableExternally) 10766 return false; 10767 10768 // Variables that have destruction with side-effects are required. 10769 if (VD->needsDestruction(*this)) 10770 return true; 10771 10772 // Variables that have initialization with side-effects are required. 10773 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) && 10774 // We can get a value-dependent initializer during error recovery. 10775 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 10776 return true; 10777 10778 // Likewise, variables with tuple-like bindings are required if their 10779 // bindings have side-effects. 10780 if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) 10781 for (const auto *BD : DD->bindings()) 10782 if (const auto *BindingVD = BD->getHoldingVar()) 10783 if (DeclMustBeEmitted(BindingVD)) 10784 return true; 10785 10786 return false; 10787 } 10788 10789 void ASTContext::forEachMultiversionedFunctionVersion( 10790 const FunctionDecl *FD, 10791 llvm::function_ref<void(FunctionDecl *)> Pred) const { 10792 assert(FD->isMultiVersion() && "Only valid for multiversioned functions"); 10793 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls; 10794 FD = FD->getMostRecentDecl(); 10795 for (auto *CurDecl : 10796 FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) { 10797 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl(); 10798 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) && 10799 std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) { 10800 SeenDecls.insert(CurFD); 10801 Pred(CurFD); 10802 } 10803 } 10804 } 10805 10806 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic, 10807 bool IsCXXMethod, 10808 bool IsBuiltin) const { 10809 // Pass through to the C++ ABI object 10810 if (IsCXXMethod) 10811 return ABI->getDefaultMethodCallConv(IsVariadic); 10812 10813 // Builtins ignore user-specified default calling convention and remain the 10814 // Target's default calling convention. 10815 if (!IsBuiltin) { 10816 switch (LangOpts.getDefaultCallingConv()) { 10817 case LangOptions::DCC_None: 10818 break; 10819 case LangOptions::DCC_CDecl: 10820 return CC_C; 10821 case LangOptions::DCC_FastCall: 10822 if (getTargetInfo().hasFeature("sse2") && !IsVariadic) 10823 return CC_X86FastCall; 10824 break; 10825 case LangOptions::DCC_StdCall: 10826 if (!IsVariadic) 10827 return CC_X86StdCall; 10828 break; 10829 case LangOptions::DCC_VectorCall: 10830 // __vectorcall cannot be applied to variadic functions. 10831 if (!IsVariadic) 10832 return CC_X86VectorCall; 10833 break; 10834 case LangOptions::DCC_RegCall: 10835 // __regcall cannot be applied to variadic functions. 10836 if (!IsVariadic) 10837 return CC_X86RegCall; 10838 break; 10839 } 10840 } 10841 return Target->getDefaultCallingConv(); 10842 } 10843 10844 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const { 10845 // Pass through to the C++ ABI object 10846 return ABI->isNearlyEmpty(RD); 10847 } 10848 10849 VTableContextBase *ASTContext::getVTableContext() { 10850 if (!VTContext.get()) { 10851 auto ABI = Target->getCXXABI(); 10852 if (ABI.isMicrosoft()) 10853 VTContext.reset(new MicrosoftVTableContext(*this)); 10854 else { 10855 auto ComponentLayout = getLangOpts().RelativeCXXABIVTables 10856 ? ItaniumVTableContext::Relative 10857 : ItaniumVTableContext::Pointer; 10858 VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout)); 10859 } 10860 } 10861 return VTContext.get(); 10862 } 10863 10864 MangleContext *ASTContext::createMangleContext(const TargetInfo *T) { 10865 if (!T) 10866 T = Target; 10867 switch (T->getCXXABI().getKind()) { 10868 case TargetCXXABI::AppleARM64: 10869 case TargetCXXABI::Fuchsia: 10870 case TargetCXXABI::GenericAArch64: 10871 case TargetCXXABI::GenericItanium: 10872 case TargetCXXABI::GenericARM: 10873 case TargetCXXABI::GenericMIPS: 10874 case TargetCXXABI::iOS: 10875 case TargetCXXABI::WebAssembly: 10876 case TargetCXXABI::WatchOS: 10877 case TargetCXXABI::XL: 10878 return ItaniumMangleContext::create(*this, getDiagnostics()); 10879 case TargetCXXABI::Microsoft: 10880 return MicrosoftMangleContext::create(*this, getDiagnostics()); 10881 } 10882 llvm_unreachable("Unsupported ABI"); 10883 } 10884 10885 CXXABI::~CXXABI() = default; 10886 10887 size_t ASTContext::getSideTableAllocatedMemory() const { 10888 return ASTRecordLayouts.getMemorySize() + 10889 llvm::capacity_in_bytes(ObjCLayouts) + 10890 llvm::capacity_in_bytes(KeyFunctions) + 10891 llvm::capacity_in_bytes(ObjCImpls) + 10892 llvm::capacity_in_bytes(BlockVarCopyInits) + 10893 llvm::capacity_in_bytes(DeclAttrs) + 10894 llvm::capacity_in_bytes(TemplateOrInstantiation) + 10895 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) + 10896 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) + 10897 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) + 10898 llvm::capacity_in_bytes(OverriddenMethods) + 10899 llvm::capacity_in_bytes(Types) + 10900 llvm::capacity_in_bytes(VariableArrayTypes); 10901 } 10902 10903 /// getIntTypeForBitwidth - 10904 /// sets integer QualTy according to specified details: 10905 /// bitwidth, signed/unsigned. 10906 /// Returns empty type if there is no appropriate target types. 10907 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth, 10908 unsigned Signed) const { 10909 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed); 10910 CanQualType QualTy = getFromTargetType(Ty); 10911 if (!QualTy && DestWidth == 128) 10912 return Signed ? Int128Ty : UnsignedInt128Ty; 10913 return QualTy; 10914 } 10915 10916 /// getRealTypeForBitwidth - 10917 /// sets floating point QualTy according to specified bitwidth. 10918 /// Returns empty type if there is no appropriate target types. 10919 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth, 10920 bool ExplicitIEEE) const { 10921 TargetInfo::RealType Ty = 10922 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitIEEE); 10923 switch (Ty) { 10924 case TargetInfo::Float: 10925 return FloatTy; 10926 case TargetInfo::Double: 10927 return DoubleTy; 10928 case TargetInfo::LongDouble: 10929 return LongDoubleTy; 10930 case TargetInfo::Float128: 10931 return Float128Ty; 10932 case TargetInfo::NoFloat: 10933 return {}; 10934 } 10935 10936 llvm_unreachable("Unhandled TargetInfo::RealType value"); 10937 } 10938 10939 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) { 10940 if (Number > 1) 10941 MangleNumbers[ND] = Number; 10942 } 10943 10944 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const { 10945 auto I = MangleNumbers.find(ND); 10946 return I != MangleNumbers.end() ? I->second : 1; 10947 } 10948 10949 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) { 10950 if (Number > 1) 10951 StaticLocalNumbers[VD] = Number; 10952 } 10953 10954 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const { 10955 auto I = StaticLocalNumbers.find(VD); 10956 return I != StaticLocalNumbers.end() ? I->second : 1; 10957 } 10958 10959 MangleNumberingContext & 10960 ASTContext::getManglingNumberContext(const DeclContext *DC) { 10961 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C. 10962 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC]; 10963 if (!MCtx) 10964 MCtx = createMangleNumberingContext(); 10965 return *MCtx; 10966 } 10967 10968 MangleNumberingContext & 10969 ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) { 10970 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C. 10971 std::unique_ptr<MangleNumberingContext> &MCtx = 10972 ExtraMangleNumberingContexts[D]; 10973 if (!MCtx) 10974 MCtx = createMangleNumberingContext(); 10975 return *MCtx; 10976 } 10977 10978 std::unique_ptr<MangleNumberingContext> 10979 ASTContext::createMangleNumberingContext() const { 10980 return ABI->createMangleNumberingContext(); 10981 } 10982 10983 const CXXConstructorDecl * 10984 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) { 10985 return ABI->getCopyConstructorForExceptionObject( 10986 cast<CXXRecordDecl>(RD->getFirstDecl())); 10987 } 10988 10989 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD, 10990 CXXConstructorDecl *CD) { 10991 return ABI->addCopyConstructorForExceptionObject( 10992 cast<CXXRecordDecl>(RD->getFirstDecl()), 10993 cast<CXXConstructorDecl>(CD->getFirstDecl())); 10994 } 10995 10996 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD, 10997 TypedefNameDecl *DD) { 10998 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD); 10999 } 11000 11001 TypedefNameDecl * 11002 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) { 11003 return ABI->getTypedefNameForUnnamedTagDecl(TD); 11004 } 11005 11006 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD, 11007 DeclaratorDecl *DD) { 11008 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD); 11009 } 11010 11011 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) { 11012 return ABI->getDeclaratorForUnnamedTagDecl(TD); 11013 } 11014 11015 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) { 11016 ParamIndices[D] = index; 11017 } 11018 11019 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const { 11020 ParameterIndexTable::const_iterator I = ParamIndices.find(D); 11021 assert(I != ParamIndices.end() && 11022 "ParmIndices lacks entry set by ParmVarDecl"); 11023 return I->second; 11024 } 11025 11026 QualType ASTContext::getStringLiteralArrayType(QualType EltTy, 11027 unsigned Length) const { 11028 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 11029 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 11030 EltTy = EltTy.withConst(); 11031 11032 EltTy = adjustStringLiteralBaseType(EltTy); 11033 11034 // Get an array type for the string, according to C99 6.4.5. This includes 11035 // the null terminator character. 11036 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr, 11037 ArrayType::Normal, /*IndexTypeQuals*/ 0); 11038 } 11039 11040 StringLiteral * 11041 ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const { 11042 StringLiteral *&Result = StringLiteralCache[Key]; 11043 if (!Result) 11044 Result = StringLiteral::Create( 11045 *this, Key, StringLiteral::Ascii, 11046 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()), 11047 SourceLocation()); 11048 return Result; 11049 } 11050 11051 MSGuidDecl * 11052 ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const { 11053 assert(MSGuidTagDecl && "building MS GUID without MS extensions?"); 11054 11055 llvm::FoldingSetNodeID ID; 11056 MSGuidDecl::Profile(ID, Parts); 11057 11058 void *InsertPos; 11059 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos)) 11060 return Existing; 11061 11062 QualType GUIDType = getMSGuidType().withConst(); 11063 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts); 11064 MSGuidDecls.InsertNode(New, InsertPos); 11065 return New; 11066 } 11067 11068 TemplateParamObjectDecl * 11069 ASTContext::getTemplateParamObjectDecl(QualType T, const APValue &V) const { 11070 assert(T->isRecordType() && "template param object of unexpected type"); 11071 11072 // C++ [temp.param]p8: 11073 // [...] a static storage duration object of type 'const T' [...] 11074 T.addConst(); 11075 11076 llvm::FoldingSetNodeID ID; 11077 TemplateParamObjectDecl::Profile(ID, T, V); 11078 11079 void *InsertPos; 11080 if (TemplateParamObjectDecl *Existing = 11081 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos)) 11082 return Existing; 11083 11084 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V); 11085 TemplateParamObjectDecls.InsertNode(New, InsertPos); 11086 return New; 11087 } 11088 11089 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const { 11090 const llvm::Triple &T = getTargetInfo().getTriple(); 11091 if (!T.isOSDarwin()) 11092 return false; 11093 11094 if (!(T.isiOS() && T.isOSVersionLT(7)) && 11095 !(T.isMacOSX() && T.isOSVersionLT(10, 9))) 11096 return false; 11097 11098 QualType AtomicTy = E->getPtr()->getType()->getPointeeType(); 11099 CharUnits sizeChars = getTypeSizeInChars(AtomicTy); 11100 uint64_t Size = sizeChars.getQuantity(); 11101 CharUnits alignChars = getTypeAlignInChars(AtomicTy); 11102 unsigned Align = alignChars.getQuantity(); 11103 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth(); 11104 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits); 11105 } 11106 11107 bool 11108 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, 11109 const ObjCMethodDecl *MethodImpl) { 11110 // No point trying to match an unavailable/deprecated mothod. 11111 if (MethodDecl->hasAttr<UnavailableAttr>() 11112 || MethodDecl->hasAttr<DeprecatedAttr>()) 11113 return false; 11114 if (MethodDecl->getObjCDeclQualifier() != 11115 MethodImpl->getObjCDeclQualifier()) 11116 return false; 11117 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType())) 11118 return false; 11119 11120 if (MethodDecl->param_size() != MethodImpl->param_size()) 11121 return false; 11122 11123 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(), 11124 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(), 11125 EF = MethodDecl->param_end(); 11126 IM != EM && IF != EF; ++IM, ++IF) { 11127 const ParmVarDecl *DeclVar = (*IF); 11128 const ParmVarDecl *ImplVar = (*IM); 11129 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier()) 11130 return false; 11131 if (!hasSameType(DeclVar->getType(), ImplVar->getType())) 11132 return false; 11133 } 11134 11135 return (MethodDecl->isVariadic() == MethodImpl->isVariadic()); 11136 } 11137 11138 uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const { 11139 LangAS AS; 11140 if (QT->getUnqualifiedDesugaredType()->isNullPtrType()) 11141 AS = LangAS::Default; 11142 else 11143 AS = QT->getPointeeType().getAddressSpace(); 11144 11145 return getTargetInfo().getNullPointerValue(AS); 11146 } 11147 11148 unsigned ASTContext::getTargetAddressSpace(LangAS AS) const { 11149 if (isTargetAddressSpace(AS)) 11150 return toTargetAddressSpace(AS); 11151 else 11152 return (*AddrSpaceMap)[(unsigned)AS]; 11153 } 11154 11155 QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const { 11156 assert(Ty->isFixedPointType()); 11157 11158 if (Ty->isSaturatedFixedPointType()) return Ty; 11159 11160 switch (Ty->castAs<BuiltinType>()->getKind()) { 11161 default: 11162 llvm_unreachable("Not a fixed point type!"); 11163 case BuiltinType::ShortAccum: 11164 return SatShortAccumTy; 11165 case BuiltinType::Accum: 11166 return SatAccumTy; 11167 case BuiltinType::LongAccum: 11168 return SatLongAccumTy; 11169 case BuiltinType::UShortAccum: 11170 return SatUnsignedShortAccumTy; 11171 case BuiltinType::UAccum: 11172 return SatUnsignedAccumTy; 11173 case BuiltinType::ULongAccum: 11174 return SatUnsignedLongAccumTy; 11175 case BuiltinType::ShortFract: 11176 return SatShortFractTy; 11177 case BuiltinType::Fract: 11178 return SatFractTy; 11179 case BuiltinType::LongFract: 11180 return SatLongFractTy; 11181 case BuiltinType::UShortFract: 11182 return SatUnsignedShortFractTy; 11183 case BuiltinType::UFract: 11184 return SatUnsignedFractTy; 11185 case BuiltinType::ULongFract: 11186 return SatUnsignedLongFractTy; 11187 } 11188 } 11189 11190 LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const { 11191 if (LangOpts.OpenCL) 11192 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS); 11193 11194 if (LangOpts.CUDA) 11195 return getTargetInfo().getCUDABuiltinAddressSpace(AS); 11196 11197 return getLangASFromTargetAS(AS); 11198 } 11199 11200 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that 11201 // doesn't include ASTContext.h 11202 template 11203 clang::LazyGenerationalUpdatePtr< 11204 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType 11205 clang::LazyGenerationalUpdatePtr< 11206 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue( 11207 const clang::ASTContext &Ctx, Decl *Value); 11208 11209 unsigned char ASTContext::getFixedPointScale(QualType Ty) const { 11210 assert(Ty->isFixedPointType()); 11211 11212 const TargetInfo &Target = getTargetInfo(); 11213 switch (Ty->castAs<BuiltinType>()->getKind()) { 11214 default: 11215 llvm_unreachable("Not a fixed point type!"); 11216 case BuiltinType::ShortAccum: 11217 case BuiltinType::SatShortAccum: 11218 return Target.getShortAccumScale(); 11219 case BuiltinType::Accum: 11220 case BuiltinType::SatAccum: 11221 return Target.getAccumScale(); 11222 case BuiltinType::LongAccum: 11223 case BuiltinType::SatLongAccum: 11224 return Target.getLongAccumScale(); 11225 case BuiltinType::UShortAccum: 11226 case BuiltinType::SatUShortAccum: 11227 return Target.getUnsignedShortAccumScale(); 11228 case BuiltinType::UAccum: 11229 case BuiltinType::SatUAccum: 11230 return Target.getUnsignedAccumScale(); 11231 case BuiltinType::ULongAccum: 11232 case BuiltinType::SatULongAccum: 11233 return Target.getUnsignedLongAccumScale(); 11234 case BuiltinType::ShortFract: 11235 case BuiltinType::SatShortFract: 11236 return Target.getShortFractScale(); 11237 case BuiltinType::Fract: 11238 case BuiltinType::SatFract: 11239 return Target.getFractScale(); 11240 case BuiltinType::LongFract: 11241 case BuiltinType::SatLongFract: 11242 return Target.getLongFractScale(); 11243 case BuiltinType::UShortFract: 11244 case BuiltinType::SatUShortFract: 11245 return Target.getUnsignedShortFractScale(); 11246 case BuiltinType::UFract: 11247 case BuiltinType::SatUFract: 11248 return Target.getUnsignedFractScale(); 11249 case BuiltinType::ULongFract: 11250 case BuiltinType::SatULongFract: 11251 return Target.getUnsignedLongFractScale(); 11252 } 11253 } 11254 11255 unsigned char ASTContext::getFixedPointIBits(QualType Ty) const { 11256 assert(Ty->isFixedPointType()); 11257 11258 const TargetInfo &Target = getTargetInfo(); 11259 switch (Ty->castAs<BuiltinType>()->getKind()) { 11260 default: 11261 llvm_unreachable("Not a fixed point type!"); 11262 case BuiltinType::ShortAccum: 11263 case BuiltinType::SatShortAccum: 11264 return Target.getShortAccumIBits(); 11265 case BuiltinType::Accum: 11266 case BuiltinType::SatAccum: 11267 return Target.getAccumIBits(); 11268 case BuiltinType::LongAccum: 11269 case BuiltinType::SatLongAccum: 11270 return Target.getLongAccumIBits(); 11271 case BuiltinType::UShortAccum: 11272 case BuiltinType::SatUShortAccum: 11273 return Target.getUnsignedShortAccumIBits(); 11274 case BuiltinType::UAccum: 11275 case BuiltinType::SatUAccum: 11276 return Target.getUnsignedAccumIBits(); 11277 case BuiltinType::ULongAccum: 11278 case BuiltinType::SatULongAccum: 11279 return Target.getUnsignedLongAccumIBits(); 11280 case BuiltinType::ShortFract: 11281 case BuiltinType::SatShortFract: 11282 case BuiltinType::Fract: 11283 case BuiltinType::SatFract: 11284 case BuiltinType::LongFract: 11285 case BuiltinType::SatLongFract: 11286 case BuiltinType::UShortFract: 11287 case BuiltinType::SatUShortFract: 11288 case BuiltinType::UFract: 11289 case BuiltinType::SatUFract: 11290 case BuiltinType::ULongFract: 11291 case BuiltinType::SatULongFract: 11292 return 0; 11293 } 11294 } 11295 11296 llvm::FixedPointSemantics 11297 ASTContext::getFixedPointSemantics(QualType Ty) const { 11298 assert((Ty->isFixedPointType() || Ty->isIntegerType()) && 11299 "Can only get the fixed point semantics for a " 11300 "fixed point or integer type."); 11301 if (Ty->isIntegerType()) 11302 return llvm::FixedPointSemantics::GetIntegerSemantics( 11303 getIntWidth(Ty), Ty->isSignedIntegerType()); 11304 11305 bool isSigned = Ty->isSignedFixedPointType(); 11306 return llvm::FixedPointSemantics( 11307 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned, 11308 Ty->isSaturatedFixedPointType(), 11309 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding()); 11310 } 11311 11312 llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const { 11313 assert(Ty->isFixedPointType()); 11314 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty)); 11315 } 11316 11317 llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const { 11318 assert(Ty->isFixedPointType()); 11319 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty)); 11320 } 11321 11322 QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const { 11323 assert(Ty->isUnsignedFixedPointType() && 11324 "Expected unsigned fixed point type"); 11325 11326 switch (Ty->castAs<BuiltinType>()->getKind()) { 11327 case BuiltinType::UShortAccum: 11328 return ShortAccumTy; 11329 case BuiltinType::UAccum: 11330 return AccumTy; 11331 case BuiltinType::ULongAccum: 11332 return LongAccumTy; 11333 case BuiltinType::SatUShortAccum: 11334 return SatShortAccumTy; 11335 case BuiltinType::SatUAccum: 11336 return SatAccumTy; 11337 case BuiltinType::SatULongAccum: 11338 return SatLongAccumTy; 11339 case BuiltinType::UShortFract: 11340 return ShortFractTy; 11341 case BuiltinType::UFract: 11342 return FractTy; 11343 case BuiltinType::ULongFract: 11344 return LongFractTy; 11345 case BuiltinType::SatUShortFract: 11346 return SatShortFractTy; 11347 case BuiltinType::SatUFract: 11348 return SatFractTy; 11349 case BuiltinType::SatULongFract: 11350 return SatLongFractTy; 11351 default: 11352 llvm_unreachable("Unexpected unsigned fixed point type"); 11353 } 11354 } 11355 11356 ParsedTargetAttr 11357 ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const { 11358 assert(TD != nullptr); 11359 ParsedTargetAttr ParsedAttr = TD->parse(); 11360 11361 ParsedAttr.Features.erase( 11362 llvm::remove_if(ParsedAttr.Features, 11363 [&](const std::string &Feat) { 11364 return !Target->isValidFeatureName( 11365 StringRef{Feat}.substr(1)); 11366 }), 11367 ParsedAttr.Features.end()); 11368 return ParsedAttr; 11369 } 11370 11371 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 11372 const FunctionDecl *FD) const { 11373 if (FD) 11374 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD)); 11375 else 11376 Target->initFeatureMap(FeatureMap, getDiagnostics(), 11377 Target->getTargetOpts().CPU, 11378 Target->getTargetOpts().Features); 11379 } 11380 11381 // Fills in the supplied string map with the set of target features for the 11382 // passed in function. 11383 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 11384 GlobalDecl GD) const { 11385 StringRef TargetCPU = Target->getTargetOpts().CPU; 11386 const FunctionDecl *FD = GD.getDecl()->getAsFunction(); 11387 if (const auto *TD = FD->getAttr<TargetAttr>()) { 11388 ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD); 11389 11390 // Make a copy of the features as passed on the command line into the 11391 // beginning of the additional features from the function to override. 11392 ParsedAttr.Features.insert( 11393 ParsedAttr.Features.begin(), 11394 Target->getTargetOpts().FeaturesAsWritten.begin(), 11395 Target->getTargetOpts().FeaturesAsWritten.end()); 11396 11397 if (ParsedAttr.Architecture != "" && 11398 Target->isValidCPUName(ParsedAttr.Architecture)) 11399 TargetCPU = ParsedAttr.Architecture; 11400 11401 // Now populate the feature map, first with the TargetCPU which is either 11402 // the default or a new one from the target attribute string. Then we'll use 11403 // the passed in features (FeaturesAsWritten) along with the new ones from 11404 // the attribute. 11405 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, 11406 ParsedAttr.Features); 11407 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) { 11408 llvm::SmallVector<StringRef, 32> FeaturesTmp; 11409 Target->getCPUSpecificCPUDispatchFeatures( 11410 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp); 11411 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end()); 11412 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features); 11413 } else { 11414 FeatureMap = Target->getTargetOpts().FeatureMap; 11415 } 11416 } 11417 11418 OMPTraitInfo &ASTContext::getNewOMPTraitInfo() { 11419 OMPTraitInfoVector.emplace_back(new OMPTraitInfo()); 11420 return *OMPTraitInfoVector.back(); 11421 } 11422 11423 const StreamingDiagnostic &clang:: 11424 operator<<(const StreamingDiagnostic &DB, 11425 const ASTContext::SectionInfo &Section) { 11426 if (Section.Decl) 11427 return DB << Section.Decl; 11428 return DB << "a prior #pragma section"; 11429 } 11430 11431 bool ASTContext::mayExternalizeStaticVar(const Decl *D) const { 11432 return !getLangOpts().GPURelocatableDeviceCode && 11433 ((D->hasAttr<CUDADeviceAttr>() && 11434 !D->getAttr<CUDADeviceAttr>()->isImplicit()) || 11435 (D->hasAttr<CUDAConstantAttr>() && 11436 !D->getAttr<CUDAConstantAttr>()->isImplicit())) && 11437 isa<VarDecl>(D) && cast<VarDecl>(D)->isFileVarDecl() && 11438 cast<VarDecl>(D)->getStorageClass() == SC_Static; 11439 } 11440 11441 bool ASTContext::shouldExternalizeStaticVar(const Decl *D) const { 11442 return mayExternalizeStaticVar(D) && 11443 CUDAStaticDeviceVarReferencedByHost.count(cast<VarDecl>(D)); 11444 } 11445