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/NoSanitizeList.h" 60 #include "clang/Basic/ObjCRuntime.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/MD5.h" 88 #include "llvm/Support/MathExtras.h" 89 #include "llvm/Support/raw_ostream.h" 90 #include <algorithm> 91 #include <cassert> 92 #include <cstddef> 93 #include <cstdint> 94 #include <cstdlib> 95 #include <map> 96 #include <memory> 97 #include <string> 98 #include <tuple> 99 #include <utility> 100 101 using namespace clang; 102 103 enum FloatingRank { 104 BFloat16Rank, 105 Float16Rank, 106 HalfRank, 107 FloatRank, 108 DoubleRank, 109 LongDoubleRank, 110 Float128Rank, 111 Ibm128Rank 112 }; 113 114 /// \returns location that is relevant when searching for Doc comments related 115 /// to \p D. 116 static SourceLocation getDeclLocForCommentSearch(const Decl *D, 117 SourceManager &SourceMgr) { 118 assert(D); 119 120 // User can not attach documentation to implicit declarations. 121 if (D->isImplicit()) 122 return {}; 123 124 // User can not attach documentation to implicit instantiations. 125 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 126 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 127 return {}; 128 } 129 130 if (const auto *VD = dyn_cast<VarDecl>(D)) { 131 if (VD->isStaticDataMember() && 132 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 133 return {}; 134 } 135 136 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) { 137 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 138 return {}; 139 } 140 141 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) { 142 TemplateSpecializationKind TSK = CTSD->getSpecializationKind(); 143 if (TSK == TSK_ImplicitInstantiation || 144 TSK == TSK_Undeclared) 145 return {}; 146 } 147 148 if (const auto *ED = dyn_cast<EnumDecl>(D)) { 149 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 150 return {}; 151 } 152 if (const auto *TD = dyn_cast<TagDecl>(D)) { 153 // When tag declaration (but not definition!) is part of the 154 // decl-specifier-seq of some other declaration, it doesn't get comment 155 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition()) 156 return {}; 157 } 158 // TODO: handle comments for function parameters properly. 159 if (isa<ParmVarDecl>(D)) 160 return {}; 161 162 // TODO: we could look up template parameter documentation in the template 163 // documentation. 164 if (isa<TemplateTypeParmDecl>(D) || 165 isa<NonTypeTemplateParmDecl>(D) || 166 isa<TemplateTemplateParmDecl>(D)) 167 return {}; 168 169 // Find declaration location. 170 // For Objective-C declarations we generally don't expect to have multiple 171 // declarators, thus use declaration starting location as the "declaration 172 // location". 173 // For all other declarations multiple declarators are used quite frequently, 174 // so we use the location of the identifier as the "declaration location". 175 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) || 176 isa<ObjCPropertyDecl>(D) || 177 isa<RedeclarableTemplateDecl>(D) || 178 isa<ClassTemplateSpecializationDecl>(D) || 179 // Allow association with Y across {} in `typedef struct X {} Y`. 180 isa<TypedefDecl>(D)) 181 return D->getBeginLoc(); 182 183 const SourceLocation DeclLoc = D->getLocation(); 184 if (DeclLoc.isMacroID()) { 185 if (isa<TypedefDecl>(D)) { 186 // If location of the typedef name is in a macro, it is because being 187 // declared via a macro. Try using declaration's starting location as 188 // the "declaration location". 189 return D->getBeginLoc(); 190 } 191 192 if (const auto *TD = dyn_cast<TagDecl>(D)) { 193 // If location of the tag decl is inside a macro, but the spelling of 194 // the tag name comes from a macro argument, it looks like a special 195 // macro like NS_ENUM is being used to define the tag decl. In that 196 // case, adjust the source location to the expansion loc so that we can 197 // attach the comment to the tag decl. 198 if (SourceMgr.isMacroArgExpansion(DeclLoc) && TD->isCompleteDefinition()) 199 return SourceMgr.getExpansionLoc(DeclLoc); 200 } 201 } 202 203 return DeclLoc; 204 } 205 206 RawComment *ASTContext::getRawCommentForDeclNoCacheImpl( 207 const Decl *D, const SourceLocation RepresentativeLocForDecl, 208 const std::map<unsigned, RawComment *> &CommentsInTheFile) const { 209 // If the declaration doesn't map directly to a location in a file, we 210 // can't find the comment. 211 if (RepresentativeLocForDecl.isInvalid() || 212 !RepresentativeLocForDecl.isFileID()) 213 return nullptr; 214 215 // If there are no comments anywhere, we won't find anything. 216 if (CommentsInTheFile.empty()) 217 return nullptr; 218 219 // Decompose the location for the declaration and find the beginning of the 220 // file buffer. 221 const std::pair<FileID, unsigned> DeclLocDecomp = 222 SourceMgr.getDecomposedLoc(RepresentativeLocForDecl); 223 224 // Slow path. 225 auto OffsetCommentBehindDecl = 226 CommentsInTheFile.lower_bound(DeclLocDecomp.second); 227 228 // First check whether we have a trailing comment. 229 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) { 230 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second; 231 if ((CommentBehindDecl->isDocumentation() || 232 LangOpts.CommentOpts.ParseAllComments) && 233 CommentBehindDecl->isTrailingComment() && 234 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) || 235 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) { 236 237 // Check that Doxygen trailing comment comes after the declaration, starts 238 // on the same line and in the same file as the declaration. 239 if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) == 240 Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first, 241 OffsetCommentBehindDecl->first)) { 242 return CommentBehindDecl; 243 } 244 } 245 } 246 247 // The comment just after the declaration was not a trailing comment. 248 // Let's look at the previous comment. 249 if (OffsetCommentBehindDecl == CommentsInTheFile.begin()) 250 return nullptr; 251 252 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl; 253 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second; 254 255 // Check that we actually have a non-member Doxygen comment. 256 if (!(CommentBeforeDecl->isDocumentation() || 257 LangOpts.CommentOpts.ParseAllComments) || 258 CommentBeforeDecl->isTrailingComment()) 259 return nullptr; 260 261 // Decompose the end of the comment. 262 const unsigned CommentEndOffset = 263 Comments.getCommentEndOffset(CommentBeforeDecl); 264 265 // Get the corresponding buffer. 266 bool Invalid = false; 267 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first, 268 &Invalid).data(); 269 if (Invalid) 270 return nullptr; 271 272 // Extract text between the comment and declaration. 273 StringRef Text(Buffer + CommentEndOffset, 274 DeclLocDecomp.second - CommentEndOffset); 275 276 // There should be no other declarations or preprocessor directives between 277 // comment and declaration. 278 if (Text.find_first_of(";{}#@") != StringRef::npos) 279 return nullptr; 280 281 return CommentBeforeDecl; 282 } 283 284 RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const { 285 const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr); 286 287 // If the declaration doesn't map directly to a location in a file, we 288 // can't find the comment. 289 if (DeclLoc.isInvalid() || !DeclLoc.isFileID()) 290 return nullptr; 291 292 if (ExternalSource && !CommentsLoaded) { 293 ExternalSource->ReadComments(); 294 CommentsLoaded = true; 295 } 296 297 if (Comments.empty()) 298 return nullptr; 299 300 const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first; 301 const auto CommentsInThisFile = Comments.getCommentsInFile(File); 302 if (!CommentsInThisFile || CommentsInThisFile->empty()) 303 return nullptr; 304 305 return getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile); 306 } 307 308 void ASTContext::addComment(const RawComment &RC) { 309 assert(LangOpts.RetainCommentsFromSystemHeaders || 310 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin())); 311 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc); 312 } 313 314 /// If we have a 'templated' declaration for a template, adjust 'D' to 315 /// refer to the actual template. 316 /// If we have an implicit instantiation, adjust 'D' to refer to template. 317 static const Decl &adjustDeclToTemplate(const Decl &D) { 318 if (const auto *FD = dyn_cast<FunctionDecl>(&D)) { 319 // Is this function declaration part of a function template? 320 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 321 return *FTD; 322 323 // Nothing to do if function is not an implicit instantiation. 324 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) 325 return D; 326 327 // Function is an implicit instantiation of a function template? 328 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate()) 329 return *FTD; 330 331 // Function is instantiated from a member definition of a class template? 332 if (const FunctionDecl *MemberDecl = 333 FD->getInstantiatedFromMemberFunction()) 334 return *MemberDecl; 335 336 return D; 337 } 338 if (const auto *VD = dyn_cast<VarDecl>(&D)) { 339 // Static data member is instantiated from a member definition of a class 340 // template? 341 if (VD->isStaticDataMember()) 342 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember()) 343 return *MemberDecl; 344 345 return D; 346 } 347 if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) { 348 // Is this class declaration part of a class template? 349 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate()) 350 return *CTD; 351 352 // Class is an implicit instantiation of a class template or partial 353 // specialization? 354 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) { 355 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation) 356 return D; 357 llvm::PointerUnion<ClassTemplateDecl *, 358 ClassTemplatePartialSpecializationDecl *> 359 PU = CTSD->getSpecializedTemplateOrPartial(); 360 return PU.is<ClassTemplateDecl *>() 361 ? *static_cast<const Decl *>(PU.get<ClassTemplateDecl *>()) 362 : *static_cast<const Decl *>( 363 PU.get<ClassTemplatePartialSpecializationDecl *>()); 364 } 365 366 // Class is instantiated from a member definition of a class template? 367 if (const MemberSpecializationInfo *Info = 368 CRD->getMemberSpecializationInfo()) 369 return *Info->getInstantiatedFrom(); 370 371 return D; 372 } 373 if (const auto *ED = dyn_cast<EnumDecl>(&D)) { 374 // Enum is instantiated from a member definition of a class template? 375 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum()) 376 return *MemberDecl; 377 378 return D; 379 } 380 // FIXME: Adjust alias templates? 381 return D; 382 } 383 384 const RawComment *ASTContext::getRawCommentForAnyRedecl( 385 const Decl *D, 386 const Decl **OriginalDecl) const { 387 if (!D) { 388 if (OriginalDecl) 389 OriginalDecl = nullptr; 390 return nullptr; 391 } 392 393 D = &adjustDeclToTemplate(*D); 394 395 // Any comment directly attached to D? 396 { 397 auto DeclComment = DeclRawComments.find(D); 398 if (DeclComment != DeclRawComments.end()) { 399 if (OriginalDecl) 400 *OriginalDecl = D; 401 return DeclComment->second; 402 } 403 } 404 405 // Any comment attached to any redeclaration of D? 406 const Decl *CanonicalD = D->getCanonicalDecl(); 407 if (!CanonicalD) 408 return nullptr; 409 410 { 411 auto RedeclComment = RedeclChainComments.find(CanonicalD); 412 if (RedeclComment != RedeclChainComments.end()) { 413 if (OriginalDecl) 414 *OriginalDecl = RedeclComment->second; 415 auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second); 416 assert(CommentAtRedecl != DeclRawComments.end() && 417 "This decl is supposed to have comment attached."); 418 return CommentAtRedecl->second; 419 } 420 } 421 422 // Any redeclarations of D that we haven't checked for comments yet? 423 // We can't use DenseMap::iterator directly since it'd get invalid. 424 auto LastCheckedRedecl = [this, CanonicalD]() -> const Decl * { 425 auto LookupRes = CommentlessRedeclChains.find(CanonicalD); 426 if (LookupRes != CommentlessRedeclChains.end()) 427 return LookupRes->second; 428 return nullptr; 429 }(); 430 431 for (const auto Redecl : D->redecls()) { 432 assert(Redecl); 433 // Skip all redeclarations that have been checked previously. 434 if (LastCheckedRedecl) { 435 if (LastCheckedRedecl == Redecl) { 436 LastCheckedRedecl = nullptr; 437 } 438 continue; 439 } 440 const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl); 441 if (RedeclComment) { 442 cacheRawCommentForDecl(*Redecl, *RedeclComment); 443 if (OriginalDecl) 444 *OriginalDecl = Redecl; 445 return RedeclComment; 446 } 447 CommentlessRedeclChains[CanonicalD] = Redecl; 448 } 449 450 if (OriginalDecl) 451 *OriginalDecl = nullptr; 452 return nullptr; 453 } 454 455 void ASTContext::cacheRawCommentForDecl(const Decl &OriginalD, 456 const RawComment &Comment) const { 457 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments); 458 DeclRawComments.try_emplace(&OriginalD, &Comment); 459 const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl(); 460 RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD); 461 CommentlessRedeclChains.erase(CanonicalDecl); 462 } 463 464 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod, 465 SmallVectorImpl<const NamedDecl *> &Redeclared) { 466 const DeclContext *DC = ObjCMethod->getDeclContext(); 467 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) { 468 const ObjCInterfaceDecl *ID = IMD->getClassInterface(); 469 if (!ID) 470 return; 471 // Add redeclared method here. 472 for (const auto *Ext : ID->known_extensions()) { 473 if (ObjCMethodDecl *RedeclaredMethod = 474 Ext->getMethod(ObjCMethod->getSelector(), 475 ObjCMethod->isInstanceMethod())) 476 Redeclared.push_back(RedeclaredMethod); 477 } 478 } 479 } 480 481 void ASTContext::attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls, 482 const Preprocessor *PP) { 483 if (Comments.empty() || Decls.empty()) 484 return; 485 486 FileID File; 487 for (Decl *D : Decls) { 488 SourceLocation Loc = D->getLocation(); 489 if (Loc.isValid()) { 490 // See if there are any new comments that are not attached to a decl. 491 // The location doesn't have to be precise - we care only about the file. 492 File = SourceMgr.getDecomposedLoc(Loc).first; 493 break; 494 } 495 } 496 497 if (File.isInvalid()) 498 return; 499 500 auto CommentsInThisFile = Comments.getCommentsInFile(File); 501 if (!CommentsInThisFile || CommentsInThisFile->empty() || 502 CommentsInThisFile->rbegin()->second->isAttached()) 503 return; 504 505 // There is at least one comment not attached to a decl. 506 // Maybe it should be attached to one of Decls? 507 // 508 // Note that this way we pick up not only comments that precede the 509 // declaration, but also comments that *follow* the declaration -- thanks to 510 // the lookahead in the lexer: we've consumed the semicolon and looked 511 // ahead through comments. 512 513 for (const Decl *D : Decls) { 514 assert(D); 515 if (D->isInvalidDecl()) 516 continue; 517 518 D = &adjustDeclToTemplate(*D); 519 520 const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr); 521 522 if (DeclLoc.isInvalid() || !DeclLoc.isFileID()) 523 continue; 524 525 if (DeclRawComments.count(D) > 0) 526 continue; 527 528 if (RawComment *const DocComment = 529 getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile)) { 530 cacheRawCommentForDecl(*D, *DocComment); 531 comments::FullComment *FC = DocComment->parse(*this, PP, D); 532 ParsedComments[D->getCanonicalDecl()] = FC; 533 } 534 } 535 } 536 537 comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC, 538 const Decl *D) const { 539 auto *ThisDeclInfo = new (*this) comments::DeclInfo; 540 ThisDeclInfo->CommentDecl = D; 541 ThisDeclInfo->IsFilled = false; 542 ThisDeclInfo->fill(); 543 ThisDeclInfo->CommentDecl = FC->getDecl(); 544 if (!ThisDeclInfo->TemplateParameters) 545 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters; 546 comments::FullComment *CFC = 547 new (*this) comments::FullComment(FC->getBlocks(), 548 ThisDeclInfo); 549 return CFC; 550 } 551 552 comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const { 553 const RawComment *RC = getRawCommentForDeclNoCache(D); 554 return RC ? RC->parse(*this, nullptr, D) : nullptr; 555 } 556 557 comments::FullComment *ASTContext::getCommentForDecl( 558 const Decl *D, 559 const Preprocessor *PP) const { 560 if (!D || D->isInvalidDecl()) 561 return nullptr; 562 D = &adjustDeclToTemplate(*D); 563 564 const Decl *Canonical = D->getCanonicalDecl(); 565 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos = 566 ParsedComments.find(Canonical); 567 568 if (Pos != ParsedComments.end()) { 569 if (Canonical != D) { 570 comments::FullComment *FC = Pos->second; 571 comments::FullComment *CFC = cloneFullComment(FC, D); 572 return CFC; 573 } 574 return Pos->second; 575 } 576 577 const Decl *OriginalDecl = nullptr; 578 579 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl); 580 if (!RC) { 581 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) { 582 SmallVector<const NamedDecl*, 8> Overridden; 583 const auto *OMD = dyn_cast<ObjCMethodDecl>(D); 584 if (OMD && OMD->isPropertyAccessor()) 585 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl()) 586 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP)) 587 return cloneFullComment(FC, D); 588 if (OMD) 589 addRedeclaredMethods(OMD, Overridden); 590 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden); 591 for (unsigned i = 0, e = Overridden.size(); i < e; i++) 592 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP)) 593 return cloneFullComment(FC, D); 594 } 595 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) { 596 // Attach any tag type's documentation to its typedef if latter 597 // does not have one of its own. 598 QualType QT = TD->getUnderlyingType(); 599 if (const auto *TT = QT->getAs<TagType>()) 600 if (const Decl *TD = TT->getDecl()) 601 if (comments::FullComment *FC = getCommentForDecl(TD, PP)) 602 return cloneFullComment(FC, D); 603 } 604 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) { 605 while (IC->getSuperClass()) { 606 IC = IC->getSuperClass(); 607 if (comments::FullComment *FC = getCommentForDecl(IC, PP)) 608 return cloneFullComment(FC, D); 609 } 610 } 611 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) { 612 if (const ObjCInterfaceDecl *IC = CD->getClassInterface()) 613 if (comments::FullComment *FC = getCommentForDecl(IC, PP)) 614 return cloneFullComment(FC, D); 615 } 616 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) { 617 if (!(RD = RD->getDefinition())) 618 return nullptr; 619 // Check non-virtual bases. 620 for (const auto &I : RD->bases()) { 621 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public)) 622 continue; 623 QualType Ty = I.getType(); 624 if (Ty.isNull()) 625 continue; 626 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) { 627 if (!(NonVirtualBase= NonVirtualBase->getDefinition())) 628 continue; 629 630 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP)) 631 return cloneFullComment(FC, D); 632 } 633 } 634 // Check virtual bases. 635 for (const auto &I : RD->vbases()) { 636 if (I.getAccessSpecifier() != AS_public) 637 continue; 638 QualType Ty = I.getType(); 639 if (Ty.isNull()) 640 continue; 641 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) { 642 if (!(VirtualBase= VirtualBase->getDefinition())) 643 continue; 644 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP)) 645 return cloneFullComment(FC, D); 646 } 647 } 648 } 649 return nullptr; 650 } 651 652 // If the RawComment was attached to other redeclaration of this Decl, we 653 // should parse the comment in context of that other Decl. This is important 654 // because comments can contain references to parameter names which can be 655 // different across redeclarations. 656 if (D != OriginalDecl && OriginalDecl) 657 return getCommentForDecl(OriginalDecl, PP); 658 659 comments::FullComment *FC = RC->parse(*this, PP, D); 660 ParsedComments[Canonical] = FC; 661 return FC; 662 } 663 664 void 665 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID, 666 const ASTContext &C, 667 TemplateTemplateParmDecl *Parm) { 668 ID.AddInteger(Parm->getDepth()); 669 ID.AddInteger(Parm->getPosition()); 670 ID.AddBoolean(Parm->isParameterPack()); 671 672 TemplateParameterList *Params = Parm->getTemplateParameters(); 673 ID.AddInteger(Params->size()); 674 for (TemplateParameterList::const_iterator P = Params->begin(), 675 PEnd = Params->end(); 676 P != PEnd; ++P) { 677 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { 678 ID.AddInteger(0); 679 ID.AddBoolean(TTP->isParameterPack()); 680 const TypeConstraint *TC = TTP->getTypeConstraint(); 681 ID.AddBoolean(TC != nullptr); 682 if (TC) 683 TC->getImmediatelyDeclaredConstraint()->Profile(ID, C, 684 /*Canonical=*/true); 685 if (TTP->isExpandedParameterPack()) { 686 ID.AddBoolean(true); 687 ID.AddInteger(TTP->getNumExpansionParameters()); 688 } else 689 ID.AddBoolean(false); 690 continue; 691 } 692 693 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 694 ID.AddInteger(1); 695 ID.AddBoolean(NTTP->isParameterPack()); 696 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr()); 697 if (NTTP->isExpandedParameterPack()) { 698 ID.AddBoolean(true); 699 ID.AddInteger(NTTP->getNumExpansionTypes()); 700 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { 701 QualType T = NTTP->getExpansionType(I); 702 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr()); 703 } 704 } else 705 ID.AddBoolean(false); 706 continue; 707 } 708 709 auto *TTP = cast<TemplateTemplateParmDecl>(*P); 710 ID.AddInteger(2); 711 Profile(ID, C, TTP); 712 } 713 Expr *RequiresClause = Parm->getTemplateParameters()->getRequiresClause(); 714 ID.AddBoolean(RequiresClause != nullptr); 715 if (RequiresClause) 716 RequiresClause->Profile(ID, C, /*Canonical=*/true); 717 } 718 719 static Expr * 720 canonicalizeImmediatelyDeclaredConstraint(const ASTContext &C, Expr *IDC, 721 QualType ConstrainedType) { 722 // This is a bit ugly - we need to form a new immediately-declared 723 // constraint that references the new parameter; this would ideally 724 // require semantic analysis (e.g. template<C T> struct S {}; - the 725 // converted arguments of C<T> could be an argument pack if C is 726 // declared as template<typename... T> concept C = ...). 727 // We don't have semantic analysis here so we dig deep into the 728 // ready-made constraint expr and change the thing manually. 729 ConceptSpecializationExpr *CSE; 730 if (const auto *Fold = dyn_cast<CXXFoldExpr>(IDC)) 731 CSE = cast<ConceptSpecializationExpr>(Fold->getLHS()); 732 else 733 CSE = cast<ConceptSpecializationExpr>(IDC); 734 ArrayRef<TemplateArgument> OldConverted = CSE->getTemplateArguments(); 735 SmallVector<TemplateArgument, 3> NewConverted; 736 NewConverted.reserve(OldConverted.size()); 737 if (OldConverted.front().getKind() == TemplateArgument::Pack) { 738 // The case: 739 // template<typename... T> concept C = true; 740 // template<C<int> T> struct S; -> constraint is C<{T, int}> 741 NewConverted.push_back(ConstrainedType); 742 llvm::append_range(NewConverted, 743 OldConverted.front().pack_elements().drop_front(1)); 744 TemplateArgument NewPack(NewConverted); 745 746 NewConverted.clear(); 747 NewConverted.push_back(NewPack); 748 assert(OldConverted.size() == 1 && 749 "Template parameter pack should be the last parameter"); 750 } else { 751 assert(OldConverted.front().getKind() == TemplateArgument::Type && 752 "Unexpected first argument kind for immediately-declared " 753 "constraint"); 754 NewConverted.push_back(ConstrainedType); 755 llvm::append_range(NewConverted, OldConverted.drop_front(1)); 756 } 757 Expr *NewIDC = ConceptSpecializationExpr::Create( 758 C, CSE->getNamedConcept(), NewConverted, nullptr, 759 CSE->isInstantiationDependent(), CSE->containsUnexpandedParameterPack()); 760 761 if (auto *OrigFold = dyn_cast<CXXFoldExpr>(IDC)) 762 NewIDC = new (C) CXXFoldExpr( 763 OrigFold->getType(), /*Callee*/nullptr, SourceLocation(), NewIDC, 764 BinaryOperatorKind::BO_LAnd, SourceLocation(), /*RHS=*/nullptr, 765 SourceLocation(), /*NumExpansions=*/None); 766 return NewIDC; 767 } 768 769 TemplateTemplateParmDecl * 770 ASTContext::getCanonicalTemplateTemplateParmDecl( 771 TemplateTemplateParmDecl *TTP) const { 772 // Check if we already have a canonical template template parameter. 773 llvm::FoldingSetNodeID ID; 774 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP); 775 void *InsertPos = nullptr; 776 CanonicalTemplateTemplateParm *Canonical 777 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 778 if (Canonical) 779 return Canonical->getParam(); 780 781 // Build a canonical template parameter list. 782 TemplateParameterList *Params = TTP->getTemplateParameters(); 783 SmallVector<NamedDecl *, 4> CanonParams; 784 CanonParams.reserve(Params->size()); 785 for (TemplateParameterList::const_iterator P = Params->begin(), 786 PEnd = Params->end(); 787 P != PEnd; ++P) { 788 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { 789 TemplateTypeParmDecl *NewTTP = TemplateTypeParmDecl::Create(*this, 790 getTranslationUnitDecl(), SourceLocation(), SourceLocation(), 791 TTP->getDepth(), TTP->getIndex(), nullptr, false, 792 TTP->isParameterPack(), TTP->hasTypeConstraint(), 793 TTP->isExpandedParameterPack() ? 794 llvm::Optional<unsigned>(TTP->getNumExpansionParameters()) : None); 795 if (const auto *TC = TTP->getTypeConstraint()) { 796 QualType ParamAsArgument(NewTTP->getTypeForDecl(), 0); 797 Expr *NewIDC = canonicalizeImmediatelyDeclaredConstraint( 798 *this, TC->getImmediatelyDeclaredConstraint(), 799 ParamAsArgument); 800 TemplateArgumentListInfo CanonArgsAsWritten; 801 if (auto *Args = TC->getTemplateArgsAsWritten()) 802 for (const auto &ArgLoc : Args->arguments()) 803 CanonArgsAsWritten.addArgument( 804 TemplateArgumentLoc(ArgLoc.getArgument(), 805 TemplateArgumentLocInfo())); 806 NewTTP->setTypeConstraint( 807 NestedNameSpecifierLoc(), 808 DeclarationNameInfo(TC->getNamedConcept()->getDeclName(), 809 SourceLocation()), /*FoundDecl=*/nullptr, 810 // Actually canonicalizing a TemplateArgumentLoc is difficult so we 811 // simply omit the ArgsAsWritten 812 TC->getNamedConcept(), /*ArgsAsWritten=*/nullptr, NewIDC); 813 } 814 CanonParams.push_back(NewTTP); 815 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 816 QualType T = getCanonicalType(NTTP->getType()); 817 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); 818 NonTypeTemplateParmDecl *Param; 819 if (NTTP->isExpandedParameterPack()) { 820 SmallVector<QualType, 2> ExpandedTypes; 821 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos; 822 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { 823 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I))); 824 ExpandedTInfos.push_back( 825 getTrivialTypeSourceInfo(ExpandedTypes.back())); 826 } 827 828 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 829 SourceLocation(), 830 SourceLocation(), 831 NTTP->getDepth(), 832 NTTP->getPosition(), nullptr, 833 T, 834 TInfo, 835 ExpandedTypes, 836 ExpandedTInfos); 837 } else { 838 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 839 SourceLocation(), 840 SourceLocation(), 841 NTTP->getDepth(), 842 NTTP->getPosition(), nullptr, 843 T, 844 NTTP->isParameterPack(), 845 TInfo); 846 } 847 if (AutoType *AT = T->getContainedAutoType()) { 848 if (AT->isConstrained()) { 849 Param->setPlaceholderTypeConstraint( 850 canonicalizeImmediatelyDeclaredConstraint( 851 *this, NTTP->getPlaceholderTypeConstraint(), T)); 852 } 853 } 854 CanonParams.push_back(Param); 855 856 } else 857 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl( 858 cast<TemplateTemplateParmDecl>(*P))); 859 } 860 861 Expr *CanonRequiresClause = nullptr; 862 if (Expr *RequiresClause = TTP->getTemplateParameters()->getRequiresClause()) 863 CanonRequiresClause = RequiresClause; 864 865 TemplateTemplateParmDecl *CanonTTP 866 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 867 SourceLocation(), TTP->getDepth(), 868 TTP->getPosition(), 869 TTP->isParameterPack(), 870 nullptr, 871 TemplateParameterList::Create(*this, SourceLocation(), 872 SourceLocation(), 873 CanonParams, 874 SourceLocation(), 875 CanonRequiresClause)); 876 877 // Get the new insert position for the node we care about. 878 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 879 assert(!Canonical && "Shouldn't be in the map!"); 880 (void)Canonical; 881 882 // Create the canonical template template parameter entry. 883 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP); 884 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos); 885 return CanonTTP; 886 } 887 888 TargetCXXABI::Kind ASTContext::getCXXABIKind() const { 889 auto Kind = getTargetInfo().getCXXABI().getKind(); 890 return getLangOpts().CXXABI.getValueOr(Kind); 891 } 892 893 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) { 894 if (!LangOpts.CPlusPlus) return nullptr; 895 896 switch (getCXXABIKind()) { 897 case TargetCXXABI::AppleARM64: 898 case TargetCXXABI::Fuchsia: 899 case TargetCXXABI::GenericARM: // Same as Itanium at this level 900 case TargetCXXABI::iOS: 901 case TargetCXXABI::WatchOS: 902 case TargetCXXABI::GenericAArch64: 903 case TargetCXXABI::GenericMIPS: 904 case TargetCXXABI::GenericItanium: 905 case TargetCXXABI::WebAssembly: 906 case TargetCXXABI::XL: 907 return CreateItaniumCXXABI(*this); 908 case TargetCXXABI::Microsoft: 909 return CreateMicrosoftCXXABI(*this); 910 } 911 llvm_unreachable("Invalid CXXABI type!"); 912 } 913 914 interp::Context &ASTContext::getInterpContext() { 915 if (!InterpContext) { 916 InterpContext.reset(new interp::Context(*this)); 917 } 918 return *InterpContext.get(); 919 } 920 921 ParentMapContext &ASTContext::getParentMapContext() { 922 if (!ParentMapCtx) 923 ParentMapCtx.reset(new ParentMapContext(*this)); 924 return *ParentMapCtx.get(); 925 } 926 927 static const LangASMap *getAddressSpaceMap(const TargetInfo &T, 928 const LangOptions &LOpts) { 929 if (LOpts.FakeAddressSpaceMap) { 930 // The fake address space map must have a distinct entry for each 931 // language-specific address space. 932 static const unsigned FakeAddrSpaceMap[] = { 933 0, // Default 934 1, // opencl_global 935 3, // opencl_local 936 2, // opencl_constant 937 0, // opencl_private 938 4, // opencl_generic 939 5, // opencl_global_device 940 6, // opencl_global_host 941 7, // cuda_device 942 8, // cuda_constant 943 9, // cuda_shared 944 1, // sycl_global 945 5, // sycl_global_device 946 6, // sycl_global_host 947 3, // sycl_local 948 0, // sycl_private 949 10, // ptr32_sptr 950 11, // ptr32_uptr 951 12 // ptr64 952 }; 953 return &FakeAddrSpaceMap; 954 } else { 955 return &T.getAddressSpaceMap(); 956 } 957 } 958 959 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI, 960 const LangOptions &LangOpts) { 961 switch (LangOpts.getAddressSpaceMapMangling()) { 962 case LangOptions::ASMM_Target: 963 return TI.useAddressSpaceMapMangling(); 964 case LangOptions::ASMM_On: 965 return true; 966 case LangOptions::ASMM_Off: 967 return false; 968 } 969 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything."); 970 } 971 972 ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM, 973 IdentifierTable &idents, SelectorTable &sels, 974 Builtin::Context &builtins, TranslationUnitKind TUKind) 975 : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize), 976 FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize), 977 TemplateSpecializationTypes(this_()), 978 DependentTemplateSpecializationTypes(this_()), AutoTypes(this_()), 979 SubstTemplateTemplateParmPacks(this_()), 980 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts), 981 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)), 982 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles, 983 LangOpts.XRayNeverInstrumentFiles, 984 LangOpts.XRayAttrListFiles, SM)), 985 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)), 986 PrintingPolicy(LOpts), Idents(idents), Selectors(sels), 987 BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this), 988 Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), 989 CompCategories(this_()), LastSDM(nullptr, 0) { 990 addTranslationUnitDecl(); 991 } 992 993 void ASTContext::cleanup() { 994 // Release the DenseMaps associated with DeclContext objects. 995 // FIXME: Is this the ideal solution? 996 ReleaseDeclContextMaps(); 997 998 // Call all of the deallocation functions on all of their targets. 999 for (auto &Pair : Deallocations) 1000 (Pair.first)(Pair.second); 1001 Deallocations.clear(); 1002 1003 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed 1004 // because they can contain DenseMaps. 1005 for (llvm::DenseMap<const ObjCContainerDecl*, 1006 const ASTRecordLayout*>::iterator 1007 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) 1008 // Increment in loop to prevent using deallocated memory. 1009 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second)) 1010 R->Destroy(*this); 1011 ObjCLayouts.clear(); 1012 1013 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator 1014 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) { 1015 // Increment in loop to prevent using deallocated memory. 1016 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second)) 1017 R->Destroy(*this); 1018 } 1019 ASTRecordLayouts.clear(); 1020 1021 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(), 1022 AEnd = DeclAttrs.end(); 1023 A != AEnd; ++A) 1024 A->second->~AttrVec(); 1025 DeclAttrs.clear(); 1026 1027 for (const auto &Value : ModuleInitializers) 1028 Value.second->~PerModuleInitializers(); 1029 ModuleInitializers.clear(); 1030 } 1031 1032 ASTContext::~ASTContext() { cleanup(); } 1033 1034 void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) { 1035 TraversalScope = TopLevelDecls; 1036 getParentMapContext().clear(); 1037 } 1038 1039 void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const { 1040 Deallocations.push_back({Callback, Data}); 1041 } 1042 1043 void 1044 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) { 1045 ExternalSource = std::move(Source); 1046 } 1047 1048 void ASTContext::PrintStats() const { 1049 llvm::errs() << "\n*** AST Context Stats:\n"; 1050 llvm::errs() << " " << Types.size() << " types total.\n"; 1051 1052 unsigned counts[] = { 1053 #define TYPE(Name, Parent) 0, 1054 #define ABSTRACT_TYPE(Name, Parent) 1055 #include "clang/AST/TypeNodes.inc" 1056 0 // Extra 1057 }; 1058 1059 for (unsigned i = 0, e = Types.size(); i != e; ++i) { 1060 Type *T = Types[i]; 1061 counts[(unsigned)T->getTypeClass()]++; 1062 } 1063 1064 unsigned Idx = 0; 1065 unsigned TotalBytes = 0; 1066 #define TYPE(Name, Parent) \ 1067 if (counts[Idx]) \ 1068 llvm::errs() << " " << counts[Idx] << " " << #Name \ 1069 << " types, " << sizeof(Name##Type) << " each " \ 1070 << "(" << counts[Idx] * sizeof(Name##Type) \ 1071 << " bytes)\n"; \ 1072 TotalBytes += counts[Idx] * sizeof(Name##Type); \ 1073 ++Idx; 1074 #define ABSTRACT_TYPE(Name, Parent) 1075 #include "clang/AST/TypeNodes.inc" 1076 1077 llvm::errs() << "Total bytes = " << TotalBytes << "\n"; 1078 1079 // Implicit special member functions. 1080 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/" 1081 << NumImplicitDefaultConstructors 1082 << " implicit default constructors created\n"; 1083 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/" 1084 << NumImplicitCopyConstructors 1085 << " implicit copy constructors created\n"; 1086 if (getLangOpts().CPlusPlus) 1087 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/" 1088 << NumImplicitMoveConstructors 1089 << " implicit move constructors created\n"; 1090 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/" 1091 << NumImplicitCopyAssignmentOperators 1092 << " implicit copy assignment operators created\n"; 1093 if (getLangOpts().CPlusPlus) 1094 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/" 1095 << NumImplicitMoveAssignmentOperators 1096 << " implicit move assignment operators created\n"; 1097 llvm::errs() << NumImplicitDestructorsDeclared << "/" 1098 << NumImplicitDestructors 1099 << " implicit destructors created\n"; 1100 1101 if (ExternalSource) { 1102 llvm::errs() << "\n"; 1103 ExternalSource->PrintStats(); 1104 } 1105 1106 BumpAlloc.PrintStats(); 1107 } 1108 1109 void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M, 1110 bool NotifyListeners) { 1111 if (NotifyListeners) 1112 if (auto *Listener = getASTMutationListener()) 1113 Listener->RedefinedHiddenDefinition(ND, M); 1114 1115 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M); 1116 } 1117 1118 void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) { 1119 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl())); 1120 if (It == MergedDefModules.end()) 1121 return; 1122 1123 auto &Merged = It->second; 1124 llvm::DenseSet<Module*> Found; 1125 for (Module *&M : Merged) 1126 if (!Found.insert(M).second) 1127 M = nullptr; 1128 llvm::erase_value(Merged, nullptr); 1129 } 1130 1131 ArrayRef<Module *> 1132 ASTContext::getModulesWithMergedDefinition(const NamedDecl *Def) { 1133 auto MergedIt = 1134 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl())); 1135 if (MergedIt == MergedDefModules.end()) 1136 return None; 1137 return MergedIt->second; 1138 } 1139 1140 void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) { 1141 if (LazyInitializers.empty()) 1142 return; 1143 1144 auto *Source = Ctx.getExternalSource(); 1145 assert(Source && "lazy initializers but no external source"); 1146 1147 auto LazyInits = std::move(LazyInitializers); 1148 LazyInitializers.clear(); 1149 1150 for (auto ID : LazyInits) 1151 Initializers.push_back(Source->GetExternalDecl(ID)); 1152 1153 assert(LazyInitializers.empty() && 1154 "GetExternalDecl for lazy module initializer added more inits"); 1155 } 1156 1157 void ASTContext::addModuleInitializer(Module *M, Decl *D) { 1158 // One special case: if we add a module initializer that imports another 1159 // module, and that module's only initializer is an ImportDecl, simplify. 1160 if (const auto *ID = dyn_cast<ImportDecl>(D)) { 1161 auto It = ModuleInitializers.find(ID->getImportedModule()); 1162 1163 // Maybe the ImportDecl does nothing at all. (Common case.) 1164 if (It == ModuleInitializers.end()) 1165 return; 1166 1167 // Maybe the ImportDecl only imports another ImportDecl. 1168 auto &Imported = *It->second; 1169 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) { 1170 Imported.resolve(*this); 1171 auto *OnlyDecl = Imported.Initializers.front(); 1172 if (isa<ImportDecl>(OnlyDecl)) 1173 D = OnlyDecl; 1174 } 1175 } 1176 1177 auto *&Inits = ModuleInitializers[M]; 1178 if (!Inits) 1179 Inits = new (*this) PerModuleInitializers; 1180 Inits->Initializers.push_back(D); 1181 } 1182 1183 void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) { 1184 auto *&Inits = ModuleInitializers[M]; 1185 if (!Inits) 1186 Inits = new (*this) PerModuleInitializers; 1187 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(), 1188 IDs.begin(), IDs.end()); 1189 } 1190 1191 ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) { 1192 auto It = ModuleInitializers.find(M); 1193 if (It == ModuleInitializers.end()) 1194 return None; 1195 1196 auto *Inits = It->second; 1197 Inits->resolve(*this); 1198 return Inits->Initializers; 1199 } 1200 1201 ExternCContextDecl *ASTContext::getExternCContextDecl() const { 1202 if (!ExternCContext) 1203 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl()); 1204 1205 return ExternCContext; 1206 } 1207 1208 BuiltinTemplateDecl * 1209 ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK, 1210 const IdentifierInfo *II) const { 1211 auto *BuiltinTemplate = 1212 BuiltinTemplateDecl::Create(*this, getTranslationUnitDecl(), II, BTK); 1213 BuiltinTemplate->setImplicit(); 1214 getTranslationUnitDecl()->addDecl(BuiltinTemplate); 1215 1216 return BuiltinTemplate; 1217 } 1218 1219 BuiltinTemplateDecl * 1220 ASTContext::getMakeIntegerSeqDecl() const { 1221 if (!MakeIntegerSeqDecl) 1222 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq, 1223 getMakeIntegerSeqName()); 1224 return MakeIntegerSeqDecl; 1225 } 1226 1227 BuiltinTemplateDecl * 1228 ASTContext::getTypePackElementDecl() const { 1229 if (!TypePackElementDecl) 1230 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element, 1231 getTypePackElementName()); 1232 return TypePackElementDecl; 1233 } 1234 1235 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name, 1236 RecordDecl::TagKind TK) const { 1237 SourceLocation Loc; 1238 RecordDecl *NewDecl; 1239 if (getLangOpts().CPlusPlus) 1240 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, 1241 Loc, &Idents.get(Name)); 1242 else 1243 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc, 1244 &Idents.get(Name)); 1245 NewDecl->setImplicit(); 1246 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit( 1247 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default)); 1248 return NewDecl; 1249 } 1250 1251 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T, 1252 StringRef Name) const { 1253 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); 1254 TypedefDecl *NewDecl = TypedefDecl::Create( 1255 const_cast<ASTContext &>(*this), getTranslationUnitDecl(), 1256 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo); 1257 NewDecl->setImplicit(); 1258 return NewDecl; 1259 } 1260 1261 TypedefDecl *ASTContext::getInt128Decl() const { 1262 if (!Int128Decl) 1263 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t"); 1264 return Int128Decl; 1265 } 1266 1267 TypedefDecl *ASTContext::getUInt128Decl() const { 1268 if (!UInt128Decl) 1269 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t"); 1270 return UInt128Decl; 1271 } 1272 1273 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) { 1274 auto *Ty = new (*this, TypeAlignment) BuiltinType(K); 1275 R = CanQualType::CreateUnsafe(QualType(Ty, 0)); 1276 Types.push_back(Ty); 1277 } 1278 1279 void ASTContext::InitBuiltinTypes(const TargetInfo &Target, 1280 const TargetInfo *AuxTarget) { 1281 assert((!this->Target || this->Target == &Target) && 1282 "Incorrect target reinitialization"); 1283 assert(VoidTy.isNull() && "Context reinitialized?"); 1284 1285 this->Target = &Target; 1286 this->AuxTarget = AuxTarget; 1287 1288 ABI.reset(createCXXABI(Target)); 1289 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts); 1290 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts); 1291 1292 // C99 6.2.5p19. 1293 InitBuiltinType(VoidTy, BuiltinType::Void); 1294 1295 // C99 6.2.5p2. 1296 InitBuiltinType(BoolTy, BuiltinType::Bool); 1297 // C99 6.2.5p3. 1298 if (LangOpts.CharIsSigned) 1299 InitBuiltinType(CharTy, BuiltinType::Char_S); 1300 else 1301 InitBuiltinType(CharTy, BuiltinType::Char_U); 1302 // C99 6.2.5p4. 1303 InitBuiltinType(SignedCharTy, BuiltinType::SChar); 1304 InitBuiltinType(ShortTy, BuiltinType::Short); 1305 InitBuiltinType(IntTy, BuiltinType::Int); 1306 InitBuiltinType(LongTy, BuiltinType::Long); 1307 InitBuiltinType(LongLongTy, BuiltinType::LongLong); 1308 1309 // C99 6.2.5p6. 1310 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar); 1311 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort); 1312 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt); 1313 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong); 1314 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong); 1315 1316 // C99 6.2.5p10. 1317 InitBuiltinType(FloatTy, BuiltinType::Float); 1318 InitBuiltinType(DoubleTy, BuiltinType::Double); 1319 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble); 1320 1321 // GNU extension, __float128 for IEEE quadruple precision 1322 InitBuiltinType(Float128Ty, BuiltinType::Float128); 1323 1324 // __ibm128 for IBM extended precision 1325 InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128); 1326 1327 // C11 extension ISO/IEC TS 18661-3 1328 InitBuiltinType(Float16Ty, BuiltinType::Float16); 1329 1330 // ISO/IEC JTC1 SC22 WG14 N1169 Extension 1331 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum); 1332 InitBuiltinType(AccumTy, BuiltinType::Accum); 1333 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum); 1334 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum); 1335 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum); 1336 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum); 1337 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract); 1338 InitBuiltinType(FractTy, BuiltinType::Fract); 1339 InitBuiltinType(LongFractTy, BuiltinType::LongFract); 1340 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract); 1341 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract); 1342 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract); 1343 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum); 1344 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum); 1345 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum); 1346 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum); 1347 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum); 1348 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum); 1349 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract); 1350 InitBuiltinType(SatFractTy, BuiltinType::SatFract); 1351 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract); 1352 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract); 1353 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract); 1354 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract); 1355 1356 // GNU extension, 128-bit integers. 1357 InitBuiltinType(Int128Ty, BuiltinType::Int128); 1358 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128); 1359 1360 // C++ 3.9.1p5 1361 if (TargetInfo::isTypeSigned(Target.getWCharType())) 1362 InitBuiltinType(WCharTy, BuiltinType::WChar_S); 1363 else // -fshort-wchar makes wchar_t be unsigned. 1364 InitBuiltinType(WCharTy, BuiltinType::WChar_U); 1365 if (LangOpts.CPlusPlus && LangOpts.WChar) 1366 WideCharTy = WCharTy; 1367 else { 1368 // C99 (or C++ using -fno-wchar). 1369 WideCharTy = getFromTargetType(Target.getWCharType()); 1370 } 1371 1372 WIntTy = getFromTargetType(Target.getWIntType()); 1373 1374 // C++20 (proposed) 1375 InitBuiltinType(Char8Ty, BuiltinType::Char8); 1376 1377 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 1378 InitBuiltinType(Char16Ty, BuiltinType::Char16); 1379 else // C99 1380 Char16Ty = getFromTargetType(Target.getChar16Type()); 1381 1382 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 1383 InitBuiltinType(Char32Ty, BuiltinType::Char32); 1384 else // C99 1385 Char32Ty = getFromTargetType(Target.getChar32Type()); 1386 1387 // Placeholder type for type-dependent expressions whose type is 1388 // completely unknown. No code should ever check a type against 1389 // DependentTy and users should never see it; however, it is here to 1390 // help diagnose failures to properly check for type-dependent 1391 // expressions. 1392 InitBuiltinType(DependentTy, BuiltinType::Dependent); 1393 1394 // Placeholder type for functions. 1395 InitBuiltinType(OverloadTy, BuiltinType::Overload); 1396 1397 // Placeholder type for bound members. 1398 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember); 1399 1400 // Placeholder type for pseudo-objects. 1401 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject); 1402 1403 // "any" type; useful for debugger-like clients. 1404 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny); 1405 1406 // Placeholder type for unbridged ARC casts. 1407 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast); 1408 1409 // Placeholder type for builtin functions. 1410 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn); 1411 1412 // Placeholder type for OMP array sections. 1413 if (LangOpts.OpenMP) { 1414 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection); 1415 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping); 1416 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator); 1417 } 1418 if (LangOpts.MatrixTypes) 1419 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx); 1420 1421 // Builtin types for 'id', 'Class', and 'SEL'. 1422 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId); 1423 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass); 1424 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel); 1425 1426 if (LangOpts.OpenCL) { 1427 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 1428 InitBuiltinType(SingletonId, BuiltinType::Id); 1429 #include "clang/Basic/OpenCLImageTypes.def" 1430 1431 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler); 1432 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent); 1433 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent); 1434 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue); 1435 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID); 1436 1437 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 1438 InitBuiltinType(Id##Ty, BuiltinType::Id); 1439 #include "clang/Basic/OpenCLExtensionTypes.def" 1440 } 1441 1442 if (Target.hasAArch64SVETypes()) { 1443 #define SVE_TYPE(Name, Id, SingletonId) \ 1444 InitBuiltinType(SingletonId, BuiltinType::Id); 1445 #include "clang/Basic/AArch64SVEACLETypes.def" 1446 } 1447 1448 if (Target.getTriple().isPPC64()) { 1449 #define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \ 1450 InitBuiltinType(Id##Ty, BuiltinType::Id); 1451 #include "clang/Basic/PPCTypes.def" 1452 #define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \ 1453 InitBuiltinType(Id##Ty, BuiltinType::Id); 1454 #include "clang/Basic/PPCTypes.def" 1455 } 1456 1457 if (Target.hasRISCVVTypes()) { 1458 #define RVV_TYPE(Name, Id, SingletonId) \ 1459 InitBuiltinType(SingletonId, BuiltinType::Id); 1460 #include "clang/Basic/RISCVVTypes.def" 1461 } 1462 1463 // Builtin type for __objc_yes and __objc_no 1464 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ? 1465 SignedCharTy : BoolTy); 1466 1467 ObjCConstantStringType = QualType(); 1468 1469 ObjCSuperType = QualType(); 1470 1471 // void * type 1472 if (LangOpts.OpenCLGenericAddressSpace) { 1473 auto Q = VoidTy.getQualifiers(); 1474 Q.setAddressSpace(LangAS::opencl_generic); 1475 VoidPtrTy = getPointerType(getCanonicalType( 1476 getQualifiedType(VoidTy.getUnqualifiedType(), Q))); 1477 } else { 1478 VoidPtrTy = getPointerType(VoidTy); 1479 } 1480 1481 // nullptr type (C++0x 2.14.7) 1482 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr); 1483 1484 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16 1485 InitBuiltinType(HalfTy, BuiltinType::Half); 1486 1487 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16); 1488 1489 // Builtin type used to help define __builtin_va_list. 1490 VaListTagDecl = nullptr; 1491 1492 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls. 1493 if (LangOpts.MicrosoftExt || LangOpts.Borland) { 1494 MSGuidTagDecl = buildImplicitRecord("_GUID"); 1495 getTranslationUnitDecl()->addDecl(MSGuidTagDecl); 1496 } 1497 } 1498 1499 DiagnosticsEngine &ASTContext::getDiagnostics() const { 1500 return SourceMgr.getDiagnostics(); 1501 } 1502 1503 AttrVec& ASTContext::getDeclAttrs(const Decl *D) { 1504 AttrVec *&Result = DeclAttrs[D]; 1505 if (!Result) { 1506 void *Mem = Allocate(sizeof(AttrVec)); 1507 Result = new (Mem) AttrVec; 1508 } 1509 1510 return *Result; 1511 } 1512 1513 /// Erase the attributes corresponding to the given declaration. 1514 void ASTContext::eraseDeclAttrs(const Decl *D) { 1515 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D); 1516 if (Pos != DeclAttrs.end()) { 1517 Pos->second->~AttrVec(); 1518 DeclAttrs.erase(Pos); 1519 } 1520 } 1521 1522 // FIXME: Remove ? 1523 MemberSpecializationInfo * 1524 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) { 1525 assert(Var->isStaticDataMember() && "Not a static data member"); 1526 return getTemplateOrSpecializationInfo(Var) 1527 .dyn_cast<MemberSpecializationInfo *>(); 1528 } 1529 1530 ASTContext::TemplateOrSpecializationInfo 1531 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) { 1532 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos = 1533 TemplateOrInstantiation.find(Var); 1534 if (Pos == TemplateOrInstantiation.end()) 1535 return {}; 1536 1537 return Pos->second; 1538 } 1539 1540 void 1541 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, 1542 TemplateSpecializationKind TSK, 1543 SourceLocation PointOfInstantiation) { 1544 assert(Inst->isStaticDataMember() && "Not a static data member"); 1545 assert(Tmpl->isStaticDataMember() && "Not a static data member"); 1546 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo( 1547 Tmpl, TSK, PointOfInstantiation)); 1548 } 1549 1550 void 1551 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst, 1552 TemplateOrSpecializationInfo TSI) { 1553 assert(!TemplateOrInstantiation[Inst] && 1554 "Already noted what the variable was instantiated from"); 1555 TemplateOrInstantiation[Inst] = TSI; 1556 } 1557 1558 NamedDecl * 1559 ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) { 1560 auto Pos = InstantiatedFromUsingDecl.find(UUD); 1561 if (Pos == InstantiatedFromUsingDecl.end()) 1562 return nullptr; 1563 1564 return Pos->second; 1565 } 1566 1567 void 1568 ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) { 1569 assert((isa<UsingDecl>(Pattern) || 1570 isa<UnresolvedUsingValueDecl>(Pattern) || 1571 isa<UnresolvedUsingTypenameDecl>(Pattern)) && 1572 "pattern decl is not a using decl"); 1573 assert((isa<UsingDecl>(Inst) || 1574 isa<UnresolvedUsingValueDecl>(Inst) || 1575 isa<UnresolvedUsingTypenameDecl>(Inst)) && 1576 "instantiation did not produce a using decl"); 1577 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists"); 1578 InstantiatedFromUsingDecl[Inst] = Pattern; 1579 } 1580 1581 UsingEnumDecl * 1582 ASTContext::getInstantiatedFromUsingEnumDecl(UsingEnumDecl *UUD) { 1583 auto Pos = InstantiatedFromUsingEnumDecl.find(UUD); 1584 if (Pos == InstantiatedFromUsingEnumDecl.end()) 1585 return nullptr; 1586 1587 return Pos->second; 1588 } 1589 1590 void ASTContext::setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst, 1591 UsingEnumDecl *Pattern) { 1592 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists"); 1593 InstantiatedFromUsingEnumDecl[Inst] = Pattern; 1594 } 1595 1596 UsingShadowDecl * 1597 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) { 1598 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos 1599 = InstantiatedFromUsingShadowDecl.find(Inst); 1600 if (Pos == InstantiatedFromUsingShadowDecl.end()) 1601 return nullptr; 1602 1603 return Pos->second; 1604 } 1605 1606 void 1607 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, 1608 UsingShadowDecl *Pattern) { 1609 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists"); 1610 InstantiatedFromUsingShadowDecl[Inst] = Pattern; 1611 } 1612 1613 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) { 1614 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos 1615 = InstantiatedFromUnnamedFieldDecl.find(Field); 1616 if (Pos == InstantiatedFromUnnamedFieldDecl.end()) 1617 return nullptr; 1618 1619 return Pos->second; 1620 } 1621 1622 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, 1623 FieldDecl *Tmpl) { 1624 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed"); 1625 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed"); 1626 assert(!InstantiatedFromUnnamedFieldDecl[Inst] && 1627 "Already noted what unnamed field was instantiated from"); 1628 1629 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl; 1630 } 1631 1632 ASTContext::overridden_cxx_method_iterator 1633 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const { 1634 return overridden_methods(Method).begin(); 1635 } 1636 1637 ASTContext::overridden_cxx_method_iterator 1638 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const { 1639 return overridden_methods(Method).end(); 1640 } 1641 1642 unsigned 1643 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const { 1644 auto Range = overridden_methods(Method); 1645 return Range.end() - Range.begin(); 1646 } 1647 1648 ASTContext::overridden_method_range 1649 ASTContext::overridden_methods(const CXXMethodDecl *Method) const { 1650 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos = 1651 OverriddenMethods.find(Method->getCanonicalDecl()); 1652 if (Pos == OverriddenMethods.end()) 1653 return overridden_method_range(nullptr, nullptr); 1654 return overridden_method_range(Pos->second.begin(), Pos->second.end()); 1655 } 1656 1657 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method, 1658 const CXXMethodDecl *Overridden) { 1659 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl()); 1660 OverriddenMethods[Method].push_back(Overridden); 1661 } 1662 1663 void ASTContext::getOverriddenMethods( 1664 const NamedDecl *D, 1665 SmallVectorImpl<const NamedDecl *> &Overridden) const { 1666 assert(D); 1667 1668 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) { 1669 Overridden.append(overridden_methods_begin(CXXMethod), 1670 overridden_methods_end(CXXMethod)); 1671 return; 1672 } 1673 1674 const auto *Method = dyn_cast<ObjCMethodDecl>(D); 1675 if (!Method) 1676 return; 1677 1678 SmallVector<const ObjCMethodDecl *, 8> OverDecls; 1679 Method->getOverriddenMethods(OverDecls); 1680 Overridden.append(OverDecls.begin(), OverDecls.end()); 1681 } 1682 1683 void ASTContext::addedLocalImportDecl(ImportDecl *Import) { 1684 assert(!Import->getNextLocalImport() && 1685 "Import declaration already in the chain"); 1686 assert(!Import->isFromASTFile() && "Non-local import declaration"); 1687 if (!FirstLocalImport) { 1688 FirstLocalImport = Import; 1689 LastLocalImport = Import; 1690 return; 1691 } 1692 1693 LastLocalImport->setNextLocalImport(Import); 1694 LastLocalImport = Import; 1695 } 1696 1697 //===----------------------------------------------------------------------===// 1698 // Type Sizing and Analysis 1699 //===----------------------------------------------------------------------===// 1700 1701 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified 1702 /// scalar floating point type. 1703 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const { 1704 switch (T->castAs<BuiltinType>()->getKind()) { 1705 default: 1706 llvm_unreachable("Not a floating point type!"); 1707 case BuiltinType::BFloat16: 1708 return Target->getBFloat16Format(); 1709 case BuiltinType::Float16: 1710 case BuiltinType::Half: 1711 return Target->getHalfFormat(); 1712 case BuiltinType::Float: return Target->getFloatFormat(); 1713 case BuiltinType::Double: return Target->getDoubleFormat(); 1714 case BuiltinType::Ibm128: 1715 return Target->getIbm128Format(); 1716 case BuiltinType::LongDouble: 1717 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) 1718 return AuxTarget->getLongDoubleFormat(); 1719 return Target->getLongDoubleFormat(); 1720 case BuiltinType::Float128: 1721 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) 1722 return AuxTarget->getFloat128Format(); 1723 return Target->getFloat128Format(); 1724 } 1725 } 1726 1727 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const { 1728 unsigned Align = Target->getCharWidth(); 1729 1730 bool UseAlignAttrOnly = false; 1731 if (unsigned AlignFromAttr = D->getMaxAlignment()) { 1732 Align = AlignFromAttr; 1733 1734 // __attribute__((aligned)) can increase or decrease alignment 1735 // *except* on a struct or struct member, where it only increases 1736 // alignment unless 'packed' is also specified. 1737 // 1738 // It is an error for alignas to decrease alignment, so we can 1739 // ignore that possibility; Sema should diagnose it. 1740 if (isa<FieldDecl>(D)) { 1741 UseAlignAttrOnly = D->hasAttr<PackedAttr>() || 1742 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 1743 } else { 1744 UseAlignAttrOnly = true; 1745 } 1746 } 1747 else if (isa<FieldDecl>(D)) 1748 UseAlignAttrOnly = 1749 D->hasAttr<PackedAttr>() || 1750 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 1751 1752 // If we're using the align attribute only, just ignore everything 1753 // else about the declaration and its type. 1754 if (UseAlignAttrOnly) { 1755 // do nothing 1756 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) { 1757 QualType T = VD->getType(); 1758 if (const auto *RT = T->getAs<ReferenceType>()) { 1759 if (ForAlignof) 1760 T = RT->getPointeeType(); 1761 else 1762 T = getPointerType(RT->getPointeeType()); 1763 } 1764 QualType BaseT = getBaseElementType(T); 1765 if (T->isFunctionType()) 1766 Align = getTypeInfoImpl(T.getTypePtr()).Align; 1767 else if (!BaseT->isIncompleteType()) { 1768 // Adjust alignments of declarations with array type by the 1769 // large-array alignment on the target. 1770 if (const ArrayType *arrayType = getAsArrayType(T)) { 1771 unsigned MinWidth = Target->getLargeArrayMinWidth(); 1772 if (!ForAlignof && MinWidth) { 1773 if (isa<VariableArrayType>(arrayType)) 1774 Align = std::max(Align, Target->getLargeArrayAlign()); 1775 else if (isa<ConstantArrayType>(arrayType) && 1776 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType))) 1777 Align = std::max(Align, Target->getLargeArrayAlign()); 1778 } 1779 } 1780 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr())); 1781 if (BaseT.getQualifiers().hasUnaligned()) 1782 Align = Target->getCharWidth(); 1783 if (const auto *VD = dyn_cast<VarDecl>(D)) { 1784 if (VD->hasGlobalStorage() && !ForAlignof) { 1785 uint64_t TypeSize = getTypeSize(T.getTypePtr()); 1786 Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize)); 1787 } 1788 } 1789 } 1790 1791 // Fields can be subject to extra alignment constraints, like if 1792 // the field is packed, the struct is packed, or the struct has a 1793 // a max-field-alignment constraint (#pragma pack). So calculate 1794 // the actual alignment of the field within the struct, and then 1795 // (as we're expected to) constrain that by the alignment of the type. 1796 if (const auto *Field = dyn_cast<FieldDecl>(VD)) { 1797 const RecordDecl *Parent = Field->getParent(); 1798 // We can only produce a sensible answer if the record is valid. 1799 if (!Parent->isInvalidDecl()) { 1800 const ASTRecordLayout &Layout = getASTRecordLayout(Parent); 1801 1802 // Start with the record's overall alignment. 1803 unsigned FieldAlign = toBits(Layout.getAlignment()); 1804 1805 // Use the GCD of that and the offset within the record. 1806 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex()); 1807 if (Offset > 0) { 1808 // Alignment is always a power of 2, so the GCD will be a power of 2, 1809 // which means we get to do this crazy thing instead of Euclid's. 1810 uint64_t LowBitOfOffset = Offset & (~Offset + 1); 1811 if (LowBitOfOffset < FieldAlign) 1812 FieldAlign = static_cast<unsigned>(LowBitOfOffset); 1813 } 1814 1815 Align = std::min(Align, FieldAlign); 1816 } 1817 } 1818 } 1819 1820 // Some targets have hard limitation on the maximum requestable alignment in 1821 // aligned attribute for static variables. 1822 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute(); 1823 const auto *VD = dyn_cast<VarDecl>(D); 1824 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static) 1825 Align = std::min(Align, MaxAlignedAttr); 1826 1827 return toCharUnitsFromBits(Align); 1828 } 1829 1830 CharUnits ASTContext::getExnObjectAlignment() const { 1831 return toCharUnitsFromBits(Target->getExnObjectAlignment()); 1832 } 1833 1834 // getTypeInfoDataSizeInChars - Return the size of a type, in 1835 // chars. If the type is a record, its data size is returned. This is 1836 // the size of the memcpy that's performed when assigning this type 1837 // using a trivial copy/move assignment operator. 1838 TypeInfoChars ASTContext::getTypeInfoDataSizeInChars(QualType T) const { 1839 TypeInfoChars Info = getTypeInfoInChars(T); 1840 1841 // In C++, objects can sometimes be allocated into the tail padding 1842 // of a base-class subobject. We decide whether that's possible 1843 // during class layout, so here we can just trust the layout results. 1844 if (getLangOpts().CPlusPlus) { 1845 if (const auto *RT = T->getAs<RecordType>()) { 1846 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl()); 1847 Info.Width = layout.getDataSize(); 1848 } 1849 } 1850 1851 return Info; 1852 } 1853 1854 /// getConstantArrayInfoInChars - Performing the computation in CharUnits 1855 /// instead of in bits prevents overflowing the uint64_t for some large arrays. 1856 TypeInfoChars 1857 static getConstantArrayInfoInChars(const ASTContext &Context, 1858 const ConstantArrayType *CAT) { 1859 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType()); 1860 uint64_t Size = CAT->getSize().getZExtValue(); 1861 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <= 1862 (uint64_t)(-1)/Size) && 1863 "Overflow in array type char size evaluation"); 1864 uint64_t Width = EltInfo.Width.getQuantity() * Size; 1865 unsigned Align = EltInfo.Align.getQuantity(); 1866 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() || 1867 Context.getTargetInfo().getPointerWidth(0) == 64) 1868 Width = llvm::alignTo(Width, Align); 1869 return TypeInfoChars(CharUnits::fromQuantity(Width), 1870 CharUnits::fromQuantity(Align), 1871 EltInfo.AlignRequirement); 1872 } 1873 1874 TypeInfoChars ASTContext::getTypeInfoInChars(const Type *T) const { 1875 if (const auto *CAT = dyn_cast<ConstantArrayType>(T)) 1876 return getConstantArrayInfoInChars(*this, CAT); 1877 TypeInfo Info = getTypeInfo(T); 1878 return TypeInfoChars(toCharUnitsFromBits(Info.Width), 1879 toCharUnitsFromBits(Info.Align), Info.AlignRequirement); 1880 } 1881 1882 TypeInfoChars ASTContext::getTypeInfoInChars(QualType T) const { 1883 return getTypeInfoInChars(T.getTypePtr()); 1884 } 1885 1886 bool ASTContext::isAlignmentRequired(const Type *T) const { 1887 return getTypeInfo(T).AlignRequirement != AlignRequirementKind::None; 1888 } 1889 1890 bool ASTContext::isAlignmentRequired(QualType T) const { 1891 return isAlignmentRequired(T.getTypePtr()); 1892 } 1893 1894 unsigned ASTContext::getTypeAlignIfKnown(QualType T, 1895 bool NeedsPreferredAlignment) const { 1896 // An alignment on a typedef overrides anything else. 1897 if (const auto *TT = T->getAs<TypedefType>()) 1898 if (unsigned Align = TT->getDecl()->getMaxAlignment()) 1899 return Align; 1900 1901 // If we have an (array of) complete type, we're done. 1902 T = getBaseElementType(T); 1903 if (!T->isIncompleteType()) 1904 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T); 1905 1906 // If we had an array type, its element type might be a typedef 1907 // type with an alignment attribute. 1908 if (const auto *TT = T->getAs<TypedefType>()) 1909 if (unsigned Align = TT->getDecl()->getMaxAlignment()) 1910 return Align; 1911 1912 // Otherwise, see if the declaration of the type had an attribute. 1913 if (const auto *TT = T->getAs<TagType>()) 1914 return TT->getDecl()->getMaxAlignment(); 1915 1916 return 0; 1917 } 1918 1919 TypeInfo ASTContext::getTypeInfo(const Type *T) const { 1920 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T); 1921 if (I != MemoizedTypeInfo.end()) 1922 return I->second; 1923 1924 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup. 1925 TypeInfo TI = getTypeInfoImpl(T); 1926 MemoizedTypeInfo[T] = TI; 1927 return TI; 1928 } 1929 1930 /// getTypeInfoImpl - Return the size of the specified type, in bits. This 1931 /// method does not work on incomplete types. 1932 /// 1933 /// FIXME: Pointers into different addr spaces could have different sizes and 1934 /// alignment requirements: getPointerInfo should take an AddrSpace, this 1935 /// should take a QualType, &c. 1936 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const { 1937 uint64_t Width = 0; 1938 unsigned Align = 8; 1939 AlignRequirementKind AlignRequirement = AlignRequirementKind::None; 1940 unsigned AS = 0; 1941 switch (T->getTypeClass()) { 1942 #define TYPE(Class, Base) 1943 #define ABSTRACT_TYPE(Class, Base) 1944 #define NON_CANONICAL_TYPE(Class, Base) 1945 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 1946 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \ 1947 case Type::Class: \ 1948 assert(!T->isDependentType() && "should not see dependent types here"); \ 1949 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr()); 1950 #include "clang/AST/TypeNodes.inc" 1951 llvm_unreachable("Should not see dependent types"); 1952 1953 case Type::FunctionNoProto: 1954 case Type::FunctionProto: 1955 // GCC extension: alignof(function) = 32 bits 1956 Width = 0; 1957 Align = 32; 1958 break; 1959 1960 case Type::IncompleteArray: 1961 case Type::VariableArray: 1962 case Type::ConstantArray: { 1963 // Model non-constant sized arrays as size zero, but track the alignment. 1964 uint64_t Size = 0; 1965 if (const auto *CAT = dyn_cast<ConstantArrayType>(T)) 1966 Size = CAT->getSize().getZExtValue(); 1967 1968 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType()); 1969 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) && 1970 "Overflow in array type bit size evaluation"); 1971 Width = EltInfo.Width * Size; 1972 Align = EltInfo.Align; 1973 AlignRequirement = EltInfo.AlignRequirement; 1974 if (!getTargetInfo().getCXXABI().isMicrosoft() || 1975 getTargetInfo().getPointerWidth(0) == 64) 1976 Width = llvm::alignTo(Width, Align); 1977 break; 1978 } 1979 1980 case Type::ExtVector: 1981 case Type::Vector: { 1982 const auto *VT = cast<VectorType>(T); 1983 TypeInfo EltInfo = getTypeInfo(VT->getElementType()); 1984 Width = VT->isExtVectorBoolType() ? VT->getNumElements() 1985 : EltInfo.Width * VT->getNumElements(); 1986 // Enforce at least byte alignment. 1987 Align = std::max<unsigned>(8, Width); 1988 1989 // If the alignment is not a power of 2, round up to the next power of 2. 1990 // This happens for non-power-of-2 length vectors. 1991 if (Align & (Align-1)) { 1992 Align = llvm::NextPowerOf2(Align); 1993 Width = llvm::alignTo(Width, Align); 1994 } 1995 // Adjust the alignment based on the target max. 1996 uint64_t TargetVectorAlign = Target->getMaxVectorAlign(); 1997 if (TargetVectorAlign && TargetVectorAlign < Align) 1998 Align = TargetVectorAlign; 1999 if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) 2000 // Adjust the alignment for fixed-length SVE vectors. This is important 2001 // for non-power-of-2 vector lengths. 2002 Align = 128; 2003 else if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 2004 // Adjust the alignment for fixed-length SVE predicates. 2005 Align = 16; 2006 break; 2007 } 2008 2009 case Type::ConstantMatrix: { 2010 const auto *MT = cast<ConstantMatrixType>(T); 2011 TypeInfo ElementInfo = getTypeInfo(MT->getElementType()); 2012 // The internal layout of a matrix value is implementation defined. 2013 // Initially be ABI compatible with arrays with respect to alignment and 2014 // size. 2015 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns(); 2016 Align = ElementInfo.Align; 2017 break; 2018 } 2019 2020 case Type::Builtin: 2021 switch (cast<BuiltinType>(T)->getKind()) { 2022 default: llvm_unreachable("Unknown builtin type!"); 2023 case BuiltinType::Void: 2024 // GCC extension: alignof(void) = 8 bits. 2025 Width = 0; 2026 Align = 8; 2027 break; 2028 case BuiltinType::Bool: 2029 Width = Target->getBoolWidth(); 2030 Align = Target->getBoolAlign(); 2031 break; 2032 case BuiltinType::Char_S: 2033 case BuiltinType::Char_U: 2034 case BuiltinType::UChar: 2035 case BuiltinType::SChar: 2036 case BuiltinType::Char8: 2037 Width = Target->getCharWidth(); 2038 Align = Target->getCharAlign(); 2039 break; 2040 case BuiltinType::WChar_S: 2041 case BuiltinType::WChar_U: 2042 Width = Target->getWCharWidth(); 2043 Align = Target->getWCharAlign(); 2044 break; 2045 case BuiltinType::Char16: 2046 Width = Target->getChar16Width(); 2047 Align = Target->getChar16Align(); 2048 break; 2049 case BuiltinType::Char32: 2050 Width = Target->getChar32Width(); 2051 Align = Target->getChar32Align(); 2052 break; 2053 case BuiltinType::UShort: 2054 case BuiltinType::Short: 2055 Width = Target->getShortWidth(); 2056 Align = Target->getShortAlign(); 2057 break; 2058 case BuiltinType::UInt: 2059 case BuiltinType::Int: 2060 Width = Target->getIntWidth(); 2061 Align = Target->getIntAlign(); 2062 break; 2063 case BuiltinType::ULong: 2064 case BuiltinType::Long: 2065 Width = Target->getLongWidth(); 2066 Align = Target->getLongAlign(); 2067 break; 2068 case BuiltinType::ULongLong: 2069 case BuiltinType::LongLong: 2070 Width = Target->getLongLongWidth(); 2071 Align = Target->getLongLongAlign(); 2072 break; 2073 case BuiltinType::Int128: 2074 case BuiltinType::UInt128: 2075 Width = 128; 2076 Align = 128; // int128_t is 128-bit aligned on all targets. 2077 break; 2078 case BuiltinType::ShortAccum: 2079 case BuiltinType::UShortAccum: 2080 case BuiltinType::SatShortAccum: 2081 case BuiltinType::SatUShortAccum: 2082 Width = Target->getShortAccumWidth(); 2083 Align = Target->getShortAccumAlign(); 2084 break; 2085 case BuiltinType::Accum: 2086 case BuiltinType::UAccum: 2087 case BuiltinType::SatAccum: 2088 case BuiltinType::SatUAccum: 2089 Width = Target->getAccumWidth(); 2090 Align = Target->getAccumAlign(); 2091 break; 2092 case BuiltinType::LongAccum: 2093 case BuiltinType::ULongAccum: 2094 case BuiltinType::SatLongAccum: 2095 case BuiltinType::SatULongAccum: 2096 Width = Target->getLongAccumWidth(); 2097 Align = Target->getLongAccumAlign(); 2098 break; 2099 case BuiltinType::ShortFract: 2100 case BuiltinType::UShortFract: 2101 case BuiltinType::SatShortFract: 2102 case BuiltinType::SatUShortFract: 2103 Width = Target->getShortFractWidth(); 2104 Align = Target->getShortFractAlign(); 2105 break; 2106 case BuiltinType::Fract: 2107 case BuiltinType::UFract: 2108 case BuiltinType::SatFract: 2109 case BuiltinType::SatUFract: 2110 Width = Target->getFractWidth(); 2111 Align = Target->getFractAlign(); 2112 break; 2113 case BuiltinType::LongFract: 2114 case BuiltinType::ULongFract: 2115 case BuiltinType::SatLongFract: 2116 case BuiltinType::SatULongFract: 2117 Width = Target->getLongFractWidth(); 2118 Align = Target->getLongFractAlign(); 2119 break; 2120 case BuiltinType::BFloat16: 2121 Width = Target->getBFloat16Width(); 2122 Align = Target->getBFloat16Align(); 2123 break; 2124 case BuiltinType::Float16: 2125 case BuiltinType::Half: 2126 if (Target->hasFloat16Type() || !getLangOpts().OpenMP || 2127 !getLangOpts().OpenMPIsDevice) { 2128 Width = Target->getHalfWidth(); 2129 Align = Target->getHalfAlign(); 2130 } else { 2131 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 2132 "Expected OpenMP device compilation."); 2133 Width = AuxTarget->getHalfWidth(); 2134 Align = AuxTarget->getHalfAlign(); 2135 } 2136 break; 2137 case BuiltinType::Float: 2138 Width = Target->getFloatWidth(); 2139 Align = Target->getFloatAlign(); 2140 break; 2141 case BuiltinType::Double: 2142 Width = Target->getDoubleWidth(); 2143 Align = Target->getDoubleAlign(); 2144 break; 2145 case BuiltinType::Ibm128: 2146 Width = Target->getIbm128Width(); 2147 Align = Target->getIbm128Align(); 2148 break; 2149 case BuiltinType::LongDouble: 2150 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 2151 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() || 2152 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) { 2153 Width = AuxTarget->getLongDoubleWidth(); 2154 Align = AuxTarget->getLongDoubleAlign(); 2155 } else { 2156 Width = Target->getLongDoubleWidth(); 2157 Align = Target->getLongDoubleAlign(); 2158 } 2159 break; 2160 case BuiltinType::Float128: 2161 if (Target->hasFloat128Type() || !getLangOpts().OpenMP || 2162 !getLangOpts().OpenMPIsDevice) { 2163 Width = Target->getFloat128Width(); 2164 Align = Target->getFloat128Align(); 2165 } else { 2166 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 2167 "Expected OpenMP device compilation."); 2168 Width = AuxTarget->getFloat128Width(); 2169 Align = AuxTarget->getFloat128Align(); 2170 } 2171 break; 2172 case BuiltinType::NullPtr: 2173 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t) 2174 Align = Target->getPointerAlign(0); // == sizeof(void*) 2175 break; 2176 case BuiltinType::ObjCId: 2177 case BuiltinType::ObjCClass: 2178 case BuiltinType::ObjCSel: 2179 Width = Target->getPointerWidth(0); 2180 Align = Target->getPointerAlign(0); 2181 break; 2182 case BuiltinType::OCLSampler: 2183 case BuiltinType::OCLEvent: 2184 case BuiltinType::OCLClkEvent: 2185 case BuiltinType::OCLQueue: 2186 case BuiltinType::OCLReserveID: 2187 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 2188 case BuiltinType::Id: 2189 #include "clang/Basic/OpenCLImageTypes.def" 2190 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 2191 case BuiltinType::Id: 2192 #include "clang/Basic/OpenCLExtensionTypes.def" 2193 AS = getTargetAddressSpace( 2194 Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T))); 2195 Width = Target->getPointerWidth(AS); 2196 Align = Target->getPointerAlign(AS); 2197 break; 2198 // The SVE types are effectively target-specific. The length of an 2199 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple 2200 // of 128 bits. There is one predicate bit for each vector byte, so the 2201 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits. 2202 // 2203 // Because the length is only known at runtime, we use a dummy value 2204 // of 0 for the static length. The alignment values are those defined 2205 // by the Procedure Call Standard for the Arm Architecture. 2206 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \ 2207 IsSigned, IsFP, IsBF) \ 2208 case BuiltinType::Id: \ 2209 Width = 0; \ 2210 Align = 128; \ 2211 break; 2212 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \ 2213 case BuiltinType::Id: \ 2214 Width = 0; \ 2215 Align = 16; \ 2216 break; 2217 #include "clang/Basic/AArch64SVEACLETypes.def" 2218 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 2219 case BuiltinType::Id: \ 2220 Width = Size; \ 2221 Align = Size; \ 2222 break; 2223 #include "clang/Basic/PPCTypes.def" 2224 #define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \ 2225 IsFP) \ 2226 case BuiltinType::Id: \ 2227 Width = 0; \ 2228 Align = ElBits; \ 2229 break; 2230 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \ 2231 case BuiltinType::Id: \ 2232 Width = 0; \ 2233 Align = 8; \ 2234 break; 2235 #include "clang/Basic/RISCVVTypes.def" 2236 } 2237 break; 2238 case Type::ObjCObjectPointer: 2239 Width = Target->getPointerWidth(0); 2240 Align = Target->getPointerAlign(0); 2241 break; 2242 case Type::BlockPointer: 2243 AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType()); 2244 Width = Target->getPointerWidth(AS); 2245 Align = Target->getPointerAlign(AS); 2246 break; 2247 case Type::LValueReference: 2248 case Type::RValueReference: 2249 // alignof and sizeof should never enter this code path here, so we go 2250 // the pointer route. 2251 AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType()); 2252 Width = Target->getPointerWidth(AS); 2253 Align = Target->getPointerAlign(AS); 2254 break; 2255 case Type::Pointer: 2256 AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType()); 2257 Width = Target->getPointerWidth(AS); 2258 Align = Target->getPointerAlign(AS); 2259 break; 2260 case Type::MemberPointer: { 2261 const auto *MPT = cast<MemberPointerType>(T); 2262 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT); 2263 Width = MPI.Width; 2264 Align = MPI.Align; 2265 break; 2266 } 2267 case Type::Complex: { 2268 // Complex types have the same alignment as their elements, but twice the 2269 // size. 2270 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType()); 2271 Width = EltInfo.Width * 2; 2272 Align = EltInfo.Align; 2273 break; 2274 } 2275 case Type::ObjCObject: 2276 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr()); 2277 case Type::Adjusted: 2278 case Type::Decayed: 2279 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr()); 2280 case Type::ObjCInterface: { 2281 const auto *ObjCI = cast<ObjCInterfaceType>(T); 2282 if (ObjCI->getDecl()->isInvalidDecl()) { 2283 Width = 8; 2284 Align = 8; 2285 break; 2286 } 2287 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 2288 Width = toBits(Layout.getSize()); 2289 Align = toBits(Layout.getAlignment()); 2290 break; 2291 } 2292 case Type::BitInt: { 2293 const auto *EIT = cast<BitIntType>(T); 2294 Align = 2295 std::min(static_cast<unsigned>(std::max( 2296 getCharWidth(), llvm::PowerOf2Ceil(EIT->getNumBits()))), 2297 Target->getLongLongAlign()); 2298 Width = llvm::alignTo(EIT->getNumBits(), Align); 2299 break; 2300 } 2301 case Type::Record: 2302 case Type::Enum: { 2303 const auto *TT = cast<TagType>(T); 2304 2305 if (TT->getDecl()->isInvalidDecl()) { 2306 Width = 8; 2307 Align = 8; 2308 break; 2309 } 2310 2311 if (const auto *ET = dyn_cast<EnumType>(TT)) { 2312 const EnumDecl *ED = ET->getDecl(); 2313 TypeInfo Info = 2314 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType()); 2315 if (unsigned AttrAlign = ED->getMaxAlignment()) { 2316 Info.Align = AttrAlign; 2317 Info.AlignRequirement = AlignRequirementKind::RequiredByEnum; 2318 } 2319 return Info; 2320 } 2321 2322 const auto *RT = cast<RecordType>(TT); 2323 const RecordDecl *RD = RT->getDecl(); 2324 const ASTRecordLayout &Layout = getASTRecordLayout(RD); 2325 Width = toBits(Layout.getSize()); 2326 Align = toBits(Layout.getAlignment()); 2327 AlignRequirement = RD->hasAttr<AlignedAttr>() 2328 ? AlignRequirementKind::RequiredByRecord 2329 : AlignRequirementKind::None; 2330 break; 2331 } 2332 2333 case Type::SubstTemplateTypeParm: 2334 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)-> 2335 getReplacementType().getTypePtr()); 2336 2337 case Type::Auto: 2338 case Type::DeducedTemplateSpecialization: { 2339 const auto *A = cast<DeducedType>(T); 2340 assert(!A->getDeducedType().isNull() && 2341 "cannot request the size of an undeduced or dependent auto type"); 2342 return getTypeInfo(A->getDeducedType().getTypePtr()); 2343 } 2344 2345 case Type::Paren: 2346 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr()); 2347 2348 case Type::MacroQualified: 2349 return getTypeInfo( 2350 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr()); 2351 2352 case Type::ObjCTypeParam: 2353 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr()); 2354 2355 case Type::Using: 2356 return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr()); 2357 2358 case Type::Typedef: { 2359 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl(); 2360 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr()); 2361 // If the typedef has an aligned attribute on it, it overrides any computed 2362 // alignment we have. This violates the GCC documentation (which says that 2363 // attribute(aligned) can only round up) but matches its implementation. 2364 if (unsigned AttrAlign = Typedef->getMaxAlignment()) { 2365 Align = AttrAlign; 2366 AlignRequirement = AlignRequirementKind::RequiredByTypedef; 2367 } else { 2368 Align = Info.Align; 2369 AlignRequirement = Info.AlignRequirement; 2370 } 2371 Width = Info.Width; 2372 break; 2373 } 2374 2375 case Type::Elaborated: 2376 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr()); 2377 2378 case Type::Attributed: 2379 return getTypeInfo( 2380 cast<AttributedType>(T)->getEquivalentType().getTypePtr()); 2381 2382 case Type::BTFTagAttributed: 2383 return getTypeInfo( 2384 cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr()); 2385 2386 case Type::Atomic: { 2387 // Start with the base type information. 2388 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType()); 2389 Width = Info.Width; 2390 Align = Info.Align; 2391 2392 if (!Width) { 2393 // An otherwise zero-sized type should still generate an 2394 // atomic operation. 2395 Width = Target->getCharWidth(); 2396 assert(Align); 2397 } else if (Width <= Target->getMaxAtomicPromoteWidth()) { 2398 // If the size of the type doesn't exceed the platform's max 2399 // atomic promotion width, make the size and alignment more 2400 // favorable to atomic operations: 2401 2402 // Round the size up to a power of 2. 2403 if (!llvm::isPowerOf2_64(Width)) 2404 Width = llvm::NextPowerOf2(Width); 2405 2406 // Set the alignment equal to the size. 2407 Align = static_cast<unsigned>(Width); 2408 } 2409 } 2410 break; 2411 2412 case Type::Pipe: 2413 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global)); 2414 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global)); 2415 break; 2416 } 2417 2418 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2"); 2419 return TypeInfo(Width, Align, AlignRequirement); 2420 } 2421 2422 unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const { 2423 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T); 2424 if (I != MemoizedUnadjustedAlign.end()) 2425 return I->second; 2426 2427 unsigned UnadjustedAlign; 2428 if (const auto *RT = T->getAs<RecordType>()) { 2429 const RecordDecl *RD = RT->getDecl(); 2430 const ASTRecordLayout &Layout = getASTRecordLayout(RD); 2431 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment()); 2432 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) { 2433 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 2434 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment()); 2435 } else { 2436 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType()); 2437 } 2438 2439 MemoizedUnadjustedAlign[T] = UnadjustedAlign; 2440 return UnadjustedAlign; 2441 } 2442 2443 unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const { 2444 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign(); 2445 return SimdAlign; 2446 } 2447 2448 /// toCharUnitsFromBits - Convert a size in bits to a size in characters. 2449 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const { 2450 return CharUnits::fromQuantity(BitSize / getCharWidth()); 2451 } 2452 2453 /// toBits - Convert a size in characters to a size in characters. 2454 int64_t ASTContext::toBits(CharUnits CharSize) const { 2455 return CharSize.getQuantity() * getCharWidth(); 2456 } 2457 2458 /// getTypeSizeInChars - Return the size of the specified type, in characters. 2459 /// This method does not work on incomplete types. 2460 CharUnits ASTContext::getTypeSizeInChars(QualType T) const { 2461 return getTypeInfoInChars(T).Width; 2462 } 2463 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const { 2464 return getTypeInfoInChars(T).Width; 2465 } 2466 2467 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in 2468 /// characters. This method does not work on incomplete types. 2469 CharUnits ASTContext::getTypeAlignInChars(QualType T) const { 2470 return toCharUnitsFromBits(getTypeAlign(T)); 2471 } 2472 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const { 2473 return toCharUnitsFromBits(getTypeAlign(T)); 2474 } 2475 2476 /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a 2477 /// type, in characters, before alignment adustments. This method does 2478 /// not work on incomplete types. 2479 CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const { 2480 return toCharUnitsFromBits(getTypeUnadjustedAlign(T)); 2481 } 2482 CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const { 2483 return toCharUnitsFromBits(getTypeUnadjustedAlign(T)); 2484 } 2485 2486 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified 2487 /// type for the current target in bits. This can be different than the ABI 2488 /// alignment in cases where it is beneficial for performance or backwards 2489 /// compatibility preserving to overalign a data type. (Note: despite the name, 2490 /// the preferred alignment is ABI-impacting, and not an optimization.) 2491 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const { 2492 TypeInfo TI = getTypeInfo(T); 2493 unsigned ABIAlign = TI.Align; 2494 2495 T = T->getBaseElementTypeUnsafe(); 2496 2497 // The preferred alignment of member pointers is that of a pointer. 2498 if (T->isMemberPointerType()) 2499 return getPreferredTypeAlign(getPointerDiffType().getTypePtr()); 2500 2501 if (!Target->allowsLargerPreferedTypeAlignment()) 2502 return ABIAlign; 2503 2504 if (const auto *RT = T->getAs<RecordType>()) { 2505 const RecordDecl *RD = RT->getDecl(); 2506 2507 // When used as part of a typedef, or together with a 'packed' attribute, 2508 // the 'aligned' attribute can be used to decrease alignment. Note that the 2509 // 'packed' case is already taken into consideration when computing the 2510 // alignment, we only need to handle the typedef case here. 2511 if (TI.AlignRequirement == AlignRequirementKind::RequiredByTypedef || 2512 RD->isInvalidDecl()) 2513 return ABIAlign; 2514 2515 unsigned PreferredAlign = static_cast<unsigned>( 2516 toBits(getASTRecordLayout(RD).PreferredAlignment)); 2517 assert(PreferredAlign >= ABIAlign && 2518 "PreferredAlign should be at least as large as ABIAlign."); 2519 return PreferredAlign; 2520 } 2521 2522 // Double (and, for targets supporting AIX `power` alignment, long double) and 2523 // long long should be naturally aligned (despite requiring less alignment) if 2524 // possible. 2525 if (const auto *CT = T->getAs<ComplexType>()) 2526 T = CT->getElementType().getTypePtr(); 2527 if (const auto *ET = T->getAs<EnumType>()) 2528 T = ET->getDecl()->getIntegerType().getTypePtr(); 2529 if (T->isSpecificBuiltinType(BuiltinType::Double) || 2530 T->isSpecificBuiltinType(BuiltinType::LongLong) || 2531 T->isSpecificBuiltinType(BuiltinType::ULongLong) || 2532 (T->isSpecificBuiltinType(BuiltinType::LongDouble) && 2533 Target->defaultsToAIXPowerAlignment())) 2534 // Don't increase the alignment if an alignment attribute was specified on a 2535 // typedef declaration. 2536 if (!TI.isAlignRequired()) 2537 return std::max(ABIAlign, (unsigned)getTypeSize(T)); 2538 2539 return ABIAlign; 2540 } 2541 2542 /// getTargetDefaultAlignForAttributeAligned - Return the default alignment 2543 /// for __attribute__((aligned)) on this target, to be used if no alignment 2544 /// value is specified. 2545 unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const { 2546 return getTargetInfo().getDefaultAlignForAttributeAligned(); 2547 } 2548 2549 /// getAlignOfGlobalVar - Return the alignment in bits that should be given 2550 /// to a global variable of the specified type. 2551 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const { 2552 uint64_t TypeSize = getTypeSize(T.getTypePtr()); 2553 return std::max(getPreferredTypeAlign(T), 2554 getTargetInfo().getMinGlobalAlign(TypeSize)); 2555 } 2556 2557 /// getAlignOfGlobalVarInChars - Return the alignment in characters that 2558 /// should be given to a global variable of the specified type. 2559 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const { 2560 return toCharUnitsFromBits(getAlignOfGlobalVar(T)); 2561 } 2562 2563 CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const { 2564 CharUnits Offset = CharUnits::Zero(); 2565 const ASTRecordLayout *Layout = &getASTRecordLayout(RD); 2566 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) { 2567 Offset += Layout->getBaseClassOffset(Base); 2568 Layout = &getASTRecordLayout(Base); 2569 } 2570 return Offset; 2571 } 2572 2573 CharUnits ASTContext::getMemberPointerPathAdjustment(const APValue &MP) const { 2574 const ValueDecl *MPD = MP.getMemberPointerDecl(); 2575 CharUnits ThisAdjustment = CharUnits::Zero(); 2576 ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath(); 2577 bool DerivedMember = MP.isMemberPointerToDerivedMember(); 2578 const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext()); 2579 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 2580 const CXXRecordDecl *Base = RD; 2581 const CXXRecordDecl *Derived = Path[I]; 2582 if (DerivedMember) 2583 std::swap(Base, Derived); 2584 ThisAdjustment += getASTRecordLayout(Derived).getBaseClassOffset(Base); 2585 RD = Path[I]; 2586 } 2587 if (DerivedMember) 2588 ThisAdjustment = -ThisAdjustment; 2589 return ThisAdjustment; 2590 } 2591 2592 /// DeepCollectObjCIvars - 2593 /// This routine first collects all declared, but not synthesized, ivars in 2594 /// super class and then collects all ivars, including those synthesized for 2595 /// current class. This routine is used for implementation of current class 2596 /// when all ivars, declared and synthesized are known. 2597 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, 2598 bool leafClass, 2599 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const { 2600 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass()) 2601 DeepCollectObjCIvars(SuperClass, false, Ivars); 2602 if (!leafClass) { 2603 llvm::append_range(Ivars, OI->ivars()); 2604 } else { 2605 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI); 2606 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv; 2607 Iv= Iv->getNextIvar()) 2608 Ivars.push_back(Iv); 2609 } 2610 } 2611 2612 /// CollectInheritedProtocols - Collect all protocols in current class and 2613 /// those inherited by it. 2614 void ASTContext::CollectInheritedProtocols(const Decl *CDecl, 2615 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) { 2616 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) { 2617 // We can use protocol_iterator here instead of 2618 // all_referenced_protocol_iterator since we are walking all categories. 2619 for (auto *Proto : OI->all_referenced_protocols()) { 2620 CollectInheritedProtocols(Proto, Protocols); 2621 } 2622 2623 // Categories of this Interface. 2624 for (const auto *Cat : OI->visible_categories()) 2625 CollectInheritedProtocols(Cat, Protocols); 2626 2627 if (ObjCInterfaceDecl *SD = OI->getSuperClass()) 2628 while (SD) { 2629 CollectInheritedProtocols(SD, Protocols); 2630 SD = SD->getSuperClass(); 2631 } 2632 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) { 2633 for (auto *Proto : OC->protocols()) { 2634 CollectInheritedProtocols(Proto, Protocols); 2635 } 2636 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) { 2637 // Insert the protocol. 2638 if (!Protocols.insert( 2639 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second) 2640 return; 2641 2642 for (auto *Proto : OP->protocols()) 2643 CollectInheritedProtocols(Proto, Protocols); 2644 } 2645 } 2646 2647 static bool unionHasUniqueObjectRepresentations(const ASTContext &Context, 2648 const RecordDecl *RD) { 2649 assert(RD->isUnion() && "Must be union type"); 2650 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl()); 2651 2652 for (const auto *Field : RD->fields()) { 2653 if (!Context.hasUniqueObjectRepresentations(Field->getType())) 2654 return false; 2655 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType()); 2656 if (FieldSize != UnionSize) 2657 return false; 2658 } 2659 return !RD->field_empty(); 2660 } 2661 2662 static int64_t getSubobjectOffset(const FieldDecl *Field, 2663 const ASTContext &Context, 2664 const clang::ASTRecordLayout & /*Layout*/) { 2665 return Context.getFieldOffset(Field); 2666 } 2667 2668 static int64_t getSubobjectOffset(const CXXRecordDecl *RD, 2669 const ASTContext &Context, 2670 const clang::ASTRecordLayout &Layout) { 2671 return Context.toBits(Layout.getBaseClassOffset(RD)); 2672 } 2673 2674 static llvm::Optional<int64_t> 2675 structHasUniqueObjectRepresentations(const ASTContext &Context, 2676 const RecordDecl *RD); 2677 2678 static llvm::Optional<int64_t> 2679 getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context) { 2680 if (Field->getType()->isRecordType()) { 2681 const RecordDecl *RD = Field->getType()->getAsRecordDecl(); 2682 if (!RD->isUnion()) 2683 return structHasUniqueObjectRepresentations(Context, RD); 2684 } 2685 if (!Field->getType()->isReferenceType() && 2686 !Context.hasUniqueObjectRepresentations(Field->getType())) 2687 return llvm::None; 2688 2689 int64_t FieldSizeInBits = 2690 Context.toBits(Context.getTypeSizeInChars(Field->getType())); 2691 if (Field->isBitField()) { 2692 int64_t BitfieldSize = Field->getBitWidthValue(Context); 2693 if (BitfieldSize > FieldSizeInBits) 2694 return llvm::None; 2695 FieldSizeInBits = BitfieldSize; 2696 } 2697 return FieldSizeInBits; 2698 } 2699 2700 static llvm::Optional<int64_t> 2701 getSubobjectSizeInBits(const CXXRecordDecl *RD, const ASTContext &Context) { 2702 return structHasUniqueObjectRepresentations(Context, RD); 2703 } 2704 2705 template <typename RangeT> 2706 static llvm::Optional<int64_t> structSubobjectsHaveUniqueObjectRepresentations( 2707 const RangeT &Subobjects, int64_t CurOffsetInBits, 2708 const ASTContext &Context, const clang::ASTRecordLayout &Layout) { 2709 for (const auto *Subobject : Subobjects) { 2710 llvm::Optional<int64_t> SizeInBits = 2711 getSubobjectSizeInBits(Subobject, Context); 2712 if (!SizeInBits) 2713 return llvm::None; 2714 if (*SizeInBits != 0) { 2715 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout); 2716 if (Offset != CurOffsetInBits) 2717 return llvm::None; 2718 CurOffsetInBits += *SizeInBits; 2719 } 2720 } 2721 return CurOffsetInBits; 2722 } 2723 2724 static llvm::Optional<int64_t> 2725 structHasUniqueObjectRepresentations(const ASTContext &Context, 2726 const RecordDecl *RD) { 2727 assert(!RD->isUnion() && "Must be struct/class type"); 2728 const auto &Layout = Context.getASTRecordLayout(RD); 2729 2730 int64_t CurOffsetInBits = 0; 2731 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) { 2732 if (ClassDecl->isDynamicClass()) 2733 return llvm::None; 2734 2735 SmallVector<CXXRecordDecl *, 4> Bases; 2736 for (const auto &Base : ClassDecl->bases()) { 2737 // Empty types can be inherited from, and non-empty types can potentially 2738 // have tail padding, so just make sure there isn't an error. 2739 Bases.emplace_back(Base.getType()->getAsCXXRecordDecl()); 2740 } 2741 2742 llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) { 2743 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R); 2744 }); 2745 2746 llvm::Optional<int64_t> OffsetAfterBases = 2747 structSubobjectsHaveUniqueObjectRepresentations(Bases, CurOffsetInBits, 2748 Context, Layout); 2749 if (!OffsetAfterBases) 2750 return llvm::None; 2751 CurOffsetInBits = *OffsetAfterBases; 2752 } 2753 2754 llvm::Optional<int64_t> OffsetAfterFields = 2755 structSubobjectsHaveUniqueObjectRepresentations( 2756 RD->fields(), CurOffsetInBits, Context, Layout); 2757 if (!OffsetAfterFields) 2758 return llvm::None; 2759 CurOffsetInBits = *OffsetAfterFields; 2760 2761 return CurOffsetInBits; 2762 } 2763 2764 bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const { 2765 // C++17 [meta.unary.prop]: 2766 // The predicate condition for a template specialization 2767 // has_unique_object_representations<T> shall be 2768 // satisfied if and only if: 2769 // (9.1) - T is trivially copyable, and 2770 // (9.2) - any two objects of type T with the same value have the same 2771 // object representation, where two objects 2772 // of array or non-union class type are considered to have the same value 2773 // if their respective sequences of 2774 // direct subobjects have the same values, and two objects of union type 2775 // are considered to have the same 2776 // value if they have the same active member and the corresponding members 2777 // have the same value. 2778 // The set of scalar types for which this condition holds is 2779 // implementation-defined. [ Note: If a type has padding 2780 // bits, the condition does not hold; otherwise, the condition holds true 2781 // for unsigned integral types. -- end note ] 2782 assert(!Ty.isNull() && "Null QualType sent to unique object rep check"); 2783 2784 // Arrays are unique only if their element type is unique. 2785 if (Ty->isArrayType()) 2786 return hasUniqueObjectRepresentations(getBaseElementType(Ty)); 2787 2788 // (9.1) - T is trivially copyable... 2789 if (!Ty.isTriviallyCopyableType(*this)) 2790 return false; 2791 2792 // All integrals and enums are unique. 2793 if (Ty->isIntegralOrEnumerationType()) 2794 return true; 2795 2796 // All other pointers are unique. 2797 if (Ty->isPointerType()) 2798 return true; 2799 2800 if (Ty->isMemberPointerType()) { 2801 const auto *MPT = Ty->getAs<MemberPointerType>(); 2802 return !ABI->getMemberPointerInfo(MPT).HasPadding; 2803 } 2804 2805 if (Ty->isRecordType()) { 2806 const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl(); 2807 2808 if (Record->isInvalidDecl()) 2809 return false; 2810 2811 if (Record->isUnion()) 2812 return unionHasUniqueObjectRepresentations(*this, Record); 2813 2814 Optional<int64_t> StructSize = 2815 structHasUniqueObjectRepresentations(*this, Record); 2816 2817 return StructSize && 2818 StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty)); 2819 } 2820 2821 // FIXME: More cases to handle here (list by rsmith): 2822 // vectors (careful about, eg, vector of 3 foo) 2823 // _Complex int and friends 2824 // _Atomic T 2825 // Obj-C block pointers 2826 // Obj-C object pointers 2827 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t, 2828 // clk_event_t, queue_t, reserve_id_t) 2829 // There're also Obj-C class types and the Obj-C selector type, but I think it 2830 // makes sense for those to return false here. 2831 2832 return false; 2833 } 2834 2835 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const { 2836 unsigned count = 0; 2837 // Count ivars declared in class extension. 2838 for (const auto *Ext : OI->known_extensions()) 2839 count += Ext->ivar_size(); 2840 2841 // Count ivar defined in this class's implementation. This 2842 // includes synthesized ivars. 2843 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) 2844 count += ImplDecl->ivar_size(); 2845 2846 return count; 2847 } 2848 2849 bool ASTContext::isSentinelNullExpr(const Expr *E) { 2850 if (!E) 2851 return false; 2852 2853 // nullptr_t is always treated as null. 2854 if (E->getType()->isNullPtrType()) return true; 2855 2856 if (E->getType()->isAnyPointerType() && 2857 E->IgnoreParenCasts()->isNullPointerConstant(*this, 2858 Expr::NPC_ValueDependentIsNull)) 2859 return true; 2860 2861 // Unfortunately, __null has type 'int'. 2862 if (isa<GNUNullExpr>(E)) return true; 2863 2864 return false; 2865 } 2866 2867 /// Get the implementation of ObjCInterfaceDecl, or nullptr if none 2868 /// exists. 2869 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) { 2870 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 2871 I = ObjCImpls.find(D); 2872 if (I != ObjCImpls.end()) 2873 return cast<ObjCImplementationDecl>(I->second); 2874 return nullptr; 2875 } 2876 2877 /// Get the implementation of ObjCCategoryDecl, or nullptr if none 2878 /// exists. 2879 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) { 2880 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 2881 I = ObjCImpls.find(D); 2882 if (I != ObjCImpls.end()) 2883 return cast<ObjCCategoryImplDecl>(I->second); 2884 return nullptr; 2885 } 2886 2887 /// Set the implementation of ObjCInterfaceDecl. 2888 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD, 2889 ObjCImplementationDecl *ImplD) { 2890 assert(IFaceD && ImplD && "Passed null params"); 2891 ObjCImpls[IFaceD] = ImplD; 2892 } 2893 2894 /// Set the implementation of ObjCCategoryDecl. 2895 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD, 2896 ObjCCategoryImplDecl *ImplD) { 2897 assert(CatD && ImplD && "Passed null params"); 2898 ObjCImpls[CatD] = ImplD; 2899 } 2900 2901 const ObjCMethodDecl * 2902 ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const { 2903 return ObjCMethodRedecls.lookup(MD); 2904 } 2905 2906 void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD, 2907 const ObjCMethodDecl *Redecl) { 2908 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration"); 2909 ObjCMethodRedecls[MD] = Redecl; 2910 } 2911 2912 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface( 2913 const NamedDecl *ND) const { 2914 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext())) 2915 return ID; 2916 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext())) 2917 return CD->getClassInterface(); 2918 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext())) 2919 return IMD->getClassInterface(); 2920 2921 return nullptr; 2922 } 2923 2924 /// Get the copy initialization expression of VarDecl, or nullptr if 2925 /// none exists. 2926 BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const { 2927 assert(VD && "Passed null params"); 2928 assert(VD->hasAttr<BlocksAttr>() && 2929 "getBlockVarCopyInits - not __block var"); 2930 auto I = BlockVarCopyInits.find(VD); 2931 if (I != BlockVarCopyInits.end()) 2932 return I->second; 2933 return {nullptr, false}; 2934 } 2935 2936 /// Set the copy initialization expression of a block var decl. 2937 void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr, 2938 bool CanThrow) { 2939 assert(VD && CopyExpr && "Passed null params"); 2940 assert(VD->hasAttr<BlocksAttr>() && 2941 "setBlockVarCopyInits - not __block var"); 2942 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow); 2943 } 2944 2945 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T, 2946 unsigned DataSize) const { 2947 if (!DataSize) 2948 DataSize = TypeLoc::getFullDataSizeForType(T); 2949 else 2950 assert(DataSize == TypeLoc::getFullDataSizeForType(T) && 2951 "incorrect data size provided to CreateTypeSourceInfo!"); 2952 2953 auto *TInfo = 2954 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8); 2955 new (TInfo) TypeSourceInfo(T); 2956 return TInfo; 2957 } 2958 2959 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T, 2960 SourceLocation L) const { 2961 TypeSourceInfo *DI = CreateTypeSourceInfo(T); 2962 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L); 2963 return DI; 2964 } 2965 2966 const ASTRecordLayout & 2967 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const { 2968 return getObjCLayout(D, nullptr); 2969 } 2970 2971 const ASTRecordLayout & 2972 ASTContext::getASTObjCImplementationLayout( 2973 const ObjCImplementationDecl *D) const { 2974 return getObjCLayout(D->getClassInterface(), D); 2975 } 2976 2977 //===----------------------------------------------------------------------===// 2978 // Type creation/memoization methods 2979 //===----------------------------------------------------------------------===// 2980 2981 QualType 2982 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const { 2983 unsigned fastQuals = quals.getFastQualifiers(); 2984 quals.removeFastQualifiers(); 2985 2986 // Check if we've already instantiated this type. 2987 llvm::FoldingSetNodeID ID; 2988 ExtQuals::Profile(ID, baseType, quals); 2989 void *insertPos = nullptr; 2990 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) { 2991 assert(eq->getQualifiers() == quals); 2992 return QualType(eq, fastQuals); 2993 } 2994 2995 // If the base type is not canonical, make the appropriate canonical type. 2996 QualType canon; 2997 if (!baseType->isCanonicalUnqualified()) { 2998 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split(); 2999 canonSplit.Quals.addConsistentQualifiers(quals); 3000 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals); 3001 3002 // Re-find the insert position. 3003 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos); 3004 } 3005 3006 auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals); 3007 ExtQualNodes.InsertNode(eq, insertPos); 3008 return QualType(eq, fastQuals); 3009 } 3010 3011 QualType ASTContext::getAddrSpaceQualType(QualType T, 3012 LangAS AddressSpace) const { 3013 QualType CanT = getCanonicalType(T); 3014 if (CanT.getAddressSpace() == AddressSpace) 3015 return T; 3016 3017 // If we are composing extended qualifiers together, merge together 3018 // into one ExtQuals node. 3019 QualifierCollector Quals; 3020 const Type *TypeNode = Quals.strip(T); 3021 3022 // If this type already has an address space specified, it cannot get 3023 // another one. 3024 assert(!Quals.hasAddressSpace() && 3025 "Type cannot be in multiple addr spaces!"); 3026 Quals.addAddressSpace(AddressSpace); 3027 3028 return getExtQualType(TypeNode, Quals); 3029 } 3030 3031 QualType ASTContext::removeAddrSpaceQualType(QualType T) const { 3032 // If the type is not qualified with an address space, just return it 3033 // immediately. 3034 if (!T.hasAddressSpace()) 3035 return T; 3036 3037 // If we are composing extended qualifiers together, merge together 3038 // into one ExtQuals node. 3039 QualifierCollector Quals; 3040 const Type *TypeNode; 3041 3042 while (T.hasAddressSpace()) { 3043 TypeNode = Quals.strip(T); 3044 3045 // If the type no longer has an address space after stripping qualifiers, 3046 // jump out. 3047 if (!QualType(TypeNode, 0).hasAddressSpace()) 3048 break; 3049 3050 // There might be sugar in the way. Strip it and try again. 3051 T = T.getSingleStepDesugaredType(*this); 3052 } 3053 3054 Quals.removeAddressSpace(); 3055 3056 // Removal of the address space can mean there are no longer any 3057 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts) 3058 // or required. 3059 if (Quals.hasNonFastQualifiers()) 3060 return getExtQualType(TypeNode, Quals); 3061 else 3062 return QualType(TypeNode, Quals.getFastQualifiers()); 3063 } 3064 3065 QualType ASTContext::getObjCGCQualType(QualType T, 3066 Qualifiers::GC GCAttr) const { 3067 QualType CanT = getCanonicalType(T); 3068 if (CanT.getObjCGCAttr() == GCAttr) 3069 return T; 3070 3071 if (const auto *ptr = T->getAs<PointerType>()) { 3072 QualType Pointee = ptr->getPointeeType(); 3073 if (Pointee->isAnyPointerType()) { 3074 QualType ResultType = getObjCGCQualType(Pointee, GCAttr); 3075 return getPointerType(ResultType); 3076 } 3077 } 3078 3079 // If we are composing extended qualifiers together, merge together 3080 // into one ExtQuals node. 3081 QualifierCollector Quals; 3082 const Type *TypeNode = Quals.strip(T); 3083 3084 // If this type already has an ObjCGC specified, it cannot get 3085 // another one. 3086 assert(!Quals.hasObjCGCAttr() && 3087 "Type cannot have multiple ObjCGCs!"); 3088 Quals.addObjCGCAttr(GCAttr); 3089 3090 return getExtQualType(TypeNode, Quals); 3091 } 3092 3093 QualType ASTContext::removePtrSizeAddrSpace(QualType T) const { 3094 if (const PointerType *Ptr = T->getAs<PointerType>()) { 3095 QualType Pointee = Ptr->getPointeeType(); 3096 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) { 3097 return getPointerType(removeAddrSpaceQualType(Pointee)); 3098 } 3099 } 3100 return T; 3101 } 3102 3103 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T, 3104 FunctionType::ExtInfo Info) { 3105 if (T->getExtInfo() == Info) 3106 return T; 3107 3108 QualType Result; 3109 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) { 3110 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info); 3111 } else { 3112 const auto *FPT = cast<FunctionProtoType>(T); 3113 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 3114 EPI.ExtInfo = Info; 3115 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI); 3116 } 3117 3118 return cast<FunctionType>(Result.getTypePtr()); 3119 } 3120 3121 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD, 3122 QualType ResultType) { 3123 FD = FD->getMostRecentDecl(); 3124 while (true) { 3125 const auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 3126 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 3127 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI)); 3128 if (FunctionDecl *Next = FD->getPreviousDecl()) 3129 FD = Next; 3130 else 3131 break; 3132 } 3133 if (ASTMutationListener *L = getASTMutationListener()) 3134 L->DeducedReturnType(FD, ResultType); 3135 } 3136 3137 /// Get a function type and produce the equivalent function type with the 3138 /// specified exception specification. Type sugar that can be present on a 3139 /// declaration of a function with an exception specification is permitted 3140 /// and preserved. Other type sugar (for instance, typedefs) is not. 3141 QualType ASTContext::getFunctionTypeWithExceptionSpec( 3142 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) { 3143 // Might have some parens. 3144 if (const auto *PT = dyn_cast<ParenType>(Orig)) 3145 return getParenType( 3146 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI)); 3147 3148 // Might be wrapped in a macro qualified type. 3149 if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig)) 3150 return getMacroQualifiedType( 3151 getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI), 3152 MQT->getMacroIdentifier()); 3153 3154 // Might have a calling-convention attribute. 3155 if (const auto *AT = dyn_cast<AttributedType>(Orig)) 3156 return getAttributedType( 3157 AT->getAttrKind(), 3158 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI), 3159 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI)); 3160 3161 // Anything else must be a function type. Rebuild it with the new exception 3162 // specification. 3163 const auto *Proto = Orig->castAs<FunctionProtoType>(); 3164 return getFunctionType( 3165 Proto->getReturnType(), Proto->getParamTypes(), 3166 Proto->getExtProtoInfo().withExceptionSpec(ESI)); 3167 } 3168 3169 bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T, 3170 QualType U) { 3171 return hasSameType(T, U) || 3172 (getLangOpts().CPlusPlus17 && 3173 hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None), 3174 getFunctionTypeWithExceptionSpec(U, EST_None))); 3175 } 3176 3177 QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) { 3178 if (const auto *Proto = T->getAs<FunctionProtoType>()) { 3179 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType()); 3180 SmallVector<QualType, 16> Args(Proto->param_types()); 3181 for (unsigned i = 0, n = Args.size(); i != n; ++i) 3182 Args[i] = removePtrSizeAddrSpace(Args[i]); 3183 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo()); 3184 } 3185 3186 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) { 3187 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType()); 3188 return getFunctionNoProtoType(RetTy, Proto->getExtInfo()); 3189 } 3190 3191 return T; 3192 } 3193 3194 bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) { 3195 return hasSameType(T, U) || 3196 hasSameType(getFunctionTypeWithoutPtrSizes(T), 3197 getFunctionTypeWithoutPtrSizes(U)); 3198 } 3199 3200 void ASTContext::adjustExceptionSpec( 3201 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, 3202 bool AsWritten) { 3203 // Update the type. 3204 QualType Updated = 3205 getFunctionTypeWithExceptionSpec(FD->getType(), ESI); 3206 FD->setType(Updated); 3207 3208 if (!AsWritten) 3209 return; 3210 3211 // Update the type in the type source information too. 3212 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) { 3213 // If the type and the type-as-written differ, we may need to update 3214 // the type-as-written too. 3215 if (TSInfo->getType() != FD->getType()) 3216 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI); 3217 3218 // FIXME: When we get proper type location information for exceptions, 3219 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch 3220 // up the TypeSourceInfo; 3221 assert(TypeLoc::getFullDataSizeForType(Updated) == 3222 TypeLoc::getFullDataSizeForType(TSInfo->getType()) && 3223 "TypeLoc size mismatch from updating exception specification"); 3224 TSInfo->overrideType(Updated); 3225 } 3226 } 3227 3228 /// getComplexType - Return the uniqued reference to the type for a complex 3229 /// number with the specified element type. 3230 QualType ASTContext::getComplexType(QualType T) const { 3231 // Unique pointers, to guarantee there is only one pointer of a particular 3232 // structure. 3233 llvm::FoldingSetNodeID ID; 3234 ComplexType::Profile(ID, T); 3235 3236 void *InsertPos = nullptr; 3237 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos)) 3238 return QualType(CT, 0); 3239 3240 // If the pointee type isn't canonical, this won't be a canonical type either, 3241 // so fill in the canonical type field. 3242 QualType Canonical; 3243 if (!T.isCanonical()) { 3244 Canonical = getComplexType(getCanonicalType(T)); 3245 3246 // Get the new insert position for the node we care about. 3247 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos); 3248 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3249 } 3250 auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical); 3251 Types.push_back(New); 3252 ComplexTypes.InsertNode(New, InsertPos); 3253 return QualType(New, 0); 3254 } 3255 3256 /// getPointerType - Return the uniqued reference to the type for a pointer to 3257 /// the specified type. 3258 QualType ASTContext::getPointerType(QualType T) const { 3259 // Unique pointers, to guarantee there is only one pointer of a particular 3260 // structure. 3261 llvm::FoldingSetNodeID ID; 3262 PointerType::Profile(ID, T); 3263 3264 void *InsertPos = nullptr; 3265 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3266 return QualType(PT, 0); 3267 3268 // If the pointee type isn't canonical, this won't be a canonical type either, 3269 // so fill in the canonical type field. 3270 QualType Canonical; 3271 if (!T.isCanonical()) { 3272 Canonical = getPointerType(getCanonicalType(T)); 3273 3274 // Get the new insert position for the node we care about. 3275 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3276 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3277 } 3278 auto *New = new (*this, TypeAlignment) PointerType(T, Canonical); 3279 Types.push_back(New); 3280 PointerTypes.InsertNode(New, InsertPos); 3281 return QualType(New, 0); 3282 } 3283 3284 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const { 3285 llvm::FoldingSetNodeID ID; 3286 AdjustedType::Profile(ID, Orig, New); 3287 void *InsertPos = nullptr; 3288 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3289 if (AT) 3290 return QualType(AT, 0); 3291 3292 QualType Canonical = getCanonicalType(New); 3293 3294 // Get the new insert position for the node we care about. 3295 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3296 assert(!AT && "Shouldn't be in the map!"); 3297 3298 AT = new (*this, TypeAlignment) 3299 AdjustedType(Type::Adjusted, Orig, New, Canonical); 3300 Types.push_back(AT); 3301 AdjustedTypes.InsertNode(AT, InsertPos); 3302 return QualType(AT, 0); 3303 } 3304 3305 QualType ASTContext::getDecayedType(QualType T) const { 3306 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay"); 3307 3308 QualType Decayed; 3309 3310 // C99 6.7.5.3p7: 3311 // A declaration of a parameter as "array of type" shall be 3312 // adjusted to "qualified pointer to type", where the type 3313 // qualifiers (if any) are those specified within the [ and ] of 3314 // the array type derivation. 3315 if (T->isArrayType()) 3316 Decayed = getArrayDecayedType(T); 3317 3318 // C99 6.7.5.3p8: 3319 // A declaration of a parameter as "function returning type" 3320 // shall be adjusted to "pointer to function returning type", as 3321 // in 6.3.2.1. 3322 if (T->isFunctionType()) 3323 Decayed = getPointerType(T); 3324 3325 llvm::FoldingSetNodeID ID; 3326 AdjustedType::Profile(ID, T, Decayed); 3327 void *InsertPos = nullptr; 3328 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3329 if (AT) 3330 return QualType(AT, 0); 3331 3332 QualType Canonical = getCanonicalType(Decayed); 3333 3334 // Get the new insert position for the node we care about. 3335 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3336 assert(!AT && "Shouldn't be in the map!"); 3337 3338 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical); 3339 Types.push_back(AT); 3340 AdjustedTypes.InsertNode(AT, InsertPos); 3341 return QualType(AT, 0); 3342 } 3343 3344 /// getBlockPointerType - Return the uniqued reference to the type for 3345 /// a pointer to the specified block. 3346 QualType ASTContext::getBlockPointerType(QualType T) const { 3347 assert(T->isFunctionType() && "block of function types only"); 3348 // Unique pointers, to guarantee there is only one block of a particular 3349 // structure. 3350 llvm::FoldingSetNodeID ID; 3351 BlockPointerType::Profile(ID, T); 3352 3353 void *InsertPos = nullptr; 3354 if (BlockPointerType *PT = 3355 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3356 return QualType(PT, 0); 3357 3358 // If the block pointee type isn't canonical, this won't be a canonical 3359 // type either so fill in the canonical type field. 3360 QualType Canonical; 3361 if (!T.isCanonical()) { 3362 Canonical = getBlockPointerType(getCanonicalType(T)); 3363 3364 // Get the new insert position for the node we care about. 3365 BlockPointerType *NewIP = 3366 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3367 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3368 } 3369 auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical); 3370 Types.push_back(New); 3371 BlockPointerTypes.InsertNode(New, InsertPos); 3372 return QualType(New, 0); 3373 } 3374 3375 /// getLValueReferenceType - Return the uniqued reference to the type for an 3376 /// lvalue reference to the specified type. 3377 QualType 3378 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const { 3379 assert((!T->isPlaceholderType() || 3380 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) && 3381 "Unresolved placeholder type"); 3382 3383 // Unique pointers, to guarantee there is only one pointer of a particular 3384 // structure. 3385 llvm::FoldingSetNodeID ID; 3386 ReferenceType::Profile(ID, T, SpelledAsLValue); 3387 3388 void *InsertPos = nullptr; 3389 if (LValueReferenceType *RT = 3390 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 3391 return QualType(RT, 0); 3392 3393 const auto *InnerRef = T->getAs<ReferenceType>(); 3394 3395 // If the referencee type isn't canonical, this won't be a canonical type 3396 // either, so fill in the canonical type field. 3397 QualType Canonical; 3398 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) { 3399 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 3400 Canonical = getLValueReferenceType(getCanonicalType(PointeeType)); 3401 3402 // Get the new insert position for the node we care about. 3403 LValueReferenceType *NewIP = 3404 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 3405 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3406 } 3407 3408 auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical, 3409 SpelledAsLValue); 3410 Types.push_back(New); 3411 LValueReferenceTypes.InsertNode(New, InsertPos); 3412 3413 return QualType(New, 0); 3414 } 3415 3416 /// getRValueReferenceType - Return the uniqued reference to the type for an 3417 /// rvalue reference to the specified type. 3418 QualType ASTContext::getRValueReferenceType(QualType T) const { 3419 assert((!T->isPlaceholderType() || 3420 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) && 3421 "Unresolved placeholder type"); 3422 3423 // Unique pointers, to guarantee there is only one pointer of a particular 3424 // structure. 3425 llvm::FoldingSetNodeID ID; 3426 ReferenceType::Profile(ID, T, false); 3427 3428 void *InsertPos = nullptr; 3429 if (RValueReferenceType *RT = 3430 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 3431 return QualType(RT, 0); 3432 3433 const auto *InnerRef = T->getAs<ReferenceType>(); 3434 3435 // If the referencee type isn't canonical, this won't be a canonical type 3436 // either, so fill in the canonical type field. 3437 QualType Canonical; 3438 if (InnerRef || !T.isCanonical()) { 3439 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 3440 Canonical = getRValueReferenceType(getCanonicalType(PointeeType)); 3441 3442 // Get the new insert position for the node we care about. 3443 RValueReferenceType *NewIP = 3444 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 3445 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3446 } 3447 3448 auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical); 3449 Types.push_back(New); 3450 RValueReferenceTypes.InsertNode(New, InsertPos); 3451 return QualType(New, 0); 3452 } 3453 3454 /// getMemberPointerType - Return the uniqued reference to the type for a 3455 /// member pointer to the specified type, in the specified class. 3456 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const { 3457 // Unique pointers, to guarantee there is only one pointer of a particular 3458 // structure. 3459 llvm::FoldingSetNodeID ID; 3460 MemberPointerType::Profile(ID, T, Cls); 3461 3462 void *InsertPos = nullptr; 3463 if (MemberPointerType *PT = 3464 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3465 return QualType(PT, 0); 3466 3467 // If the pointee or class type isn't canonical, this won't be a canonical 3468 // type either, so fill in the canonical type field. 3469 QualType Canonical; 3470 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) { 3471 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls)); 3472 3473 // Get the new insert position for the node we care about. 3474 MemberPointerType *NewIP = 3475 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3476 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3477 } 3478 auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical); 3479 Types.push_back(New); 3480 MemberPointerTypes.InsertNode(New, InsertPos); 3481 return QualType(New, 0); 3482 } 3483 3484 /// getConstantArrayType - Return the unique reference to the type for an 3485 /// array of the specified element type. 3486 QualType ASTContext::getConstantArrayType(QualType EltTy, 3487 const llvm::APInt &ArySizeIn, 3488 const Expr *SizeExpr, 3489 ArrayType::ArraySizeModifier ASM, 3490 unsigned IndexTypeQuals) const { 3491 assert((EltTy->isDependentType() || 3492 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) && 3493 "Constant array of VLAs is illegal!"); 3494 3495 // We only need the size as part of the type if it's instantiation-dependent. 3496 if (SizeExpr && !SizeExpr->isInstantiationDependent()) 3497 SizeExpr = nullptr; 3498 3499 // Convert the array size into a canonical width matching the pointer size for 3500 // the target. 3501 llvm::APInt ArySize(ArySizeIn); 3502 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth()); 3503 3504 llvm::FoldingSetNodeID ID; 3505 ConstantArrayType::Profile(ID, *this, EltTy, ArySize, SizeExpr, ASM, 3506 IndexTypeQuals); 3507 3508 void *InsertPos = nullptr; 3509 if (ConstantArrayType *ATP = 3510 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 3511 return QualType(ATP, 0); 3512 3513 // If the element type isn't canonical or has qualifiers, or the array bound 3514 // is instantiation-dependent, this won't be a canonical type either, so fill 3515 // in the canonical type field. 3516 QualType Canon; 3517 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) { 3518 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 3519 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr, 3520 ASM, IndexTypeQuals); 3521 Canon = getQualifiedType(Canon, canonSplit.Quals); 3522 3523 // Get the new insert position for the node we care about. 3524 ConstantArrayType *NewIP = 3525 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 3526 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3527 } 3528 3529 void *Mem = Allocate( 3530 ConstantArrayType::totalSizeToAlloc<const Expr *>(SizeExpr ? 1 : 0), 3531 TypeAlignment); 3532 auto *New = new (Mem) 3533 ConstantArrayType(EltTy, Canon, ArySize, SizeExpr, ASM, IndexTypeQuals); 3534 ConstantArrayTypes.InsertNode(New, InsertPos); 3535 Types.push_back(New); 3536 return QualType(New, 0); 3537 } 3538 3539 /// getVariableArrayDecayedType - Turns the given type, which may be 3540 /// variably-modified, into the corresponding type with all the known 3541 /// sizes replaced with [*]. 3542 QualType ASTContext::getVariableArrayDecayedType(QualType type) const { 3543 // Vastly most common case. 3544 if (!type->isVariablyModifiedType()) return type; 3545 3546 QualType result; 3547 3548 SplitQualType split = type.getSplitDesugaredType(); 3549 const Type *ty = split.Ty; 3550 switch (ty->getTypeClass()) { 3551 #define TYPE(Class, Base) 3552 #define ABSTRACT_TYPE(Class, Base) 3553 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 3554 #include "clang/AST/TypeNodes.inc" 3555 llvm_unreachable("didn't desugar past all non-canonical types?"); 3556 3557 // These types should never be variably-modified. 3558 case Type::Builtin: 3559 case Type::Complex: 3560 case Type::Vector: 3561 case Type::DependentVector: 3562 case Type::ExtVector: 3563 case Type::DependentSizedExtVector: 3564 case Type::ConstantMatrix: 3565 case Type::DependentSizedMatrix: 3566 case Type::DependentAddressSpace: 3567 case Type::ObjCObject: 3568 case Type::ObjCInterface: 3569 case Type::ObjCObjectPointer: 3570 case Type::Record: 3571 case Type::Enum: 3572 case Type::UnresolvedUsing: 3573 case Type::TypeOfExpr: 3574 case Type::TypeOf: 3575 case Type::Decltype: 3576 case Type::UnaryTransform: 3577 case Type::DependentName: 3578 case Type::InjectedClassName: 3579 case Type::TemplateSpecialization: 3580 case Type::DependentTemplateSpecialization: 3581 case Type::TemplateTypeParm: 3582 case Type::SubstTemplateTypeParmPack: 3583 case Type::Auto: 3584 case Type::DeducedTemplateSpecialization: 3585 case Type::PackExpansion: 3586 case Type::BitInt: 3587 case Type::DependentBitInt: 3588 llvm_unreachable("type should never be variably-modified"); 3589 3590 // These types can be variably-modified but should never need to 3591 // further decay. 3592 case Type::FunctionNoProto: 3593 case Type::FunctionProto: 3594 case Type::BlockPointer: 3595 case Type::MemberPointer: 3596 case Type::Pipe: 3597 return type; 3598 3599 // These types can be variably-modified. All these modifications 3600 // preserve structure except as noted by comments. 3601 // TODO: if we ever care about optimizing VLAs, there are no-op 3602 // optimizations available here. 3603 case Type::Pointer: 3604 result = getPointerType(getVariableArrayDecayedType( 3605 cast<PointerType>(ty)->getPointeeType())); 3606 break; 3607 3608 case Type::LValueReference: { 3609 const auto *lv = cast<LValueReferenceType>(ty); 3610 result = getLValueReferenceType( 3611 getVariableArrayDecayedType(lv->getPointeeType()), 3612 lv->isSpelledAsLValue()); 3613 break; 3614 } 3615 3616 case Type::RValueReference: { 3617 const auto *lv = cast<RValueReferenceType>(ty); 3618 result = getRValueReferenceType( 3619 getVariableArrayDecayedType(lv->getPointeeType())); 3620 break; 3621 } 3622 3623 case Type::Atomic: { 3624 const auto *at = cast<AtomicType>(ty); 3625 result = getAtomicType(getVariableArrayDecayedType(at->getValueType())); 3626 break; 3627 } 3628 3629 case Type::ConstantArray: { 3630 const auto *cat = cast<ConstantArrayType>(ty); 3631 result = getConstantArrayType( 3632 getVariableArrayDecayedType(cat->getElementType()), 3633 cat->getSize(), 3634 cat->getSizeExpr(), 3635 cat->getSizeModifier(), 3636 cat->getIndexTypeCVRQualifiers()); 3637 break; 3638 } 3639 3640 case Type::DependentSizedArray: { 3641 const auto *dat = cast<DependentSizedArrayType>(ty); 3642 result = getDependentSizedArrayType( 3643 getVariableArrayDecayedType(dat->getElementType()), 3644 dat->getSizeExpr(), 3645 dat->getSizeModifier(), 3646 dat->getIndexTypeCVRQualifiers(), 3647 dat->getBracketsRange()); 3648 break; 3649 } 3650 3651 // Turn incomplete types into [*] types. 3652 case Type::IncompleteArray: { 3653 const auto *iat = cast<IncompleteArrayType>(ty); 3654 result = getVariableArrayType( 3655 getVariableArrayDecayedType(iat->getElementType()), 3656 /*size*/ nullptr, 3657 ArrayType::Normal, 3658 iat->getIndexTypeCVRQualifiers(), 3659 SourceRange()); 3660 break; 3661 } 3662 3663 // Turn VLA types into [*] types. 3664 case Type::VariableArray: { 3665 const auto *vat = cast<VariableArrayType>(ty); 3666 result = getVariableArrayType( 3667 getVariableArrayDecayedType(vat->getElementType()), 3668 /*size*/ nullptr, 3669 ArrayType::Star, 3670 vat->getIndexTypeCVRQualifiers(), 3671 vat->getBracketsRange()); 3672 break; 3673 } 3674 } 3675 3676 // Apply the top-level qualifiers from the original. 3677 return getQualifiedType(result, split.Quals); 3678 } 3679 3680 /// getVariableArrayType - Returns a non-unique reference to the type for a 3681 /// variable array of the specified element type. 3682 QualType ASTContext::getVariableArrayType(QualType EltTy, 3683 Expr *NumElts, 3684 ArrayType::ArraySizeModifier ASM, 3685 unsigned IndexTypeQuals, 3686 SourceRange Brackets) const { 3687 // Since we don't unique expressions, it isn't possible to unique VLA's 3688 // that have an expression provided for their size. 3689 QualType Canon; 3690 3691 // Be sure to pull qualifiers off the element type. 3692 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) { 3693 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 3694 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM, 3695 IndexTypeQuals, Brackets); 3696 Canon = getQualifiedType(Canon, canonSplit.Quals); 3697 } 3698 3699 auto *New = new (*this, TypeAlignment) 3700 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets); 3701 3702 VariableArrayTypes.push_back(New); 3703 Types.push_back(New); 3704 return QualType(New, 0); 3705 } 3706 3707 /// getDependentSizedArrayType - Returns a non-unique reference to 3708 /// the type for a dependently-sized array of the specified element 3709 /// type. 3710 QualType ASTContext::getDependentSizedArrayType(QualType elementType, 3711 Expr *numElements, 3712 ArrayType::ArraySizeModifier ASM, 3713 unsigned elementTypeQuals, 3714 SourceRange brackets) const { 3715 assert((!numElements || numElements->isTypeDependent() || 3716 numElements->isValueDependent()) && 3717 "Size must be type- or value-dependent!"); 3718 3719 // Dependently-sized array types that do not have a specified number 3720 // of elements will have their sizes deduced from a dependent 3721 // initializer. We do no canonicalization here at all, which is okay 3722 // because they can't be used in most locations. 3723 if (!numElements) { 3724 auto *newType 3725 = new (*this, TypeAlignment) 3726 DependentSizedArrayType(*this, elementType, QualType(), 3727 numElements, ASM, elementTypeQuals, 3728 brackets); 3729 Types.push_back(newType); 3730 return QualType(newType, 0); 3731 } 3732 3733 // Otherwise, we actually build a new type every time, but we 3734 // also build a canonical type. 3735 3736 SplitQualType canonElementType = getCanonicalType(elementType).split(); 3737 3738 void *insertPos = nullptr; 3739 llvm::FoldingSetNodeID ID; 3740 DependentSizedArrayType::Profile(ID, *this, 3741 QualType(canonElementType.Ty, 0), 3742 ASM, elementTypeQuals, numElements); 3743 3744 // Look for an existing type with these properties. 3745 DependentSizedArrayType *canonTy = 3746 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos); 3747 3748 // If we don't have one, build one. 3749 if (!canonTy) { 3750 canonTy = new (*this, TypeAlignment) 3751 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0), 3752 QualType(), numElements, ASM, elementTypeQuals, 3753 brackets); 3754 DependentSizedArrayTypes.InsertNode(canonTy, insertPos); 3755 Types.push_back(canonTy); 3756 } 3757 3758 // Apply qualifiers from the element type to the array. 3759 QualType canon = getQualifiedType(QualType(canonTy,0), 3760 canonElementType.Quals); 3761 3762 // If we didn't need extra canonicalization for the element type or the size 3763 // expression, then just use that as our result. 3764 if (QualType(canonElementType.Ty, 0) == elementType && 3765 canonTy->getSizeExpr() == numElements) 3766 return canon; 3767 3768 // Otherwise, we need to build a type which follows the spelling 3769 // of the element type. 3770 auto *sugaredType 3771 = new (*this, TypeAlignment) 3772 DependentSizedArrayType(*this, elementType, canon, numElements, 3773 ASM, elementTypeQuals, brackets); 3774 Types.push_back(sugaredType); 3775 return QualType(sugaredType, 0); 3776 } 3777 3778 QualType ASTContext::getIncompleteArrayType(QualType elementType, 3779 ArrayType::ArraySizeModifier ASM, 3780 unsigned elementTypeQuals) const { 3781 llvm::FoldingSetNodeID ID; 3782 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals); 3783 3784 void *insertPos = nullptr; 3785 if (IncompleteArrayType *iat = 3786 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos)) 3787 return QualType(iat, 0); 3788 3789 // If the element type isn't canonical, this won't be a canonical type 3790 // either, so fill in the canonical type field. We also have to pull 3791 // qualifiers off the element type. 3792 QualType canon; 3793 3794 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) { 3795 SplitQualType canonSplit = getCanonicalType(elementType).split(); 3796 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0), 3797 ASM, elementTypeQuals); 3798 canon = getQualifiedType(canon, canonSplit.Quals); 3799 3800 // Get the new insert position for the node we care about. 3801 IncompleteArrayType *existing = 3802 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos); 3803 assert(!existing && "Shouldn't be in the map!"); (void) existing; 3804 } 3805 3806 auto *newType = new (*this, TypeAlignment) 3807 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals); 3808 3809 IncompleteArrayTypes.InsertNode(newType, insertPos); 3810 Types.push_back(newType); 3811 return QualType(newType, 0); 3812 } 3813 3814 ASTContext::BuiltinVectorTypeInfo 3815 ASTContext::getBuiltinVectorTypeInfo(const BuiltinType *Ty) const { 3816 #define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \ 3817 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \ 3818 NUMVECTORS}; 3819 3820 #define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \ 3821 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS}; 3822 3823 switch (Ty->getKind()) { 3824 default: 3825 llvm_unreachable("Unsupported builtin vector type"); 3826 case BuiltinType::SveInt8: 3827 return SVE_INT_ELTTY(8, 16, true, 1); 3828 case BuiltinType::SveUint8: 3829 return SVE_INT_ELTTY(8, 16, false, 1); 3830 case BuiltinType::SveInt8x2: 3831 return SVE_INT_ELTTY(8, 16, true, 2); 3832 case BuiltinType::SveUint8x2: 3833 return SVE_INT_ELTTY(8, 16, false, 2); 3834 case BuiltinType::SveInt8x3: 3835 return SVE_INT_ELTTY(8, 16, true, 3); 3836 case BuiltinType::SveUint8x3: 3837 return SVE_INT_ELTTY(8, 16, false, 3); 3838 case BuiltinType::SveInt8x4: 3839 return SVE_INT_ELTTY(8, 16, true, 4); 3840 case BuiltinType::SveUint8x4: 3841 return SVE_INT_ELTTY(8, 16, false, 4); 3842 case BuiltinType::SveInt16: 3843 return SVE_INT_ELTTY(16, 8, true, 1); 3844 case BuiltinType::SveUint16: 3845 return SVE_INT_ELTTY(16, 8, false, 1); 3846 case BuiltinType::SveInt16x2: 3847 return SVE_INT_ELTTY(16, 8, true, 2); 3848 case BuiltinType::SveUint16x2: 3849 return SVE_INT_ELTTY(16, 8, false, 2); 3850 case BuiltinType::SveInt16x3: 3851 return SVE_INT_ELTTY(16, 8, true, 3); 3852 case BuiltinType::SveUint16x3: 3853 return SVE_INT_ELTTY(16, 8, false, 3); 3854 case BuiltinType::SveInt16x4: 3855 return SVE_INT_ELTTY(16, 8, true, 4); 3856 case BuiltinType::SveUint16x4: 3857 return SVE_INT_ELTTY(16, 8, false, 4); 3858 case BuiltinType::SveInt32: 3859 return SVE_INT_ELTTY(32, 4, true, 1); 3860 case BuiltinType::SveUint32: 3861 return SVE_INT_ELTTY(32, 4, false, 1); 3862 case BuiltinType::SveInt32x2: 3863 return SVE_INT_ELTTY(32, 4, true, 2); 3864 case BuiltinType::SveUint32x2: 3865 return SVE_INT_ELTTY(32, 4, false, 2); 3866 case BuiltinType::SveInt32x3: 3867 return SVE_INT_ELTTY(32, 4, true, 3); 3868 case BuiltinType::SveUint32x3: 3869 return SVE_INT_ELTTY(32, 4, false, 3); 3870 case BuiltinType::SveInt32x4: 3871 return SVE_INT_ELTTY(32, 4, true, 4); 3872 case BuiltinType::SveUint32x4: 3873 return SVE_INT_ELTTY(32, 4, false, 4); 3874 case BuiltinType::SveInt64: 3875 return SVE_INT_ELTTY(64, 2, true, 1); 3876 case BuiltinType::SveUint64: 3877 return SVE_INT_ELTTY(64, 2, false, 1); 3878 case BuiltinType::SveInt64x2: 3879 return SVE_INT_ELTTY(64, 2, true, 2); 3880 case BuiltinType::SveUint64x2: 3881 return SVE_INT_ELTTY(64, 2, false, 2); 3882 case BuiltinType::SveInt64x3: 3883 return SVE_INT_ELTTY(64, 2, true, 3); 3884 case BuiltinType::SveUint64x3: 3885 return SVE_INT_ELTTY(64, 2, false, 3); 3886 case BuiltinType::SveInt64x4: 3887 return SVE_INT_ELTTY(64, 2, true, 4); 3888 case BuiltinType::SveUint64x4: 3889 return SVE_INT_ELTTY(64, 2, false, 4); 3890 case BuiltinType::SveBool: 3891 return SVE_ELTTY(BoolTy, 16, 1); 3892 case BuiltinType::SveFloat16: 3893 return SVE_ELTTY(HalfTy, 8, 1); 3894 case BuiltinType::SveFloat16x2: 3895 return SVE_ELTTY(HalfTy, 8, 2); 3896 case BuiltinType::SveFloat16x3: 3897 return SVE_ELTTY(HalfTy, 8, 3); 3898 case BuiltinType::SveFloat16x4: 3899 return SVE_ELTTY(HalfTy, 8, 4); 3900 case BuiltinType::SveFloat32: 3901 return SVE_ELTTY(FloatTy, 4, 1); 3902 case BuiltinType::SveFloat32x2: 3903 return SVE_ELTTY(FloatTy, 4, 2); 3904 case BuiltinType::SveFloat32x3: 3905 return SVE_ELTTY(FloatTy, 4, 3); 3906 case BuiltinType::SveFloat32x4: 3907 return SVE_ELTTY(FloatTy, 4, 4); 3908 case BuiltinType::SveFloat64: 3909 return SVE_ELTTY(DoubleTy, 2, 1); 3910 case BuiltinType::SveFloat64x2: 3911 return SVE_ELTTY(DoubleTy, 2, 2); 3912 case BuiltinType::SveFloat64x3: 3913 return SVE_ELTTY(DoubleTy, 2, 3); 3914 case BuiltinType::SveFloat64x4: 3915 return SVE_ELTTY(DoubleTy, 2, 4); 3916 case BuiltinType::SveBFloat16: 3917 return SVE_ELTTY(BFloat16Ty, 8, 1); 3918 case BuiltinType::SveBFloat16x2: 3919 return SVE_ELTTY(BFloat16Ty, 8, 2); 3920 case BuiltinType::SveBFloat16x3: 3921 return SVE_ELTTY(BFloat16Ty, 8, 3); 3922 case BuiltinType::SveBFloat16x4: 3923 return SVE_ELTTY(BFloat16Ty, 8, 4); 3924 #define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \ 3925 IsSigned) \ 3926 case BuiltinType::Id: \ 3927 return {getIntTypeForBitwidth(ElBits, IsSigned), \ 3928 llvm::ElementCount::getScalable(NumEls), NF}; 3929 #define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \ 3930 case BuiltinType::Id: \ 3931 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \ 3932 llvm::ElementCount::getScalable(NumEls), NF}; 3933 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \ 3934 case BuiltinType::Id: \ 3935 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1}; 3936 #include "clang/Basic/RISCVVTypes.def" 3937 } 3938 } 3939 3940 /// getScalableVectorType - Return the unique reference to a scalable vector 3941 /// type of the specified element type and size. VectorType must be a built-in 3942 /// type. 3943 QualType ASTContext::getScalableVectorType(QualType EltTy, 3944 unsigned NumElts) const { 3945 if (Target->hasAArch64SVETypes()) { 3946 uint64_t EltTySize = getTypeSize(EltTy); 3947 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \ 3948 IsSigned, IsFP, IsBF) \ 3949 if (!EltTy->isBooleanType() && \ 3950 ((EltTy->hasIntegerRepresentation() && \ 3951 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \ 3952 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \ 3953 IsFP && !IsBF) || \ 3954 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \ 3955 IsBF && !IsFP)) && \ 3956 EltTySize == ElBits && NumElts == NumEls) { \ 3957 return SingletonId; \ 3958 } 3959 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \ 3960 if (EltTy->isBooleanType() && NumElts == NumEls) \ 3961 return SingletonId; 3962 #include "clang/Basic/AArch64SVEACLETypes.def" 3963 } else if (Target->hasRISCVVTypes()) { 3964 uint64_t EltTySize = getTypeSize(EltTy); 3965 #define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \ 3966 IsFP) \ 3967 if (!EltTy->isBooleanType() && \ 3968 ((EltTy->hasIntegerRepresentation() && \ 3969 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \ 3970 (EltTy->hasFloatingRepresentation() && IsFP)) && \ 3971 EltTySize == ElBits && NumElts == NumEls) \ 3972 return SingletonId; 3973 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \ 3974 if (EltTy->isBooleanType() && NumElts == NumEls) \ 3975 return SingletonId; 3976 #include "clang/Basic/RISCVVTypes.def" 3977 } 3978 return QualType(); 3979 } 3980 3981 /// getVectorType - Return the unique reference to a vector type of 3982 /// the specified element type and size. VectorType must be a built-in type. 3983 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts, 3984 VectorType::VectorKind VecKind) const { 3985 assert(vecType->isBuiltinType()); 3986 3987 // Check if we've already instantiated a vector of this type. 3988 llvm::FoldingSetNodeID ID; 3989 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind); 3990 3991 void *InsertPos = nullptr; 3992 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 3993 return QualType(VTP, 0); 3994 3995 // If the element type isn't canonical, this won't be a canonical type either, 3996 // so fill in the canonical type field. 3997 QualType Canonical; 3998 if (!vecType.isCanonical()) { 3999 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind); 4000 4001 // Get the new insert position for the node we care about. 4002 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4003 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4004 } 4005 auto *New = new (*this, TypeAlignment) 4006 VectorType(vecType, NumElts, Canonical, VecKind); 4007 VectorTypes.InsertNode(New, InsertPos); 4008 Types.push_back(New); 4009 return QualType(New, 0); 4010 } 4011 4012 QualType 4013 ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr, 4014 SourceLocation AttrLoc, 4015 VectorType::VectorKind VecKind) const { 4016 llvm::FoldingSetNodeID ID; 4017 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr, 4018 VecKind); 4019 void *InsertPos = nullptr; 4020 DependentVectorType *Canon = 4021 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4022 DependentVectorType *New; 4023 4024 if (Canon) { 4025 New = new (*this, TypeAlignment) DependentVectorType( 4026 *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind); 4027 } else { 4028 QualType CanonVecTy = getCanonicalType(VecType); 4029 if (CanonVecTy == VecType) { 4030 New = new (*this, TypeAlignment) DependentVectorType( 4031 *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind); 4032 4033 DependentVectorType *CanonCheck = 4034 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4035 assert(!CanonCheck && 4036 "Dependent-sized vector_size canonical type broken"); 4037 (void)CanonCheck; 4038 DependentVectorTypes.InsertNode(New, InsertPos); 4039 } else { 4040 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr, 4041 SourceLocation(), VecKind); 4042 New = new (*this, TypeAlignment) DependentVectorType( 4043 *this, VecType, CanonTy, SizeExpr, AttrLoc, VecKind); 4044 } 4045 } 4046 4047 Types.push_back(New); 4048 return QualType(New, 0); 4049 } 4050 4051 /// getExtVectorType - Return the unique reference to an extended vector type of 4052 /// the specified element type and size. VectorType must be a built-in type. 4053 QualType 4054 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const { 4055 assert(vecType->isBuiltinType() || vecType->isDependentType()); 4056 4057 // Check if we've already instantiated a vector of this type. 4058 llvm::FoldingSetNodeID ID; 4059 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, 4060 VectorType::GenericVector); 4061 void *InsertPos = nullptr; 4062 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 4063 return QualType(VTP, 0); 4064 4065 // If the element type isn't canonical, this won't be a canonical type either, 4066 // so fill in the canonical type field. 4067 QualType Canonical; 4068 if (!vecType.isCanonical()) { 4069 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts); 4070 4071 // Get the new insert position for the node we care about. 4072 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4073 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4074 } 4075 auto *New = new (*this, TypeAlignment) 4076 ExtVectorType(vecType, NumElts, Canonical); 4077 VectorTypes.InsertNode(New, InsertPos); 4078 Types.push_back(New); 4079 return QualType(New, 0); 4080 } 4081 4082 QualType 4083 ASTContext::getDependentSizedExtVectorType(QualType vecType, 4084 Expr *SizeExpr, 4085 SourceLocation AttrLoc) const { 4086 llvm::FoldingSetNodeID ID; 4087 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType), 4088 SizeExpr); 4089 4090 void *InsertPos = nullptr; 4091 DependentSizedExtVectorType *Canon 4092 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4093 DependentSizedExtVectorType *New; 4094 if (Canon) { 4095 // We already have a canonical version of this array type; use it as 4096 // the canonical type for a newly-built type. 4097 New = new (*this, TypeAlignment) 4098 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0), 4099 SizeExpr, AttrLoc); 4100 } else { 4101 QualType CanonVecTy = getCanonicalType(vecType); 4102 if (CanonVecTy == vecType) { 4103 New = new (*this, TypeAlignment) 4104 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr, 4105 AttrLoc); 4106 4107 DependentSizedExtVectorType *CanonCheck 4108 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4109 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken"); 4110 (void)CanonCheck; 4111 DependentSizedExtVectorTypes.InsertNode(New, InsertPos); 4112 } else { 4113 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr, 4114 SourceLocation()); 4115 New = new (*this, TypeAlignment) DependentSizedExtVectorType( 4116 *this, vecType, CanonExtTy, SizeExpr, AttrLoc); 4117 } 4118 } 4119 4120 Types.push_back(New); 4121 return QualType(New, 0); 4122 } 4123 4124 QualType ASTContext::getConstantMatrixType(QualType ElementTy, unsigned NumRows, 4125 unsigned NumColumns) const { 4126 llvm::FoldingSetNodeID ID; 4127 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns, 4128 Type::ConstantMatrix); 4129 4130 assert(MatrixType::isValidElementType(ElementTy) && 4131 "need a valid element type"); 4132 assert(ConstantMatrixType::isDimensionValid(NumRows) && 4133 ConstantMatrixType::isDimensionValid(NumColumns) && 4134 "need valid matrix dimensions"); 4135 void *InsertPos = nullptr; 4136 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos)) 4137 return QualType(MTP, 0); 4138 4139 QualType Canonical; 4140 if (!ElementTy.isCanonical()) { 4141 Canonical = 4142 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns); 4143 4144 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos); 4145 assert(!NewIP && "Matrix type shouldn't already exist in the map"); 4146 (void)NewIP; 4147 } 4148 4149 auto *New = new (*this, TypeAlignment) 4150 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical); 4151 MatrixTypes.InsertNode(New, InsertPos); 4152 Types.push_back(New); 4153 return QualType(New, 0); 4154 } 4155 4156 QualType ASTContext::getDependentSizedMatrixType(QualType ElementTy, 4157 Expr *RowExpr, 4158 Expr *ColumnExpr, 4159 SourceLocation AttrLoc) const { 4160 QualType CanonElementTy = getCanonicalType(ElementTy); 4161 llvm::FoldingSetNodeID ID; 4162 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr, 4163 ColumnExpr); 4164 4165 void *InsertPos = nullptr; 4166 DependentSizedMatrixType *Canon = 4167 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos); 4168 4169 if (!Canon) { 4170 Canon = new (*this, TypeAlignment) DependentSizedMatrixType( 4171 *this, CanonElementTy, QualType(), RowExpr, ColumnExpr, AttrLoc); 4172 #ifndef NDEBUG 4173 DependentSizedMatrixType *CanonCheck = 4174 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos); 4175 assert(!CanonCheck && "Dependent-sized matrix canonical type broken"); 4176 #endif 4177 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos); 4178 Types.push_back(Canon); 4179 } 4180 4181 // Already have a canonical version of the matrix type 4182 // 4183 // If it exactly matches the requested type, use it directly. 4184 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr && 4185 Canon->getRowExpr() == ColumnExpr) 4186 return QualType(Canon, 0); 4187 4188 // Use Canon as the canonical type for newly-built type. 4189 DependentSizedMatrixType *New = new (*this, TypeAlignment) 4190 DependentSizedMatrixType(*this, ElementTy, QualType(Canon, 0), RowExpr, 4191 ColumnExpr, AttrLoc); 4192 Types.push_back(New); 4193 return QualType(New, 0); 4194 } 4195 4196 QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType, 4197 Expr *AddrSpaceExpr, 4198 SourceLocation AttrLoc) const { 4199 assert(AddrSpaceExpr->isInstantiationDependent()); 4200 4201 QualType canonPointeeType = getCanonicalType(PointeeType); 4202 4203 void *insertPos = nullptr; 4204 llvm::FoldingSetNodeID ID; 4205 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType, 4206 AddrSpaceExpr); 4207 4208 DependentAddressSpaceType *canonTy = 4209 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos); 4210 4211 if (!canonTy) { 4212 canonTy = new (*this, TypeAlignment) 4213 DependentAddressSpaceType(*this, canonPointeeType, 4214 QualType(), AddrSpaceExpr, AttrLoc); 4215 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos); 4216 Types.push_back(canonTy); 4217 } 4218 4219 if (canonPointeeType == PointeeType && 4220 canonTy->getAddrSpaceExpr() == AddrSpaceExpr) 4221 return QualType(canonTy, 0); 4222 4223 auto *sugaredType 4224 = new (*this, TypeAlignment) 4225 DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0), 4226 AddrSpaceExpr, AttrLoc); 4227 Types.push_back(sugaredType); 4228 return QualType(sugaredType, 0); 4229 } 4230 4231 /// Determine whether \p T is canonical as the result type of a function. 4232 static bool isCanonicalResultType(QualType T) { 4233 return T.isCanonical() && 4234 (T.getObjCLifetime() == Qualifiers::OCL_None || 4235 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone); 4236 } 4237 4238 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'. 4239 QualType 4240 ASTContext::getFunctionNoProtoType(QualType ResultTy, 4241 const FunctionType::ExtInfo &Info) const { 4242 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter 4243 // functionality creates a function without a prototype regardless of 4244 // language mode (so it makes them even in C++). Once the rewriter has been 4245 // fixed, this assertion can be enabled again. 4246 //assert(!LangOpts.requiresStrictPrototypes() && 4247 // "strict prototypes are disabled"); 4248 4249 // Unique functions, to guarantee there is only one function of a particular 4250 // structure. 4251 llvm::FoldingSetNodeID ID; 4252 FunctionNoProtoType::Profile(ID, ResultTy, Info); 4253 4254 void *InsertPos = nullptr; 4255 if (FunctionNoProtoType *FT = 4256 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 4257 return QualType(FT, 0); 4258 4259 QualType Canonical; 4260 if (!isCanonicalResultType(ResultTy)) { 4261 Canonical = 4262 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info); 4263 4264 // Get the new insert position for the node we care about. 4265 FunctionNoProtoType *NewIP = 4266 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 4267 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4268 } 4269 4270 auto *New = new (*this, TypeAlignment) 4271 FunctionNoProtoType(ResultTy, Canonical, Info); 4272 Types.push_back(New); 4273 FunctionNoProtoTypes.InsertNode(New, InsertPos); 4274 return QualType(New, 0); 4275 } 4276 4277 CanQualType 4278 ASTContext::getCanonicalFunctionResultType(QualType ResultType) const { 4279 CanQualType CanResultType = getCanonicalType(ResultType); 4280 4281 // Canonical result types do not have ARC lifetime qualifiers. 4282 if (CanResultType.getQualifiers().hasObjCLifetime()) { 4283 Qualifiers Qs = CanResultType.getQualifiers(); 4284 Qs.removeObjCLifetime(); 4285 return CanQualType::CreateUnsafe( 4286 getQualifiedType(CanResultType.getUnqualifiedType(), Qs)); 4287 } 4288 4289 return CanResultType; 4290 } 4291 4292 static bool isCanonicalExceptionSpecification( 4293 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) { 4294 if (ESI.Type == EST_None) 4295 return true; 4296 if (!NoexceptInType) 4297 return false; 4298 4299 // C++17 onwards: exception specification is part of the type, as a simple 4300 // boolean "can this function type throw". 4301 if (ESI.Type == EST_BasicNoexcept) 4302 return true; 4303 4304 // A noexcept(expr) specification is (possibly) canonical if expr is 4305 // value-dependent. 4306 if (ESI.Type == EST_DependentNoexcept) 4307 return true; 4308 4309 // A dynamic exception specification is canonical if it only contains pack 4310 // expansions (so we can't tell whether it's non-throwing) and all its 4311 // contained types are canonical. 4312 if (ESI.Type == EST_Dynamic) { 4313 bool AnyPackExpansions = false; 4314 for (QualType ET : ESI.Exceptions) { 4315 if (!ET.isCanonical()) 4316 return false; 4317 if (ET->getAs<PackExpansionType>()) 4318 AnyPackExpansions = true; 4319 } 4320 return AnyPackExpansions; 4321 } 4322 4323 return false; 4324 } 4325 4326 QualType ASTContext::getFunctionTypeInternal( 4327 QualType ResultTy, ArrayRef<QualType> ArgArray, 4328 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const { 4329 size_t NumArgs = ArgArray.size(); 4330 4331 // Unique functions, to guarantee there is only one function of a particular 4332 // structure. 4333 llvm::FoldingSetNodeID ID; 4334 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI, 4335 *this, true); 4336 4337 QualType Canonical; 4338 bool Unique = false; 4339 4340 void *InsertPos = nullptr; 4341 if (FunctionProtoType *FPT = 4342 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) { 4343 QualType Existing = QualType(FPT, 0); 4344 4345 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse 4346 // it so long as our exception specification doesn't contain a dependent 4347 // noexcept expression, or we're just looking for a canonical type. 4348 // Otherwise, we're going to need to create a type 4349 // sugar node to hold the concrete expression. 4350 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) || 4351 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr()) 4352 return Existing; 4353 4354 // We need a new type sugar node for this one, to hold the new noexcept 4355 // expression. We do no canonicalization here, but that's OK since we don't 4356 // expect to see the same noexcept expression much more than once. 4357 Canonical = getCanonicalType(Existing); 4358 Unique = true; 4359 } 4360 4361 bool NoexceptInType = getLangOpts().CPlusPlus17; 4362 bool IsCanonicalExceptionSpec = 4363 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType); 4364 4365 // Determine whether the type being created is already canonical or not. 4366 bool isCanonical = !Unique && IsCanonicalExceptionSpec && 4367 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn; 4368 for (unsigned i = 0; i != NumArgs && isCanonical; ++i) 4369 if (!ArgArray[i].isCanonicalAsParam()) 4370 isCanonical = false; 4371 4372 if (OnlyWantCanonical) 4373 assert(isCanonical && 4374 "given non-canonical parameters constructing canonical type"); 4375 4376 // If this type isn't canonical, get the canonical version of it if we don't 4377 // already have it. The exception spec is only partially part of the 4378 // canonical type, and only in C++17 onwards. 4379 if (!isCanonical && Canonical.isNull()) { 4380 SmallVector<QualType, 16> CanonicalArgs; 4381 CanonicalArgs.reserve(NumArgs); 4382 for (unsigned i = 0; i != NumArgs; ++i) 4383 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i])); 4384 4385 llvm::SmallVector<QualType, 8> ExceptionTypeStorage; 4386 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI; 4387 CanonicalEPI.HasTrailingReturn = false; 4388 4389 if (IsCanonicalExceptionSpec) { 4390 // Exception spec is already OK. 4391 } else if (NoexceptInType) { 4392 switch (EPI.ExceptionSpec.Type) { 4393 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated: 4394 // We don't know yet. It shouldn't matter what we pick here; no-one 4395 // should ever look at this. 4396 LLVM_FALLTHROUGH; 4397 case EST_None: case EST_MSAny: case EST_NoexceptFalse: 4398 CanonicalEPI.ExceptionSpec.Type = EST_None; 4399 break; 4400 4401 // A dynamic exception specification is almost always "not noexcept", 4402 // with the exception that a pack expansion might expand to no types. 4403 case EST_Dynamic: { 4404 bool AnyPacks = false; 4405 for (QualType ET : EPI.ExceptionSpec.Exceptions) { 4406 if (ET->getAs<PackExpansionType>()) 4407 AnyPacks = true; 4408 ExceptionTypeStorage.push_back(getCanonicalType(ET)); 4409 } 4410 if (!AnyPacks) 4411 CanonicalEPI.ExceptionSpec.Type = EST_None; 4412 else { 4413 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic; 4414 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage; 4415 } 4416 break; 4417 } 4418 4419 case EST_DynamicNone: 4420 case EST_BasicNoexcept: 4421 case EST_NoexceptTrue: 4422 case EST_NoThrow: 4423 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept; 4424 break; 4425 4426 case EST_DependentNoexcept: 4427 llvm_unreachable("dependent noexcept is already canonical"); 4428 } 4429 } else { 4430 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo(); 4431 } 4432 4433 // Adjust the canonical function result type. 4434 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy); 4435 Canonical = 4436 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true); 4437 4438 // Get the new insert position for the node we care about. 4439 FunctionProtoType *NewIP = 4440 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 4441 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4442 } 4443 4444 // Compute the needed size to hold this FunctionProtoType and the 4445 // various trailing objects. 4446 auto ESH = FunctionProtoType::getExceptionSpecSize( 4447 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size()); 4448 size_t Size = FunctionProtoType::totalSizeToAlloc< 4449 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields, 4450 FunctionType::ExceptionType, Expr *, FunctionDecl *, 4451 FunctionProtoType::ExtParameterInfo, Qualifiers>( 4452 NumArgs, EPI.Variadic, 4453 FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type), 4454 ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr, 4455 EPI.ExtParameterInfos ? NumArgs : 0, 4456 EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0); 4457 4458 auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment); 4459 FunctionProtoType::ExtProtoInfo newEPI = EPI; 4460 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI); 4461 Types.push_back(FTP); 4462 if (!Unique) 4463 FunctionProtoTypes.InsertNode(FTP, InsertPos); 4464 return QualType(FTP, 0); 4465 } 4466 4467 QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const { 4468 llvm::FoldingSetNodeID ID; 4469 PipeType::Profile(ID, T, ReadOnly); 4470 4471 void *InsertPos = nullptr; 4472 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos)) 4473 return QualType(PT, 0); 4474 4475 // If the pipe element type isn't canonical, this won't be a canonical type 4476 // either, so fill in the canonical type field. 4477 QualType Canonical; 4478 if (!T.isCanonical()) { 4479 Canonical = getPipeType(getCanonicalType(T), ReadOnly); 4480 4481 // Get the new insert position for the node we care about. 4482 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos); 4483 assert(!NewIP && "Shouldn't be in the map!"); 4484 (void)NewIP; 4485 } 4486 auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly); 4487 Types.push_back(New); 4488 PipeTypes.InsertNode(New, InsertPos); 4489 return QualType(New, 0); 4490 } 4491 4492 QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const { 4493 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 4494 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant) 4495 : Ty; 4496 } 4497 4498 QualType ASTContext::getReadPipeType(QualType T) const { 4499 return getPipeType(T, true); 4500 } 4501 4502 QualType ASTContext::getWritePipeType(QualType T) const { 4503 return getPipeType(T, false); 4504 } 4505 4506 QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const { 4507 llvm::FoldingSetNodeID ID; 4508 BitIntType::Profile(ID, IsUnsigned, NumBits); 4509 4510 void *InsertPos = nullptr; 4511 if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos)) 4512 return QualType(EIT, 0); 4513 4514 auto *New = new (*this, TypeAlignment) BitIntType(IsUnsigned, NumBits); 4515 BitIntTypes.InsertNode(New, InsertPos); 4516 Types.push_back(New); 4517 return QualType(New, 0); 4518 } 4519 4520 QualType ASTContext::getDependentBitIntType(bool IsUnsigned, 4521 Expr *NumBitsExpr) const { 4522 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent"); 4523 llvm::FoldingSetNodeID ID; 4524 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr); 4525 4526 void *InsertPos = nullptr; 4527 if (DependentBitIntType *Existing = 4528 DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos)) 4529 return QualType(Existing, 0); 4530 4531 auto *New = new (*this, TypeAlignment) 4532 DependentBitIntType(*this, IsUnsigned, NumBitsExpr); 4533 DependentBitIntTypes.InsertNode(New, InsertPos); 4534 4535 Types.push_back(New); 4536 return QualType(New, 0); 4537 } 4538 4539 #ifndef NDEBUG 4540 static bool NeedsInjectedClassNameType(const RecordDecl *D) { 4541 if (!isa<CXXRecordDecl>(D)) return false; 4542 const auto *RD = cast<CXXRecordDecl>(D); 4543 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) 4544 return true; 4545 if (RD->getDescribedClassTemplate() && 4546 !isa<ClassTemplateSpecializationDecl>(RD)) 4547 return true; 4548 return false; 4549 } 4550 #endif 4551 4552 /// getInjectedClassNameType - Return the unique reference to the 4553 /// injected class name type for the specified templated declaration. 4554 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl, 4555 QualType TST) const { 4556 assert(NeedsInjectedClassNameType(Decl)); 4557 if (Decl->TypeForDecl) { 4558 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 4559 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) { 4560 assert(PrevDecl->TypeForDecl && "previous declaration has no type"); 4561 Decl->TypeForDecl = PrevDecl->TypeForDecl; 4562 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 4563 } else { 4564 Type *newType = 4565 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST); 4566 Decl->TypeForDecl = newType; 4567 Types.push_back(newType); 4568 } 4569 return QualType(Decl->TypeForDecl, 0); 4570 } 4571 4572 /// getTypeDeclType - Return the unique reference to the type for the 4573 /// specified type declaration. 4574 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const { 4575 assert(Decl && "Passed null for Decl param"); 4576 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case"); 4577 4578 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl)) 4579 return getTypedefType(Typedef); 4580 4581 assert(!isa<TemplateTypeParmDecl>(Decl) && 4582 "Template type parameter types are always available."); 4583 4584 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) { 4585 assert(Record->isFirstDecl() && "struct/union has previous declaration"); 4586 assert(!NeedsInjectedClassNameType(Record)); 4587 return getRecordType(Record); 4588 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) { 4589 assert(Enum->isFirstDecl() && "enum has previous declaration"); 4590 return getEnumType(Enum); 4591 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) { 4592 return getUnresolvedUsingType(Using); 4593 } else 4594 llvm_unreachable("TypeDecl without a type?"); 4595 4596 return QualType(Decl->TypeForDecl, 0); 4597 } 4598 4599 /// getTypedefType - Return the unique reference to the type for the 4600 /// specified typedef name decl. 4601 QualType ASTContext::getTypedefType(const TypedefNameDecl *Decl, 4602 QualType Underlying) const { 4603 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 4604 4605 if (Underlying.isNull()) 4606 Underlying = Decl->getUnderlyingType(); 4607 QualType Canonical = getCanonicalType(Underlying); 4608 auto *newType = new (*this, TypeAlignment) 4609 TypedefType(Type::Typedef, Decl, Underlying, Canonical); 4610 Decl->TypeForDecl = newType; 4611 Types.push_back(newType); 4612 return QualType(newType, 0); 4613 } 4614 4615 QualType ASTContext::getUsingType(const UsingShadowDecl *Found, 4616 QualType Underlying) const { 4617 llvm::FoldingSetNodeID ID; 4618 UsingType::Profile(ID, Found); 4619 4620 void *InsertPos = nullptr; 4621 UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos); 4622 if (T) 4623 return QualType(T, 0); 4624 4625 assert(!Underlying.hasLocalQualifiers()); 4626 assert(Underlying == getTypeDeclType(cast<TypeDecl>(Found->getTargetDecl()))); 4627 QualType Canon = Underlying.getCanonicalType(); 4628 4629 UsingType *NewType = 4630 new (*this, TypeAlignment) UsingType(Found, Underlying, Canon); 4631 Types.push_back(NewType); 4632 UsingTypes.InsertNode(NewType, InsertPos); 4633 return QualType(NewType, 0); 4634 } 4635 4636 QualType ASTContext::getRecordType(const RecordDecl *Decl) const { 4637 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 4638 4639 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl()) 4640 if (PrevDecl->TypeForDecl) 4641 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 4642 4643 auto *newType = new (*this, TypeAlignment) RecordType(Decl); 4644 Decl->TypeForDecl = newType; 4645 Types.push_back(newType); 4646 return QualType(newType, 0); 4647 } 4648 4649 QualType ASTContext::getEnumType(const EnumDecl *Decl) const { 4650 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 4651 4652 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl()) 4653 if (PrevDecl->TypeForDecl) 4654 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 4655 4656 auto *newType = new (*this, TypeAlignment) EnumType(Decl); 4657 Decl->TypeForDecl = newType; 4658 Types.push_back(newType); 4659 return QualType(newType, 0); 4660 } 4661 4662 QualType ASTContext::getUnresolvedUsingType( 4663 const UnresolvedUsingTypenameDecl *Decl) const { 4664 if (Decl->TypeForDecl) 4665 return QualType(Decl->TypeForDecl, 0); 4666 4667 if (const UnresolvedUsingTypenameDecl *CanonicalDecl = 4668 Decl->getCanonicalDecl()) 4669 if (CanonicalDecl->TypeForDecl) 4670 return QualType(Decl->TypeForDecl = CanonicalDecl->TypeForDecl, 0); 4671 4672 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Decl); 4673 Decl->TypeForDecl = newType; 4674 Types.push_back(newType); 4675 return QualType(newType, 0); 4676 } 4677 4678 QualType ASTContext::getAttributedType(attr::Kind attrKind, 4679 QualType modifiedType, 4680 QualType equivalentType) { 4681 llvm::FoldingSetNodeID id; 4682 AttributedType::Profile(id, attrKind, modifiedType, equivalentType); 4683 4684 void *insertPos = nullptr; 4685 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos); 4686 if (type) return QualType(type, 0); 4687 4688 QualType canon = getCanonicalType(equivalentType); 4689 type = new (*this, TypeAlignment) 4690 AttributedType(canon, attrKind, modifiedType, equivalentType); 4691 4692 Types.push_back(type); 4693 AttributedTypes.InsertNode(type, insertPos); 4694 4695 return QualType(type, 0); 4696 } 4697 4698 QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr, 4699 QualType Wrapped) { 4700 llvm::FoldingSetNodeID ID; 4701 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr); 4702 4703 void *InsertPos = nullptr; 4704 BTFTagAttributedType *Ty = 4705 BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos); 4706 if (Ty) 4707 return QualType(Ty, 0); 4708 4709 QualType Canon = getCanonicalType(Wrapped); 4710 Ty = new (*this, TypeAlignment) BTFTagAttributedType(Canon, Wrapped, BTFAttr); 4711 4712 Types.push_back(Ty); 4713 BTFTagAttributedTypes.InsertNode(Ty, InsertPos); 4714 4715 return QualType(Ty, 0); 4716 } 4717 4718 /// Retrieve a substitution-result type. 4719 QualType 4720 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm, 4721 QualType Replacement) const { 4722 assert(Replacement.isCanonical() 4723 && "replacement types must always be canonical"); 4724 4725 llvm::FoldingSetNodeID ID; 4726 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement); 4727 void *InsertPos = nullptr; 4728 SubstTemplateTypeParmType *SubstParm 4729 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 4730 4731 if (!SubstParm) { 4732 SubstParm = new (*this, TypeAlignment) 4733 SubstTemplateTypeParmType(Parm, Replacement); 4734 Types.push_back(SubstParm); 4735 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos); 4736 } 4737 4738 return QualType(SubstParm, 0); 4739 } 4740 4741 /// Retrieve a 4742 QualType ASTContext::getSubstTemplateTypeParmPackType( 4743 const TemplateTypeParmType *Parm, 4744 const TemplateArgument &ArgPack) { 4745 #ifndef NDEBUG 4746 for (const auto &P : ArgPack.pack_elements()) { 4747 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type"); 4748 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type"); 4749 } 4750 #endif 4751 4752 llvm::FoldingSetNodeID ID; 4753 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack); 4754 void *InsertPos = nullptr; 4755 if (SubstTemplateTypeParmPackType *SubstParm 4756 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos)) 4757 return QualType(SubstParm, 0); 4758 4759 QualType Canon; 4760 if (!Parm->isCanonicalUnqualified()) { 4761 Canon = getCanonicalType(QualType(Parm, 0)); 4762 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon), 4763 ArgPack); 4764 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos); 4765 } 4766 4767 auto *SubstParm 4768 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon, 4769 ArgPack); 4770 Types.push_back(SubstParm); 4771 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos); 4772 return QualType(SubstParm, 0); 4773 } 4774 4775 /// Retrieve the template type parameter type for a template 4776 /// parameter or parameter pack with the given depth, index, and (optionally) 4777 /// name. 4778 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index, 4779 bool ParameterPack, 4780 TemplateTypeParmDecl *TTPDecl) const { 4781 llvm::FoldingSetNodeID ID; 4782 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl); 4783 void *InsertPos = nullptr; 4784 TemplateTypeParmType *TypeParm 4785 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 4786 4787 if (TypeParm) 4788 return QualType(TypeParm, 0); 4789 4790 if (TTPDecl) { 4791 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack); 4792 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon); 4793 4794 TemplateTypeParmType *TypeCheck 4795 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 4796 assert(!TypeCheck && "Template type parameter canonical type broken"); 4797 (void)TypeCheck; 4798 } else 4799 TypeParm = new (*this, TypeAlignment) 4800 TemplateTypeParmType(Depth, Index, ParameterPack); 4801 4802 Types.push_back(TypeParm); 4803 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos); 4804 4805 return QualType(TypeParm, 0); 4806 } 4807 4808 TypeSourceInfo * 4809 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name, 4810 SourceLocation NameLoc, 4811 const TemplateArgumentListInfo &Args, 4812 QualType Underlying) const { 4813 assert(!Name.getAsDependentTemplateName() && 4814 "No dependent template names here!"); 4815 QualType TST = getTemplateSpecializationType(Name, Args, Underlying); 4816 4817 TypeSourceInfo *DI = CreateTypeSourceInfo(TST); 4818 TemplateSpecializationTypeLoc TL = 4819 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>(); 4820 TL.setTemplateKeywordLoc(SourceLocation()); 4821 TL.setTemplateNameLoc(NameLoc); 4822 TL.setLAngleLoc(Args.getLAngleLoc()); 4823 TL.setRAngleLoc(Args.getRAngleLoc()); 4824 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 4825 TL.setArgLocInfo(i, Args[i].getLocInfo()); 4826 return DI; 4827 } 4828 4829 QualType 4830 ASTContext::getTemplateSpecializationType(TemplateName Template, 4831 const TemplateArgumentListInfo &Args, 4832 QualType Underlying) const { 4833 assert(!Template.getAsDependentTemplateName() && 4834 "No dependent template names here!"); 4835 4836 SmallVector<TemplateArgument, 4> ArgVec; 4837 ArgVec.reserve(Args.size()); 4838 for (const TemplateArgumentLoc &Arg : Args.arguments()) 4839 ArgVec.push_back(Arg.getArgument()); 4840 4841 return getTemplateSpecializationType(Template, ArgVec, Underlying); 4842 } 4843 4844 #ifndef NDEBUG 4845 static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) { 4846 for (const TemplateArgument &Arg : Args) 4847 if (Arg.isPackExpansion()) 4848 return true; 4849 4850 return true; 4851 } 4852 #endif 4853 4854 QualType 4855 ASTContext::getTemplateSpecializationType(TemplateName Template, 4856 ArrayRef<TemplateArgument> Args, 4857 QualType Underlying) const { 4858 assert(!Template.getAsDependentTemplateName() && 4859 "No dependent template names here!"); 4860 // Look through qualified template names. 4861 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 4862 Template = QTN->getUnderlyingTemplate(); 4863 4864 bool IsTypeAlias = 4865 isa_and_nonnull<TypeAliasTemplateDecl>(Template.getAsTemplateDecl()); 4866 QualType CanonType; 4867 if (!Underlying.isNull()) 4868 CanonType = getCanonicalType(Underlying); 4869 else { 4870 // We can get here with an alias template when the specialization contains 4871 // a pack expansion that does not match up with a parameter pack. 4872 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) && 4873 "Caller must compute aliased type"); 4874 IsTypeAlias = false; 4875 CanonType = getCanonicalTemplateSpecializationType(Template, Args); 4876 } 4877 4878 // Allocate the (non-canonical) template specialization type, but don't 4879 // try to unique it: these types typically have location information that 4880 // we don't unique and don't want to lose. 4881 void *Mem = Allocate(sizeof(TemplateSpecializationType) + 4882 sizeof(TemplateArgument) * Args.size() + 4883 (IsTypeAlias? sizeof(QualType) : 0), 4884 TypeAlignment); 4885 auto *Spec 4886 = new (Mem) TemplateSpecializationType(Template, Args, CanonType, 4887 IsTypeAlias ? Underlying : QualType()); 4888 4889 Types.push_back(Spec); 4890 return QualType(Spec, 0); 4891 } 4892 4893 static bool 4894 getCanonicalTemplateArguments(const ASTContext &C, 4895 ArrayRef<TemplateArgument> OrigArgs, 4896 SmallVectorImpl<TemplateArgument> &CanonArgs) { 4897 bool AnyNonCanonArgs = false; 4898 unsigned NumArgs = OrigArgs.size(); 4899 CanonArgs.resize(NumArgs); 4900 for (unsigned I = 0; I != NumArgs; ++I) { 4901 const TemplateArgument &OrigArg = OrigArgs[I]; 4902 TemplateArgument &CanonArg = CanonArgs[I]; 4903 CanonArg = C.getCanonicalTemplateArgument(OrigArg); 4904 if (!CanonArg.structurallyEquals(OrigArg)) 4905 AnyNonCanonArgs = true; 4906 } 4907 return AnyNonCanonArgs; 4908 } 4909 4910 QualType ASTContext::getCanonicalTemplateSpecializationType( 4911 TemplateName Template, ArrayRef<TemplateArgument> Args) const { 4912 assert(!Template.getAsDependentTemplateName() && 4913 "No dependent template names here!"); 4914 4915 // Look through qualified template names. 4916 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 4917 Template = TemplateName(QTN->getUnderlyingTemplate()); 4918 4919 // Build the canonical template specialization type. 4920 TemplateName CanonTemplate = getCanonicalTemplateName(Template); 4921 SmallVector<TemplateArgument, 4> CanonArgs; 4922 ::getCanonicalTemplateArguments(*this, Args, CanonArgs); 4923 4924 // Determine whether this canonical template specialization type already 4925 // exists. 4926 llvm::FoldingSetNodeID ID; 4927 TemplateSpecializationType::Profile(ID, CanonTemplate, 4928 CanonArgs, *this); 4929 4930 void *InsertPos = nullptr; 4931 TemplateSpecializationType *Spec 4932 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 4933 4934 if (!Spec) { 4935 // Allocate a new canonical template specialization type. 4936 void *Mem = Allocate((sizeof(TemplateSpecializationType) + 4937 sizeof(TemplateArgument) * CanonArgs.size()), 4938 TypeAlignment); 4939 Spec = new (Mem) TemplateSpecializationType(CanonTemplate, 4940 CanonArgs, 4941 QualType(), QualType()); 4942 Types.push_back(Spec); 4943 TemplateSpecializationTypes.InsertNode(Spec, InsertPos); 4944 } 4945 4946 assert(Spec->isDependentType() && 4947 "Non-dependent template-id type must have a canonical type"); 4948 return QualType(Spec, 0); 4949 } 4950 4951 QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword, 4952 NestedNameSpecifier *NNS, 4953 QualType NamedType, 4954 TagDecl *OwnedTagDecl) const { 4955 llvm::FoldingSetNodeID ID; 4956 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl); 4957 4958 void *InsertPos = nullptr; 4959 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 4960 if (T) 4961 return QualType(T, 0); 4962 4963 QualType Canon = NamedType; 4964 if (!Canon.isCanonical()) { 4965 Canon = getCanonicalType(NamedType); 4966 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 4967 assert(!CheckT && "Elaborated canonical type broken"); 4968 (void)CheckT; 4969 } 4970 4971 void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl), 4972 TypeAlignment); 4973 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl); 4974 4975 Types.push_back(T); 4976 ElaboratedTypes.InsertNode(T, InsertPos); 4977 return QualType(T, 0); 4978 } 4979 4980 QualType 4981 ASTContext::getParenType(QualType InnerType) const { 4982 llvm::FoldingSetNodeID ID; 4983 ParenType::Profile(ID, InnerType); 4984 4985 void *InsertPos = nullptr; 4986 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 4987 if (T) 4988 return QualType(T, 0); 4989 4990 QualType Canon = InnerType; 4991 if (!Canon.isCanonical()) { 4992 Canon = getCanonicalType(InnerType); 4993 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 4994 assert(!CheckT && "Paren canonical type broken"); 4995 (void)CheckT; 4996 } 4997 4998 T = new (*this, TypeAlignment) ParenType(InnerType, Canon); 4999 Types.push_back(T); 5000 ParenTypes.InsertNode(T, InsertPos); 5001 return QualType(T, 0); 5002 } 5003 5004 QualType 5005 ASTContext::getMacroQualifiedType(QualType UnderlyingTy, 5006 const IdentifierInfo *MacroII) const { 5007 QualType Canon = UnderlyingTy; 5008 if (!Canon.isCanonical()) 5009 Canon = getCanonicalType(UnderlyingTy); 5010 5011 auto *newType = new (*this, TypeAlignment) 5012 MacroQualifiedType(UnderlyingTy, Canon, MacroII); 5013 Types.push_back(newType); 5014 return QualType(newType, 0); 5015 } 5016 5017 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword, 5018 NestedNameSpecifier *NNS, 5019 const IdentifierInfo *Name, 5020 QualType Canon) const { 5021 if (Canon.isNull()) { 5022 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 5023 if (CanonNNS != NNS) 5024 Canon = getDependentNameType(Keyword, CanonNNS, Name); 5025 } 5026 5027 llvm::FoldingSetNodeID ID; 5028 DependentNameType::Profile(ID, Keyword, NNS, Name); 5029 5030 void *InsertPos = nullptr; 5031 DependentNameType *T 5032 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos); 5033 if (T) 5034 return QualType(T, 0); 5035 5036 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon); 5037 Types.push_back(T); 5038 DependentNameTypes.InsertNode(T, InsertPos); 5039 return QualType(T, 0); 5040 } 5041 5042 QualType 5043 ASTContext::getDependentTemplateSpecializationType( 5044 ElaboratedTypeKeyword Keyword, 5045 NestedNameSpecifier *NNS, 5046 const IdentifierInfo *Name, 5047 const TemplateArgumentListInfo &Args) const { 5048 // TODO: avoid this copy 5049 SmallVector<TemplateArgument, 16> ArgCopy; 5050 for (unsigned I = 0, E = Args.size(); I != E; ++I) 5051 ArgCopy.push_back(Args[I].getArgument()); 5052 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy); 5053 } 5054 5055 QualType 5056 ASTContext::getDependentTemplateSpecializationType( 5057 ElaboratedTypeKeyword Keyword, 5058 NestedNameSpecifier *NNS, 5059 const IdentifierInfo *Name, 5060 ArrayRef<TemplateArgument> Args) const { 5061 assert((!NNS || NNS->isDependent()) && 5062 "nested-name-specifier must be dependent"); 5063 5064 llvm::FoldingSetNodeID ID; 5065 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS, 5066 Name, Args); 5067 5068 void *InsertPos = nullptr; 5069 DependentTemplateSpecializationType *T 5070 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 5071 if (T) 5072 return QualType(T, 0); 5073 5074 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 5075 5076 ElaboratedTypeKeyword CanonKeyword = Keyword; 5077 if (Keyword == ETK_None) CanonKeyword = ETK_Typename; 5078 5079 SmallVector<TemplateArgument, 16> CanonArgs; 5080 bool AnyNonCanonArgs = 5081 ::getCanonicalTemplateArguments(*this, Args, CanonArgs); 5082 5083 QualType Canon; 5084 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) { 5085 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS, 5086 Name, 5087 CanonArgs); 5088 5089 // Find the insert position again. 5090 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 5091 } 5092 5093 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) + 5094 sizeof(TemplateArgument) * Args.size()), 5095 TypeAlignment); 5096 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS, 5097 Name, Args, Canon); 5098 Types.push_back(T); 5099 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos); 5100 return QualType(T, 0); 5101 } 5102 5103 TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) { 5104 TemplateArgument Arg; 5105 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) { 5106 QualType ArgType = getTypeDeclType(TTP); 5107 if (TTP->isParameterPack()) 5108 ArgType = getPackExpansionType(ArgType, None); 5109 5110 Arg = TemplateArgument(ArgType); 5111 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 5112 QualType T = 5113 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this); 5114 // For class NTTPs, ensure we include the 'const' so the type matches that 5115 // of a real template argument. 5116 // FIXME: It would be more faithful to model this as something like an 5117 // lvalue-to-rvalue conversion applied to a const-qualified lvalue. 5118 if (T->isRecordType()) 5119 T.addConst(); 5120 Expr *E = new (*this) DeclRefExpr( 5121 *this, NTTP, /*enclosing*/ false, T, 5122 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation()); 5123 5124 if (NTTP->isParameterPack()) 5125 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(), 5126 None); 5127 Arg = TemplateArgument(E); 5128 } else { 5129 auto *TTP = cast<TemplateTemplateParmDecl>(Param); 5130 if (TTP->isParameterPack()) 5131 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>()); 5132 else 5133 Arg = TemplateArgument(TemplateName(TTP)); 5134 } 5135 5136 if (Param->isTemplateParameterPack()) 5137 Arg = TemplateArgument::CreatePackCopy(*this, Arg); 5138 5139 return Arg; 5140 } 5141 5142 void 5143 ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params, 5144 SmallVectorImpl<TemplateArgument> &Args) { 5145 Args.reserve(Args.size() + Params->size()); 5146 5147 for (NamedDecl *Param : *Params) 5148 Args.push_back(getInjectedTemplateArg(Param)); 5149 } 5150 5151 QualType ASTContext::getPackExpansionType(QualType Pattern, 5152 Optional<unsigned> NumExpansions, 5153 bool ExpectPackInType) { 5154 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) && 5155 "Pack expansions must expand one or more parameter packs"); 5156 5157 llvm::FoldingSetNodeID ID; 5158 PackExpansionType::Profile(ID, Pattern, NumExpansions); 5159 5160 void *InsertPos = nullptr; 5161 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 5162 if (T) 5163 return QualType(T, 0); 5164 5165 QualType Canon; 5166 if (!Pattern.isCanonical()) { 5167 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions, 5168 /*ExpectPackInType=*/false); 5169 5170 // Find the insert position again, in case we inserted an element into 5171 // PackExpansionTypes and invalidated our insert position. 5172 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 5173 } 5174 5175 T = new (*this, TypeAlignment) 5176 PackExpansionType(Pattern, Canon, NumExpansions); 5177 Types.push_back(T); 5178 PackExpansionTypes.InsertNode(T, InsertPos); 5179 return QualType(T, 0); 5180 } 5181 5182 /// CmpProtocolNames - Comparison predicate for sorting protocols 5183 /// alphabetically. 5184 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS, 5185 ObjCProtocolDecl *const *RHS) { 5186 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName()); 5187 } 5188 5189 static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) { 5190 if (Protocols.empty()) return true; 5191 5192 if (Protocols[0]->getCanonicalDecl() != Protocols[0]) 5193 return false; 5194 5195 for (unsigned i = 1; i != Protocols.size(); ++i) 5196 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 || 5197 Protocols[i]->getCanonicalDecl() != Protocols[i]) 5198 return false; 5199 return true; 5200 } 5201 5202 static void 5203 SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) { 5204 // Sort protocols, keyed by name. 5205 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames); 5206 5207 // Canonicalize. 5208 for (ObjCProtocolDecl *&P : Protocols) 5209 P = P->getCanonicalDecl(); 5210 5211 // Remove duplicates. 5212 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end()); 5213 Protocols.erase(ProtocolsEnd, Protocols.end()); 5214 } 5215 5216 QualType ASTContext::getObjCObjectType(QualType BaseType, 5217 ObjCProtocolDecl * const *Protocols, 5218 unsigned NumProtocols) const { 5219 return getObjCObjectType(BaseType, {}, 5220 llvm::makeArrayRef(Protocols, NumProtocols), 5221 /*isKindOf=*/false); 5222 } 5223 5224 QualType ASTContext::getObjCObjectType( 5225 QualType baseType, 5226 ArrayRef<QualType> typeArgs, 5227 ArrayRef<ObjCProtocolDecl *> protocols, 5228 bool isKindOf) const { 5229 // If the base type is an interface and there aren't any protocols or 5230 // type arguments to add, then the interface type will do just fine. 5231 if (typeArgs.empty() && protocols.empty() && !isKindOf && 5232 isa<ObjCInterfaceType>(baseType)) 5233 return baseType; 5234 5235 // Look in the folding set for an existing type. 5236 llvm::FoldingSetNodeID ID; 5237 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf); 5238 void *InsertPos = nullptr; 5239 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos)) 5240 return QualType(QT, 0); 5241 5242 // Determine the type arguments to be used for canonicalization, 5243 // which may be explicitly specified here or written on the base 5244 // type. 5245 ArrayRef<QualType> effectiveTypeArgs = typeArgs; 5246 if (effectiveTypeArgs.empty()) { 5247 if (const auto *baseObject = baseType->getAs<ObjCObjectType>()) 5248 effectiveTypeArgs = baseObject->getTypeArgs(); 5249 } 5250 5251 // Build the canonical type, which has the canonical base type and a 5252 // sorted-and-uniqued list of protocols and the type arguments 5253 // canonicalized. 5254 QualType canonical; 5255 bool typeArgsAreCanonical = llvm::all_of( 5256 effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); }); 5257 bool protocolsSorted = areSortedAndUniqued(protocols); 5258 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) { 5259 // Determine the canonical type arguments. 5260 ArrayRef<QualType> canonTypeArgs; 5261 SmallVector<QualType, 4> canonTypeArgsVec; 5262 if (!typeArgsAreCanonical) { 5263 canonTypeArgsVec.reserve(effectiveTypeArgs.size()); 5264 for (auto typeArg : effectiveTypeArgs) 5265 canonTypeArgsVec.push_back(getCanonicalType(typeArg)); 5266 canonTypeArgs = canonTypeArgsVec; 5267 } else { 5268 canonTypeArgs = effectiveTypeArgs; 5269 } 5270 5271 ArrayRef<ObjCProtocolDecl *> canonProtocols; 5272 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec; 5273 if (!protocolsSorted) { 5274 canonProtocolsVec.append(protocols.begin(), protocols.end()); 5275 SortAndUniqueProtocols(canonProtocolsVec); 5276 canonProtocols = canonProtocolsVec; 5277 } else { 5278 canonProtocols = protocols; 5279 } 5280 5281 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs, 5282 canonProtocols, isKindOf); 5283 5284 // Regenerate InsertPos. 5285 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos); 5286 } 5287 5288 unsigned size = sizeof(ObjCObjectTypeImpl); 5289 size += typeArgs.size() * sizeof(QualType); 5290 size += protocols.size() * sizeof(ObjCProtocolDecl *); 5291 void *mem = Allocate(size, TypeAlignment); 5292 auto *T = 5293 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols, 5294 isKindOf); 5295 5296 Types.push_back(T); 5297 ObjCObjectTypes.InsertNode(T, InsertPos); 5298 return QualType(T, 0); 5299 } 5300 5301 /// Apply Objective-C protocol qualifiers to the given type. 5302 /// If this is for the canonical type of a type parameter, we can apply 5303 /// protocol qualifiers on the ObjCObjectPointerType. 5304 QualType 5305 ASTContext::applyObjCProtocolQualifiers(QualType type, 5306 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError, 5307 bool allowOnPointerType) const { 5308 hasError = false; 5309 5310 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) { 5311 return getObjCTypeParamType(objT->getDecl(), protocols); 5312 } 5313 5314 // Apply protocol qualifiers to ObjCObjectPointerType. 5315 if (allowOnPointerType) { 5316 if (const auto *objPtr = 5317 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) { 5318 const ObjCObjectType *objT = objPtr->getObjectType(); 5319 // Merge protocol lists and construct ObjCObjectType. 5320 SmallVector<ObjCProtocolDecl*, 8> protocolsVec; 5321 protocolsVec.append(objT->qual_begin(), 5322 objT->qual_end()); 5323 protocolsVec.append(protocols.begin(), protocols.end()); 5324 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec; 5325 type = getObjCObjectType( 5326 objT->getBaseType(), 5327 objT->getTypeArgsAsWritten(), 5328 protocols, 5329 objT->isKindOfTypeAsWritten()); 5330 return getObjCObjectPointerType(type); 5331 } 5332 } 5333 5334 // Apply protocol qualifiers to ObjCObjectType. 5335 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){ 5336 // FIXME: Check for protocols to which the class type is already 5337 // known to conform. 5338 5339 return getObjCObjectType(objT->getBaseType(), 5340 objT->getTypeArgsAsWritten(), 5341 protocols, 5342 objT->isKindOfTypeAsWritten()); 5343 } 5344 5345 // If the canonical type is ObjCObjectType, ... 5346 if (type->isObjCObjectType()) { 5347 // Silently overwrite any existing protocol qualifiers. 5348 // TODO: determine whether that's the right thing to do. 5349 5350 // FIXME: Check for protocols to which the class type is already 5351 // known to conform. 5352 return getObjCObjectType(type, {}, protocols, false); 5353 } 5354 5355 // id<protocol-list> 5356 if (type->isObjCIdType()) { 5357 const auto *objPtr = type->castAs<ObjCObjectPointerType>(); 5358 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols, 5359 objPtr->isKindOfType()); 5360 return getObjCObjectPointerType(type); 5361 } 5362 5363 // Class<protocol-list> 5364 if (type->isObjCClassType()) { 5365 const auto *objPtr = type->castAs<ObjCObjectPointerType>(); 5366 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols, 5367 objPtr->isKindOfType()); 5368 return getObjCObjectPointerType(type); 5369 } 5370 5371 hasError = true; 5372 return type; 5373 } 5374 5375 QualType 5376 ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl, 5377 ArrayRef<ObjCProtocolDecl *> protocols) const { 5378 // Look in the folding set for an existing type. 5379 llvm::FoldingSetNodeID ID; 5380 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols); 5381 void *InsertPos = nullptr; 5382 if (ObjCTypeParamType *TypeParam = 5383 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos)) 5384 return QualType(TypeParam, 0); 5385 5386 // We canonicalize to the underlying type. 5387 QualType Canonical = getCanonicalType(Decl->getUnderlyingType()); 5388 if (!protocols.empty()) { 5389 // Apply the protocol qualifers. 5390 bool hasError; 5391 Canonical = getCanonicalType(applyObjCProtocolQualifiers( 5392 Canonical, protocols, hasError, true /*allowOnPointerType*/)); 5393 assert(!hasError && "Error when apply protocol qualifier to bound type"); 5394 } 5395 5396 unsigned size = sizeof(ObjCTypeParamType); 5397 size += protocols.size() * sizeof(ObjCProtocolDecl *); 5398 void *mem = Allocate(size, TypeAlignment); 5399 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols); 5400 5401 Types.push_back(newType); 5402 ObjCTypeParamTypes.InsertNode(newType, InsertPos); 5403 return QualType(newType, 0); 5404 } 5405 5406 void ASTContext::adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig, 5407 ObjCTypeParamDecl *New) const { 5408 New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType())); 5409 // Update TypeForDecl after updating TypeSourceInfo. 5410 auto NewTypeParamTy = cast<ObjCTypeParamType>(New->getTypeForDecl()); 5411 SmallVector<ObjCProtocolDecl *, 8> protocols; 5412 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end()); 5413 QualType UpdatedTy = getObjCTypeParamType(New, protocols); 5414 New->setTypeForDecl(UpdatedTy.getTypePtr()); 5415 } 5416 5417 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's 5418 /// protocol list adopt all protocols in QT's qualified-id protocol 5419 /// list. 5420 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT, 5421 ObjCInterfaceDecl *IC) { 5422 if (!QT->isObjCQualifiedIdType()) 5423 return false; 5424 5425 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) { 5426 // If both the right and left sides have qualifiers. 5427 for (auto *Proto : OPT->quals()) { 5428 if (!IC->ClassImplementsProtocol(Proto, false)) 5429 return false; 5430 } 5431 return true; 5432 } 5433 return false; 5434 } 5435 5436 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in 5437 /// QT's qualified-id protocol list adopt all protocols in IDecl's list 5438 /// of protocols. 5439 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT, 5440 ObjCInterfaceDecl *IDecl) { 5441 if (!QT->isObjCQualifiedIdType()) 5442 return false; 5443 const auto *OPT = QT->getAs<ObjCObjectPointerType>(); 5444 if (!OPT) 5445 return false; 5446 if (!IDecl->hasDefinition()) 5447 return false; 5448 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols; 5449 CollectInheritedProtocols(IDecl, InheritedProtocols); 5450 if (InheritedProtocols.empty()) 5451 return false; 5452 // Check that if every protocol in list of id<plist> conforms to a protocol 5453 // of IDecl's, then bridge casting is ok. 5454 bool Conforms = false; 5455 for (auto *Proto : OPT->quals()) { 5456 Conforms = false; 5457 for (auto *PI : InheritedProtocols) { 5458 if (ProtocolCompatibleWithProtocol(Proto, PI)) { 5459 Conforms = true; 5460 break; 5461 } 5462 } 5463 if (!Conforms) 5464 break; 5465 } 5466 if (Conforms) 5467 return true; 5468 5469 for (auto *PI : InheritedProtocols) { 5470 // If both the right and left sides have qualifiers. 5471 bool Adopts = false; 5472 for (auto *Proto : OPT->quals()) { 5473 // return 'true' if 'PI' is in the inheritance hierarchy of Proto 5474 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto))) 5475 break; 5476 } 5477 if (!Adopts) 5478 return false; 5479 } 5480 return true; 5481 } 5482 5483 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for 5484 /// the given object type. 5485 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const { 5486 llvm::FoldingSetNodeID ID; 5487 ObjCObjectPointerType::Profile(ID, ObjectT); 5488 5489 void *InsertPos = nullptr; 5490 if (ObjCObjectPointerType *QT = 5491 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 5492 return QualType(QT, 0); 5493 5494 // Find the canonical object type. 5495 QualType Canonical; 5496 if (!ObjectT.isCanonical()) { 5497 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT)); 5498 5499 // Regenerate InsertPos. 5500 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 5501 } 5502 5503 // No match. 5504 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment); 5505 auto *QType = 5506 new (Mem) ObjCObjectPointerType(Canonical, ObjectT); 5507 5508 Types.push_back(QType); 5509 ObjCObjectPointerTypes.InsertNode(QType, InsertPos); 5510 return QualType(QType, 0); 5511 } 5512 5513 /// getObjCInterfaceType - Return the unique reference to the type for the 5514 /// specified ObjC interface decl. The list of protocols is optional. 5515 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl, 5516 ObjCInterfaceDecl *PrevDecl) const { 5517 if (Decl->TypeForDecl) 5518 return QualType(Decl->TypeForDecl, 0); 5519 5520 if (PrevDecl) { 5521 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl"); 5522 Decl->TypeForDecl = PrevDecl->TypeForDecl; 5523 return QualType(PrevDecl->TypeForDecl, 0); 5524 } 5525 5526 // Prefer the definition, if there is one. 5527 if (const ObjCInterfaceDecl *Def = Decl->getDefinition()) 5528 Decl = Def; 5529 5530 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment); 5531 auto *T = new (Mem) ObjCInterfaceType(Decl); 5532 Decl->TypeForDecl = T; 5533 Types.push_back(T); 5534 return QualType(T, 0); 5535 } 5536 5537 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique 5538 /// TypeOfExprType AST's (since expression's are never shared). For example, 5539 /// multiple declarations that refer to "typeof(x)" all contain different 5540 /// DeclRefExpr's. This doesn't effect the type checker, since it operates 5541 /// on canonical type's (which are always unique). 5542 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const { 5543 TypeOfExprType *toe; 5544 if (tofExpr->isTypeDependent()) { 5545 llvm::FoldingSetNodeID ID; 5546 DependentTypeOfExprType::Profile(ID, *this, tofExpr); 5547 5548 void *InsertPos = nullptr; 5549 DependentTypeOfExprType *Canon 5550 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos); 5551 if (Canon) { 5552 // We already have a "canonical" version of an identical, dependent 5553 // typeof(expr) type. Use that as our canonical type. 5554 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, 5555 QualType((TypeOfExprType*)Canon, 0)); 5556 } else { 5557 // Build a new, canonical typeof(expr) type. 5558 Canon 5559 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr); 5560 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos); 5561 toe = Canon; 5562 } 5563 } else { 5564 QualType Canonical = getCanonicalType(tofExpr->getType()); 5565 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical); 5566 } 5567 Types.push_back(toe); 5568 return QualType(toe, 0); 5569 } 5570 5571 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique 5572 /// TypeOfType nodes. The only motivation to unique these nodes would be 5573 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be 5574 /// an issue. This doesn't affect the type checker, since it operates 5575 /// on canonical types (which are always unique). 5576 QualType ASTContext::getTypeOfType(QualType tofType) const { 5577 QualType Canonical = getCanonicalType(tofType); 5578 auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical); 5579 Types.push_back(tot); 5580 return QualType(tot, 0); 5581 } 5582 5583 /// getReferenceQualifiedType - Given an expr, will return the type for 5584 /// that expression, as in [dcl.type.simple]p4 but without taking id-expressions 5585 /// and class member access into account. 5586 QualType ASTContext::getReferenceQualifiedType(const Expr *E) const { 5587 // C++11 [dcl.type.simple]p4: 5588 // [...] 5589 QualType T = E->getType(); 5590 switch (E->getValueKind()) { 5591 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the 5592 // type of e; 5593 case VK_XValue: 5594 return getRValueReferenceType(T); 5595 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the 5596 // type of e; 5597 case VK_LValue: 5598 return getLValueReferenceType(T); 5599 // - otherwise, decltype(e) is the type of e. 5600 case VK_PRValue: 5601 return T; 5602 } 5603 llvm_unreachable("Unknown value kind"); 5604 } 5605 5606 /// Unlike many "get<Type>" functions, we don't unique DecltypeType 5607 /// nodes. This would never be helpful, since each such type has its own 5608 /// expression, and would not give a significant memory saving, since there 5609 /// is an Expr tree under each such type. 5610 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const { 5611 DecltypeType *dt; 5612 5613 // C++11 [temp.type]p2: 5614 // If an expression e involves a template parameter, decltype(e) denotes a 5615 // unique dependent type. Two such decltype-specifiers refer to the same 5616 // type only if their expressions are equivalent (14.5.6.1). 5617 if (e->isInstantiationDependent()) { 5618 llvm::FoldingSetNodeID ID; 5619 DependentDecltypeType::Profile(ID, *this, e); 5620 5621 void *InsertPos = nullptr; 5622 DependentDecltypeType *Canon 5623 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos); 5624 if (!Canon) { 5625 // Build a new, canonical decltype(expr) type. 5626 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e); 5627 DependentDecltypeTypes.InsertNode(Canon, InsertPos); 5628 } 5629 dt = new (*this, TypeAlignment) 5630 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0)); 5631 } else { 5632 dt = new (*this, TypeAlignment) 5633 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType)); 5634 } 5635 Types.push_back(dt); 5636 return QualType(dt, 0); 5637 } 5638 5639 /// getUnaryTransformationType - We don't unique these, since the memory 5640 /// savings are minimal and these are rare. 5641 QualType ASTContext::getUnaryTransformType(QualType BaseType, 5642 QualType UnderlyingType, 5643 UnaryTransformType::UTTKind Kind) 5644 const { 5645 UnaryTransformType *ut = nullptr; 5646 5647 if (BaseType->isDependentType()) { 5648 // Look in the folding set for an existing type. 5649 llvm::FoldingSetNodeID ID; 5650 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind); 5651 5652 void *InsertPos = nullptr; 5653 DependentUnaryTransformType *Canon 5654 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos); 5655 5656 if (!Canon) { 5657 // Build a new, canonical __underlying_type(type) type. 5658 Canon = new (*this, TypeAlignment) 5659 DependentUnaryTransformType(*this, getCanonicalType(BaseType), 5660 Kind); 5661 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos); 5662 } 5663 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType, 5664 QualType(), Kind, 5665 QualType(Canon, 0)); 5666 } else { 5667 QualType CanonType = getCanonicalType(UnderlyingType); 5668 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType, 5669 UnderlyingType, Kind, 5670 CanonType); 5671 } 5672 Types.push_back(ut); 5673 return QualType(ut, 0); 5674 } 5675 5676 QualType ASTContext::getAutoTypeInternal( 5677 QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent, 5678 bool IsPack, ConceptDecl *TypeConstraintConcept, 5679 ArrayRef<TemplateArgument> TypeConstraintArgs, bool IsCanon) const { 5680 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && 5681 !TypeConstraintConcept && !IsDependent) 5682 return getAutoDeductType(); 5683 5684 // Look in the folding set for an existing type. 5685 void *InsertPos = nullptr; 5686 llvm::FoldingSetNodeID ID; 5687 AutoType::Profile(ID, *this, DeducedType, Keyword, IsDependent, 5688 TypeConstraintConcept, TypeConstraintArgs); 5689 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos)) 5690 return QualType(AT, 0); 5691 5692 QualType Canon; 5693 if (!IsCanon) { 5694 if (DeducedType.isNull()) { 5695 SmallVector<TemplateArgument, 4> CanonArgs; 5696 bool AnyNonCanonArgs = 5697 ::getCanonicalTemplateArguments(*this, TypeConstraintArgs, CanonArgs); 5698 if (AnyNonCanonArgs) { 5699 Canon = getAutoTypeInternal(QualType(), Keyword, IsDependent, IsPack, 5700 TypeConstraintConcept, CanonArgs, true); 5701 // Find the insert position again. 5702 AutoTypes.FindNodeOrInsertPos(ID, InsertPos); 5703 } 5704 } else { 5705 Canon = DeducedType.getCanonicalType(); 5706 } 5707 } 5708 5709 void *Mem = Allocate(sizeof(AutoType) + 5710 sizeof(TemplateArgument) * TypeConstraintArgs.size(), 5711 TypeAlignment); 5712 auto *AT = new (Mem) AutoType( 5713 DeducedType, Keyword, 5714 (IsDependent ? TypeDependence::DependentInstantiation 5715 : TypeDependence::None) | 5716 (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None), 5717 Canon, TypeConstraintConcept, TypeConstraintArgs); 5718 Types.push_back(AT); 5719 AutoTypes.InsertNode(AT, InsertPos); 5720 return QualType(AT, 0); 5721 } 5722 5723 /// getAutoType - Return the uniqued reference to the 'auto' type which has been 5724 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the 5725 /// canonical deduced-but-dependent 'auto' type. 5726 QualType 5727 ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, 5728 bool IsDependent, bool IsPack, 5729 ConceptDecl *TypeConstraintConcept, 5730 ArrayRef<TemplateArgument> TypeConstraintArgs) const { 5731 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack"); 5732 assert((!IsDependent || DeducedType.isNull()) && 5733 "A dependent auto should be undeduced"); 5734 return getAutoTypeInternal(DeducedType, Keyword, IsDependent, IsPack, 5735 TypeConstraintConcept, TypeConstraintArgs); 5736 } 5737 5738 /// Return the uniqued reference to the deduced template specialization type 5739 /// which has been deduced to the given type, or to the canonical undeduced 5740 /// such type, or the canonical deduced-but-dependent such type. 5741 QualType ASTContext::getDeducedTemplateSpecializationType( 5742 TemplateName Template, QualType DeducedType, bool IsDependent) const { 5743 // Look in the folding set for an existing type. 5744 void *InsertPos = nullptr; 5745 llvm::FoldingSetNodeID ID; 5746 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType, 5747 IsDependent); 5748 if (DeducedTemplateSpecializationType *DTST = 5749 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos)) 5750 return QualType(DTST, 0); 5751 5752 auto *DTST = new (*this, TypeAlignment) 5753 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent); 5754 llvm::FoldingSetNodeID TempID; 5755 DTST->Profile(TempID); 5756 assert(ID == TempID && "ID does not match"); 5757 Types.push_back(DTST); 5758 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos); 5759 return QualType(DTST, 0); 5760 } 5761 5762 /// getAtomicType - Return the uniqued reference to the atomic type for 5763 /// the given value type. 5764 QualType ASTContext::getAtomicType(QualType T) const { 5765 // Unique pointers, to guarantee there is only one pointer of a particular 5766 // structure. 5767 llvm::FoldingSetNodeID ID; 5768 AtomicType::Profile(ID, T); 5769 5770 void *InsertPos = nullptr; 5771 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos)) 5772 return QualType(AT, 0); 5773 5774 // If the atomic value type isn't canonical, this won't be a canonical type 5775 // either, so fill in the canonical type field. 5776 QualType Canonical; 5777 if (!T.isCanonical()) { 5778 Canonical = getAtomicType(getCanonicalType(T)); 5779 5780 // Get the new insert position for the node we care about. 5781 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos); 5782 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 5783 } 5784 auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical); 5785 Types.push_back(New); 5786 AtomicTypes.InsertNode(New, InsertPos); 5787 return QualType(New, 0); 5788 } 5789 5790 /// getAutoDeductType - Get type pattern for deducing against 'auto'. 5791 QualType ASTContext::getAutoDeductType() const { 5792 if (AutoDeductTy.isNull()) 5793 AutoDeductTy = QualType(new (*this, TypeAlignment) 5794 AutoType(QualType(), AutoTypeKeyword::Auto, 5795 TypeDependence::None, QualType(), 5796 /*concept*/ nullptr, /*args*/ {}), 5797 0); 5798 return AutoDeductTy; 5799 } 5800 5801 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'. 5802 QualType ASTContext::getAutoRRefDeductType() const { 5803 if (AutoRRefDeductTy.isNull()) 5804 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType()); 5805 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern"); 5806 return AutoRRefDeductTy; 5807 } 5808 5809 /// getTagDeclType - Return the unique reference to the type for the 5810 /// specified TagDecl (struct/union/class/enum) decl. 5811 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const { 5812 assert(Decl); 5813 // FIXME: What is the design on getTagDeclType when it requires casting 5814 // away const? mutable? 5815 return getTypeDeclType(const_cast<TagDecl*>(Decl)); 5816 } 5817 5818 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result 5819 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and 5820 /// needs to agree with the definition in <stddef.h>. 5821 CanQualType ASTContext::getSizeType() const { 5822 return getFromTargetType(Target->getSizeType()); 5823 } 5824 5825 /// Return the unique signed counterpart of the integer type 5826 /// corresponding to size_t. 5827 CanQualType ASTContext::getSignedSizeType() const { 5828 return getFromTargetType(Target->getSignedSizeType()); 5829 } 5830 5831 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5). 5832 CanQualType ASTContext::getIntMaxType() const { 5833 return getFromTargetType(Target->getIntMaxType()); 5834 } 5835 5836 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5). 5837 CanQualType ASTContext::getUIntMaxType() const { 5838 return getFromTargetType(Target->getUIntMaxType()); 5839 } 5840 5841 /// getSignedWCharType - Return the type of "signed wchar_t". 5842 /// Used when in C++, as a GCC extension. 5843 QualType ASTContext::getSignedWCharType() const { 5844 // FIXME: derive from "Target" ? 5845 return WCharTy; 5846 } 5847 5848 /// getUnsignedWCharType - Return the type of "unsigned wchar_t". 5849 /// Used when in C++, as a GCC extension. 5850 QualType ASTContext::getUnsignedWCharType() const { 5851 // FIXME: derive from "Target" ? 5852 return UnsignedIntTy; 5853 } 5854 5855 QualType ASTContext::getIntPtrType() const { 5856 return getFromTargetType(Target->getIntPtrType()); 5857 } 5858 5859 QualType ASTContext::getUIntPtrType() const { 5860 return getCorrespondingUnsignedType(getIntPtrType()); 5861 } 5862 5863 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17) 5864 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9). 5865 QualType ASTContext::getPointerDiffType() const { 5866 return getFromTargetType(Target->getPtrDiffType(0)); 5867 } 5868 5869 /// Return the unique unsigned counterpart of "ptrdiff_t" 5870 /// integer type. The standard (C11 7.21.6.1p7) refers to this type 5871 /// in the definition of %tu format specifier. 5872 QualType ASTContext::getUnsignedPointerDiffType() const { 5873 return getFromTargetType(Target->getUnsignedPtrDiffType(0)); 5874 } 5875 5876 /// Return the unique type for "pid_t" defined in 5877 /// <sys/types.h>. We need this to compute the correct type for vfork(). 5878 QualType ASTContext::getProcessIDType() const { 5879 return getFromTargetType(Target->getProcessIDType()); 5880 } 5881 5882 //===----------------------------------------------------------------------===// 5883 // Type Operators 5884 //===----------------------------------------------------------------------===// 5885 5886 CanQualType ASTContext::getCanonicalParamType(QualType T) const { 5887 // Push qualifiers into arrays, and then discard any remaining 5888 // qualifiers. 5889 T = getCanonicalType(T); 5890 T = getVariableArrayDecayedType(T); 5891 const Type *Ty = T.getTypePtr(); 5892 QualType Result; 5893 if (isa<ArrayType>(Ty)) { 5894 Result = getArrayDecayedType(QualType(Ty,0)); 5895 } else if (isa<FunctionType>(Ty)) { 5896 Result = getPointerType(QualType(Ty, 0)); 5897 } else { 5898 Result = QualType(Ty, 0); 5899 } 5900 5901 return CanQualType::CreateUnsafe(Result); 5902 } 5903 5904 QualType ASTContext::getUnqualifiedArrayType(QualType type, 5905 Qualifiers &quals) { 5906 SplitQualType splitType = type.getSplitUnqualifiedType(); 5907 5908 // FIXME: getSplitUnqualifiedType() actually walks all the way to 5909 // the unqualified desugared type and then drops it on the floor. 5910 // We then have to strip that sugar back off with 5911 // getUnqualifiedDesugaredType(), which is silly. 5912 const auto *AT = 5913 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType()); 5914 5915 // If we don't have an array, just use the results in splitType. 5916 if (!AT) { 5917 quals = splitType.Quals; 5918 return QualType(splitType.Ty, 0); 5919 } 5920 5921 // Otherwise, recurse on the array's element type. 5922 QualType elementType = AT->getElementType(); 5923 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals); 5924 5925 // If that didn't change the element type, AT has no qualifiers, so we 5926 // can just use the results in splitType. 5927 if (elementType == unqualElementType) { 5928 assert(quals.empty()); // from the recursive call 5929 quals = splitType.Quals; 5930 return QualType(splitType.Ty, 0); 5931 } 5932 5933 // Otherwise, add in the qualifiers from the outermost type, then 5934 // build the type back up. 5935 quals.addConsistentQualifiers(splitType.Quals); 5936 5937 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 5938 return getConstantArrayType(unqualElementType, CAT->getSize(), 5939 CAT->getSizeExpr(), CAT->getSizeModifier(), 0); 5940 } 5941 5942 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) { 5943 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0); 5944 } 5945 5946 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) { 5947 return getVariableArrayType(unqualElementType, 5948 VAT->getSizeExpr(), 5949 VAT->getSizeModifier(), 5950 VAT->getIndexTypeCVRQualifiers(), 5951 VAT->getBracketsRange()); 5952 } 5953 5954 const auto *DSAT = cast<DependentSizedArrayType>(AT); 5955 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(), 5956 DSAT->getSizeModifier(), 0, 5957 SourceRange()); 5958 } 5959 5960 /// Attempt to unwrap two types that may both be array types with the same bound 5961 /// (or both be array types of unknown bound) for the purpose of comparing the 5962 /// cv-decomposition of two types per C++ [conv.qual]. 5963 /// 5964 /// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in 5965 /// C++20 [conv.qual], if permitted by the current language mode. 5966 void ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2, 5967 bool AllowPiMismatch) { 5968 while (true) { 5969 auto *AT1 = getAsArrayType(T1); 5970 if (!AT1) 5971 return; 5972 5973 auto *AT2 = getAsArrayType(T2); 5974 if (!AT2) 5975 return; 5976 5977 // If we don't have two array types with the same constant bound nor two 5978 // incomplete array types, we've unwrapped everything we can. 5979 // C++20 also permits one type to be a constant array type and the other 5980 // to be an incomplete array type. 5981 // FIXME: Consider also unwrapping array of unknown bound and VLA. 5982 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) { 5983 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2); 5984 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) || 5985 (AllowPiMismatch && getLangOpts().CPlusPlus20 && 5986 isa<IncompleteArrayType>(AT2)))) 5987 return; 5988 } else if (isa<IncompleteArrayType>(AT1)) { 5989 if (!(isa<IncompleteArrayType>(AT2) || 5990 (AllowPiMismatch && getLangOpts().CPlusPlus20 && 5991 isa<ConstantArrayType>(AT2)))) 5992 return; 5993 } else { 5994 return; 5995 } 5996 5997 T1 = AT1->getElementType(); 5998 T2 = AT2->getElementType(); 5999 } 6000 } 6001 6002 /// Attempt to unwrap two types that may be similar (C++ [conv.qual]). 6003 /// 6004 /// If T1 and T2 are both pointer types of the same kind, or both array types 6005 /// with the same bound, unwraps layers from T1 and T2 until a pointer type is 6006 /// unwrapped. Top-level qualifiers on T1 and T2 are ignored. 6007 /// 6008 /// This function will typically be called in a loop that successively 6009 /// "unwraps" pointer and pointer-to-member types to compare them at each 6010 /// level. 6011 /// 6012 /// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in 6013 /// C++20 [conv.qual], if permitted by the current language mode. 6014 /// 6015 /// \return \c true if a pointer type was unwrapped, \c false if we reached a 6016 /// pair of types that can't be unwrapped further. 6017 bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2, 6018 bool AllowPiMismatch) { 6019 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch); 6020 6021 const auto *T1PtrType = T1->getAs<PointerType>(); 6022 const auto *T2PtrType = T2->getAs<PointerType>(); 6023 if (T1PtrType && T2PtrType) { 6024 T1 = T1PtrType->getPointeeType(); 6025 T2 = T2PtrType->getPointeeType(); 6026 return true; 6027 } 6028 6029 const auto *T1MPType = T1->getAs<MemberPointerType>(); 6030 const auto *T2MPType = T2->getAs<MemberPointerType>(); 6031 if (T1MPType && T2MPType && 6032 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0), 6033 QualType(T2MPType->getClass(), 0))) { 6034 T1 = T1MPType->getPointeeType(); 6035 T2 = T2MPType->getPointeeType(); 6036 return true; 6037 } 6038 6039 if (getLangOpts().ObjC) { 6040 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>(); 6041 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>(); 6042 if (T1OPType && T2OPType) { 6043 T1 = T1OPType->getPointeeType(); 6044 T2 = T2OPType->getPointeeType(); 6045 return true; 6046 } 6047 } 6048 6049 // FIXME: Block pointers, too? 6050 6051 return false; 6052 } 6053 6054 bool ASTContext::hasSimilarType(QualType T1, QualType T2) { 6055 while (true) { 6056 Qualifiers Quals; 6057 T1 = getUnqualifiedArrayType(T1, Quals); 6058 T2 = getUnqualifiedArrayType(T2, Quals); 6059 if (hasSameType(T1, T2)) 6060 return true; 6061 if (!UnwrapSimilarTypes(T1, T2)) 6062 return false; 6063 } 6064 } 6065 6066 bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) { 6067 while (true) { 6068 Qualifiers Quals1, Quals2; 6069 T1 = getUnqualifiedArrayType(T1, Quals1); 6070 T2 = getUnqualifiedArrayType(T2, Quals2); 6071 6072 Quals1.removeCVRQualifiers(); 6073 Quals2.removeCVRQualifiers(); 6074 if (Quals1 != Quals2) 6075 return false; 6076 6077 if (hasSameType(T1, T2)) 6078 return true; 6079 6080 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false)) 6081 return false; 6082 } 6083 } 6084 6085 DeclarationNameInfo 6086 ASTContext::getNameForTemplate(TemplateName Name, 6087 SourceLocation NameLoc) const { 6088 switch (Name.getKind()) { 6089 case TemplateName::QualifiedTemplate: 6090 case TemplateName::Template: 6091 // DNInfo work in progress: CHECKME: what about DNLoc? 6092 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(), 6093 NameLoc); 6094 6095 case TemplateName::OverloadedTemplate: { 6096 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate(); 6097 // DNInfo work in progress: CHECKME: what about DNLoc? 6098 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc); 6099 } 6100 6101 case TemplateName::AssumedTemplate: { 6102 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName(); 6103 return DeclarationNameInfo(Storage->getDeclName(), NameLoc); 6104 } 6105 6106 case TemplateName::DependentTemplate: { 6107 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 6108 DeclarationName DName; 6109 if (DTN->isIdentifier()) { 6110 DName = DeclarationNames.getIdentifier(DTN->getIdentifier()); 6111 return DeclarationNameInfo(DName, NameLoc); 6112 } else { 6113 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator()); 6114 // DNInfo work in progress: FIXME: source locations? 6115 DeclarationNameLoc DNLoc = 6116 DeclarationNameLoc::makeCXXOperatorNameLoc(SourceRange()); 6117 return DeclarationNameInfo(DName, NameLoc, DNLoc); 6118 } 6119 } 6120 6121 case TemplateName::SubstTemplateTemplateParm: { 6122 SubstTemplateTemplateParmStorage *subst 6123 = Name.getAsSubstTemplateTemplateParm(); 6124 return DeclarationNameInfo(subst->getParameter()->getDeclName(), 6125 NameLoc); 6126 } 6127 6128 case TemplateName::SubstTemplateTemplateParmPack: { 6129 SubstTemplateTemplateParmPackStorage *subst 6130 = Name.getAsSubstTemplateTemplateParmPack(); 6131 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(), 6132 NameLoc); 6133 } 6134 case TemplateName::UsingTemplate: 6135 return DeclarationNameInfo(Name.getAsUsingShadowDecl()->getDeclName(), 6136 NameLoc); 6137 } 6138 6139 llvm_unreachable("bad template name kind!"); 6140 } 6141 6142 TemplateName 6143 ASTContext::getCanonicalTemplateName(const TemplateName &Name) const { 6144 switch (Name.getKind()) { 6145 case TemplateName::UsingTemplate: 6146 case TemplateName::QualifiedTemplate: 6147 case TemplateName::Template: { 6148 TemplateDecl *Template = Name.getAsTemplateDecl(); 6149 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template)) 6150 Template = getCanonicalTemplateTemplateParmDecl(TTP); 6151 6152 // The canonical template name is the canonical template declaration. 6153 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl())); 6154 } 6155 6156 case TemplateName::OverloadedTemplate: 6157 case TemplateName::AssumedTemplate: 6158 llvm_unreachable("cannot canonicalize unresolved template"); 6159 6160 case TemplateName::DependentTemplate: { 6161 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 6162 assert(DTN && "Non-dependent template names must refer to template decls."); 6163 return DTN->CanonicalTemplateName; 6164 } 6165 6166 case TemplateName::SubstTemplateTemplateParm: { 6167 SubstTemplateTemplateParmStorage *subst 6168 = Name.getAsSubstTemplateTemplateParm(); 6169 return getCanonicalTemplateName(subst->getReplacement()); 6170 } 6171 6172 case TemplateName::SubstTemplateTemplateParmPack: { 6173 SubstTemplateTemplateParmPackStorage *subst 6174 = Name.getAsSubstTemplateTemplateParmPack(); 6175 TemplateTemplateParmDecl *canonParameter 6176 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack()); 6177 TemplateArgument canonArgPack 6178 = getCanonicalTemplateArgument(subst->getArgumentPack()); 6179 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack); 6180 } 6181 } 6182 6183 llvm_unreachable("bad template name!"); 6184 } 6185 6186 bool ASTContext::hasSameTemplateName(const TemplateName &X, 6187 const TemplateName &Y) const { 6188 return getCanonicalTemplateName(X).getAsVoidPointer() == 6189 getCanonicalTemplateName(Y).getAsVoidPointer(); 6190 } 6191 6192 bool ASTContext::isSameTemplateParameter(const NamedDecl *X, 6193 const NamedDecl *Y) { 6194 if (X->getKind() != Y->getKind()) 6195 return false; 6196 6197 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) { 6198 auto *TY = cast<TemplateTypeParmDecl>(Y); 6199 if (TX->isParameterPack() != TY->isParameterPack()) 6200 return false; 6201 if (TX->hasTypeConstraint() != TY->hasTypeConstraint()) 6202 return false; 6203 const TypeConstraint *TXTC = TX->getTypeConstraint(); 6204 const TypeConstraint *TYTC = TY->getTypeConstraint(); 6205 if (!TXTC != !TYTC) 6206 return false; 6207 if (TXTC && TYTC) { 6208 auto *NCX = TXTC->getNamedConcept(); 6209 auto *NCY = TYTC->getNamedConcept(); 6210 if (!NCX || !NCY || !isSameEntity(NCX, NCY)) 6211 return false; 6212 if (TXTC->hasExplicitTemplateArgs() != TYTC->hasExplicitTemplateArgs()) 6213 return false; 6214 if (TXTC->hasExplicitTemplateArgs()) { 6215 auto *TXTCArgs = TXTC->getTemplateArgsAsWritten(); 6216 auto *TYTCArgs = TYTC->getTemplateArgsAsWritten(); 6217 if (TXTCArgs->NumTemplateArgs != TYTCArgs->NumTemplateArgs) 6218 return false; 6219 llvm::FoldingSetNodeID XID, YID; 6220 for (auto &ArgLoc : TXTCArgs->arguments()) 6221 ArgLoc.getArgument().Profile(XID, X->getASTContext()); 6222 for (auto &ArgLoc : TYTCArgs->arguments()) 6223 ArgLoc.getArgument().Profile(YID, Y->getASTContext()); 6224 if (XID != YID) 6225 return false; 6226 } 6227 } 6228 return true; 6229 } 6230 6231 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) { 6232 auto *TY = cast<NonTypeTemplateParmDecl>(Y); 6233 return TX->isParameterPack() == TY->isParameterPack() && 6234 TX->getASTContext().hasSameType(TX->getType(), TY->getType()); 6235 } 6236 6237 auto *TX = cast<TemplateTemplateParmDecl>(X); 6238 auto *TY = cast<TemplateTemplateParmDecl>(Y); 6239 return TX->isParameterPack() == TY->isParameterPack() && 6240 isSameTemplateParameterList(TX->getTemplateParameters(), 6241 TY->getTemplateParameters()); 6242 } 6243 6244 bool ASTContext::isSameTemplateParameterList(const TemplateParameterList *X, 6245 const TemplateParameterList *Y) { 6246 if (X->size() != Y->size()) 6247 return false; 6248 6249 for (unsigned I = 0, N = X->size(); I != N; ++I) 6250 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I))) 6251 return false; 6252 6253 const Expr *XRC = X->getRequiresClause(); 6254 const Expr *YRC = Y->getRequiresClause(); 6255 if (!XRC != !YRC) 6256 return false; 6257 if (XRC) { 6258 llvm::FoldingSetNodeID XRCID, YRCID; 6259 XRC->Profile(XRCID, *this, /*Canonical=*/true); 6260 YRC->Profile(YRCID, *this, /*Canonical=*/true); 6261 if (XRCID != YRCID) 6262 return false; 6263 } 6264 6265 return true; 6266 } 6267 6268 static NamespaceDecl *getNamespace(const NestedNameSpecifier *X) { 6269 if (auto *NS = X->getAsNamespace()) 6270 return NS; 6271 if (auto *NAS = X->getAsNamespaceAlias()) 6272 return NAS->getNamespace(); 6273 return nullptr; 6274 } 6275 6276 static bool isSameQualifier(const NestedNameSpecifier *X, 6277 const NestedNameSpecifier *Y) { 6278 if (auto *NSX = getNamespace(X)) { 6279 auto *NSY = getNamespace(Y); 6280 if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl()) 6281 return false; 6282 } else if (X->getKind() != Y->getKind()) 6283 return false; 6284 6285 // FIXME: For namespaces and types, we're permitted to check that the entity 6286 // is named via the same tokens. We should probably do so. 6287 switch (X->getKind()) { 6288 case NestedNameSpecifier::Identifier: 6289 if (X->getAsIdentifier() != Y->getAsIdentifier()) 6290 return false; 6291 break; 6292 case NestedNameSpecifier::Namespace: 6293 case NestedNameSpecifier::NamespaceAlias: 6294 // We've already checked that we named the same namespace. 6295 break; 6296 case NestedNameSpecifier::TypeSpec: 6297 case NestedNameSpecifier::TypeSpecWithTemplate: 6298 if (X->getAsType()->getCanonicalTypeInternal() != 6299 Y->getAsType()->getCanonicalTypeInternal()) 6300 return false; 6301 break; 6302 case NestedNameSpecifier::Global: 6303 case NestedNameSpecifier::Super: 6304 return true; 6305 } 6306 6307 // Recurse into earlier portion of NNS, if any. 6308 auto *PX = X->getPrefix(); 6309 auto *PY = Y->getPrefix(); 6310 if (PX && PY) 6311 return isSameQualifier(PX, PY); 6312 return !PX && !PY; 6313 } 6314 6315 /// Determine whether the attributes we can overload on are identical for A and 6316 /// B. Will ignore any overloadable attrs represented in the type of A and B. 6317 static bool hasSameOverloadableAttrs(const FunctionDecl *A, 6318 const FunctionDecl *B) { 6319 // Note that pass_object_size attributes are represented in the function's 6320 // ExtParameterInfo, so we don't need to check them here. 6321 6322 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 6323 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>(); 6324 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>(); 6325 6326 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) { 6327 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); 6328 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); 6329 6330 // Return false if the number of enable_if attributes is different. 6331 if (!Cand1A || !Cand2A) 6332 return false; 6333 6334 Cand1ID.clear(); 6335 Cand2ID.clear(); 6336 6337 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true); 6338 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true); 6339 6340 // Return false if any of the enable_if expressions of A and B are 6341 // different. 6342 if (Cand1ID != Cand2ID) 6343 return false; 6344 } 6345 return true; 6346 } 6347 6348 bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) { 6349 if (X == Y) 6350 return true; 6351 6352 if (X->getDeclName() != Y->getDeclName()) 6353 return false; 6354 6355 // Must be in the same context. 6356 // 6357 // Note that we can't use DeclContext::Equals here, because the DeclContexts 6358 // could be two different declarations of the same function. (We will fix the 6359 // semantic DC to refer to the primary definition after merging.) 6360 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()), 6361 cast<Decl>(Y->getDeclContext()->getRedeclContext()))) 6362 return false; 6363 6364 // Two typedefs refer to the same entity if they have the same underlying 6365 // type. 6366 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X)) 6367 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y)) 6368 return hasSameType(TypedefX->getUnderlyingType(), 6369 TypedefY->getUnderlyingType()); 6370 6371 // Must have the same kind. 6372 if (X->getKind() != Y->getKind()) 6373 return false; 6374 6375 // Objective-C classes and protocols with the same name always match. 6376 if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X)) 6377 return true; 6378 6379 if (isa<ClassTemplateSpecializationDecl>(X)) { 6380 // No need to handle these here: we merge them when adding them to the 6381 // template. 6382 return false; 6383 } 6384 6385 // Compatible tags match. 6386 if (const auto *TagX = dyn_cast<TagDecl>(X)) { 6387 const auto *TagY = cast<TagDecl>(Y); 6388 return (TagX->getTagKind() == TagY->getTagKind()) || 6389 ((TagX->getTagKind() == TTK_Struct || 6390 TagX->getTagKind() == TTK_Class || 6391 TagX->getTagKind() == TTK_Interface) && 6392 (TagY->getTagKind() == TTK_Struct || 6393 TagY->getTagKind() == TTK_Class || 6394 TagY->getTagKind() == TTK_Interface)); 6395 } 6396 6397 // Functions with the same type and linkage match. 6398 // FIXME: This needs to cope with merging of prototyped/non-prototyped 6399 // functions, etc. 6400 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) { 6401 const auto *FuncY = cast<FunctionDecl>(Y); 6402 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) { 6403 const auto *CtorY = cast<CXXConstructorDecl>(Y); 6404 if (CtorX->getInheritedConstructor() && 6405 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(), 6406 CtorY->getInheritedConstructor().getConstructor())) 6407 return false; 6408 } 6409 6410 if (FuncX->isMultiVersion() != FuncY->isMultiVersion()) 6411 return false; 6412 6413 // Multiversioned functions with different feature strings are represented 6414 // as separate declarations. 6415 if (FuncX->isMultiVersion()) { 6416 const auto *TAX = FuncX->getAttr<TargetAttr>(); 6417 const auto *TAY = FuncY->getAttr<TargetAttr>(); 6418 assert(TAX && TAY && "Multiversion Function without target attribute"); 6419 6420 if (TAX->getFeaturesStr() != TAY->getFeaturesStr()) 6421 return false; 6422 } 6423 6424 const Expr *XRC = FuncX->getTrailingRequiresClause(); 6425 const Expr *YRC = FuncY->getTrailingRequiresClause(); 6426 if (!XRC != !YRC) 6427 return false; 6428 if (XRC) { 6429 llvm::FoldingSetNodeID XRCID, YRCID; 6430 XRC->Profile(XRCID, *this, /*Canonical=*/true); 6431 YRC->Profile(YRCID, *this, /*Canonical=*/true); 6432 if (XRCID != YRCID) 6433 return false; 6434 } 6435 6436 auto GetTypeAsWritten = [](const FunctionDecl *FD) { 6437 // Map to the first declaration that we've already merged into this one. 6438 // The TSI of redeclarations might not match (due to calling conventions 6439 // being inherited onto the type but not the TSI), but the TSI type of 6440 // the first declaration of the function should match across modules. 6441 FD = FD->getCanonicalDecl(); 6442 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType() 6443 : FD->getType(); 6444 }; 6445 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY); 6446 if (!hasSameType(XT, YT)) { 6447 // We can get functions with different types on the redecl chain in C++17 6448 // if they have differing exception specifications and at least one of 6449 // the excpetion specs is unresolved. 6450 auto *XFPT = XT->getAs<FunctionProtoType>(); 6451 auto *YFPT = YT->getAs<FunctionProtoType>(); 6452 if (getLangOpts().CPlusPlus17 && XFPT && YFPT && 6453 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) || 6454 isUnresolvedExceptionSpec(YFPT->getExceptionSpecType())) && 6455 // FIXME: We could make isSameEntity const after we make 6456 // hasSameFunctionTypeIgnoringExceptionSpec const. 6457 hasSameFunctionTypeIgnoringExceptionSpec(XT, YT)) 6458 return true; 6459 return false; 6460 } 6461 6462 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() && 6463 hasSameOverloadableAttrs(FuncX, FuncY); 6464 } 6465 6466 // Variables with the same type and linkage match. 6467 if (const auto *VarX = dyn_cast<VarDecl>(X)) { 6468 const auto *VarY = cast<VarDecl>(Y); 6469 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) { 6470 if (hasSameType(VarX->getType(), VarY->getType())) 6471 return true; 6472 6473 // We can get decls with different types on the redecl chain. Eg. 6474 // template <typename T> struct S { static T Var[]; }; // #1 6475 // template <typename T> T S<T>::Var[sizeof(T)]; // #2 6476 // Only? happens when completing an incomplete array type. In this case 6477 // when comparing #1 and #2 we should go through their element type. 6478 const ArrayType *VarXTy = getAsArrayType(VarX->getType()); 6479 const ArrayType *VarYTy = getAsArrayType(VarY->getType()); 6480 if (!VarXTy || !VarYTy) 6481 return false; 6482 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType()) 6483 return hasSameType(VarXTy->getElementType(), VarYTy->getElementType()); 6484 } 6485 return false; 6486 } 6487 6488 // Namespaces with the same name and inlinedness match. 6489 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) { 6490 const auto *NamespaceY = cast<NamespaceDecl>(Y); 6491 return NamespaceX->isInline() == NamespaceY->isInline(); 6492 } 6493 6494 // Identical template names and kinds match if their template parameter lists 6495 // and patterns match. 6496 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) { 6497 const auto *TemplateY = cast<TemplateDecl>(Y); 6498 return isSameEntity(TemplateX->getTemplatedDecl(), 6499 TemplateY->getTemplatedDecl()) && 6500 isSameTemplateParameterList(TemplateX->getTemplateParameters(), 6501 TemplateY->getTemplateParameters()); 6502 } 6503 6504 // Fields with the same name and the same type match. 6505 if (const auto *FDX = dyn_cast<FieldDecl>(X)) { 6506 const auto *FDY = cast<FieldDecl>(Y); 6507 // FIXME: Also check the bitwidth is odr-equivalent, if any. 6508 return hasSameType(FDX->getType(), FDY->getType()); 6509 } 6510 6511 // Indirect fields with the same target field match. 6512 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) { 6513 const auto *IFDY = cast<IndirectFieldDecl>(Y); 6514 return IFDX->getAnonField()->getCanonicalDecl() == 6515 IFDY->getAnonField()->getCanonicalDecl(); 6516 } 6517 6518 // Enumerators with the same name match. 6519 if (isa<EnumConstantDecl>(X)) 6520 // FIXME: Also check the value is odr-equivalent. 6521 return true; 6522 6523 // Using shadow declarations with the same target match. 6524 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) { 6525 const auto *USY = cast<UsingShadowDecl>(Y); 6526 return USX->getTargetDecl() == USY->getTargetDecl(); 6527 } 6528 6529 // Using declarations with the same qualifier match. (We already know that 6530 // the name matches.) 6531 if (const auto *UX = dyn_cast<UsingDecl>(X)) { 6532 const auto *UY = cast<UsingDecl>(Y); 6533 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) && 6534 UX->hasTypename() == UY->hasTypename() && 6535 UX->isAccessDeclaration() == UY->isAccessDeclaration(); 6536 } 6537 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) { 6538 const auto *UY = cast<UnresolvedUsingValueDecl>(Y); 6539 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) && 6540 UX->isAccessDeclaration() == UY->isAccessDeclaration(); 6541 } 6542 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) { 6543 return isSameQualifier( 6544 UX->getQualifier(), 6545 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier()); 6546 } 6547 6548 // Using-pack declarations are only created by instantiation, and match if 6549 // they're instantiated from matching UnresolvedUsing...Decls. 6550 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) { 6551 return declaresSameEntity( 6552 UX->getInstantiatedFromUsingDecl(), 6553 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl()); 6554 } 6555 6556 // Namespace alias definitions with the same target match. 6557 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) { 6558 const auto *NAY = cast<NamespaceAliasDecl>(Y); 6559 return NAX->getNamespace()->Equals(NAY->getNamespace()); 6560 } 6561 6562 return false; 6563 } 6564 6565 TemplateArgument 6566 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const { 6567 switch (Arg.getKind()) { 6568 case TemplateArgument::Null: 6569 return Arg; 6570 6571 case TemplateArgument::Expression: 6572 return Arg; 6573 6574 case TemplateArgument::Declaration: { 6575 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl()); 6576 return TemplateArgument(D, Arg.getParamTypeForDecl()); 6577 } 6578 6579 case TemplateArgument::NullPtr: 6580 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()), 6581 /*isNullPtr*/true); 6582 6583 case TemplateArgument::Template: 6584 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate())); 6585 6586 case TemplateArgument::TemplateExpansion: 6587 return TemplateArgument(getCanonicalTemplateName( 6588 Arg.getAsTemplateOrTemplatePattern()), 6589 Arg.getNumTemplateExpansions()); 6590 6591 case TemplateArgument::Integral: 6592 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType())); 6593 6594 case TemplateArgument::Type: 6595 return TemplateArgument(getCanonicalType(Arg.getAsType())); 6596 6597 case TemplateArgument::Pack: { 6598 if (Arg.pack_size() == 0) 6599 return Arg; 6600 6601 auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()]; 6602 unsigned Idx = 0; 6603 for (TemplateArgument::pack_iterator A = Arg.pack_begin(), 6604 AEnd = Arg.pack_end(); 6605 A != AEnd; (void)++A, ++Idx) 6606 CanonArgs[Idx] = getCanonicalTemplateArgument(*A); 6607 6608 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size())); 6609 } 6610 } 6611 6612 // Silence GCC warning 6613 llvm_unreachable("Unhandled template argument kind"); 6614 } 6615 6616 NestedNameSpecifier * 6617 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const { 6618 if (!NNS) 6619 return nullptr; 6620 6621 switch (NNS->getKind()) { 6622 case NestedNameSpecifier::Identifier: 6623 // Canonicalize the prefix but keep the identifier the same. 6624 return NestedNameSpecifier::Create(*this, 6625 getCanonicalNestedNameSpecifier(NNS->getPrefix()), 6626 NNS->getAsIdentifier()); 6627 6628 case NestedNameSpecifier::Namespace: 6629 // A namespace is canonical; build a nested-name-specifier with 6630 // this namespace and no prefix. 6631 return NestedNameSpecifier::Create(*this, nullptr, 6632 NNS->getAsNamespace()->getOriginalNamespace()); 6633 6634 case NestedNameSpecifier::NamespaceAlias: 6635 // A namespace is canonical; build a nested-name-specifier with 6636 // this namespace and no prefix. 6637 return NestedNameSpecifier::Create(*this, nullptr, 6638 NNS->getAsNamespaceAlias()->getNamespace() 6639 ->getOriginalNamespace()); 6640 6641 // The difference between TypeSpec and TypeSpecWithTemplate is that the 6642 // latter will have the 'template' keyword when printed. 6643 case NestedNameSpecifier::TypeSpec: 6644 case NestedNameSpecifier::TypeSpecWithTemplate: { 6645 const Type *T = getCanonicalType(NNS->getAsType()); 6646 6647 // If we have some kind of dependent-named type (e.g., "typename T::type"), 6648 // break it apart into its prefix and identifier, then reconsititute those 6649 // as the canonical nested-name-specifier. This is required to canonicalize 6650 // a dependent nested-name-specifier involving typedefs of dependent-name 6651 // types, e.g., 6652 // typedef typename T::type T1; 6653 // typedef typename T1::type T2; 6654 if (const auto *DNT = T->getAs<DependentNameType>()) 6655 return NestedNameSpecifier::Create( 6656 *this, DNT->getQualifier(), 6657 const_cast<IdentifierInfo *>(DNT->getIdentifier())); 6658 if (const auto *DTST = T->getAs<DependentTemplateSpecializationType>()) 6659 return NestedNameSpecifier::Create(*this, DTST->getQualifier(), true, 6660 const_cast<Type *>(T)); 6661 6662 // TODO: Set 'Template' parameter to true for other template types. 6663 return NestedNameSpecifier::Create(*this, nullptr, false, 6664 const_cast<Type *>(T)); 6665 } 6666 6667 case NestedNameSpecifier::Global: 6668 case NestedNameSpecifier::Super: 6669 // The global specifier and __super specifer are canonical and unique. 6670 return NNS; 6671 } 6672 6673 llvm_unreachable("Invalid NestedNameSpecifier::Kind!"); 6674 } 6675 6676 const ArrayType *ASTContext::getAsArrayType(QualType T) const { 6677 // Handle the non-qualified case efficiently. 6678 if (!T.hasLocalQualifiers()) { 6679 // Handle the common positive case fast. 6680 if (const auto *AT = dyn_cast<ArrayType>(T)) 6681 return AT; 6682 } 6683 6684 // Handle the common negative case fast. 6685 if (!isa<ArrayType>(T.getCanonicalType())) 6686 return nullptr; 6687 6688 // Apply any qualifiers from the array type to the element type. This 6689 // implements C99 6.7.3p8: "If the specification of an array type includes 6690 // any type qualifiers, the element type is so qualified, not the array type." 6691 6692 // If we get here, we either have type qualifiers on the type, or we have 6693 // sugar such as a typedef in the way. If we have type qualifiers on the type 6694 // we must propagate them down into the element type. 6695 6696 SplitQualType split = T.getSplitDesugaredType(); 6697 Qualifiers qs = split.Quals; 6698 6699 // If we have a simple case, just return now. 6700 const auto *ATy = dyn_cast<ArrayType>(split.Ty); 6701 if (!ATy || qs.empty()) 6702 return ATy; 6703 6704 // Otherwise, we have an array and we have qualifiers on it. Push the 6705 // qualifiers into the array element type and return a new array type. 6706 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs); 6707 6708 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy)) 6709 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(), 6710 CAT->getSizeExpr(), 6711 CAT->getSizeModifier(), 6712 CAT->getIndexTypeCVRQualifiers())); 6713 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy)) 6714 return cast<ArrayType>(getIncompleteArrayType(NewEltTy, 6715 IAT->getSizeModifier(), 6716 IAT->getIndexTypeCVRQualifiers())); 6717 6718 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy)) 6719 return cast<ArrayType>( 6720 getDependentSizedArrayType(NewEltTy, 6721 DSAT->getSizeExpr(), 6722 DSAT->getSizeModifier(), 6723 DSAT->getIndexTypeCVRQualifiers(), 6724 DSAT->getBracketsRange())); 6725 6726 const auto *VAT = cast<VariableArrayType>(ATy); 6727 return cast<ArrayType>(getVariableArrayType(NewEltTy, 6728 VAT->getSizeExpr(), 6729 VAT->getSizeModifier(), 6730 VAT->getIndexTypeCVRQualifiers(), 6731 VAT->getBracketsRange())); 6732 } 6733 6734 QualType ASTContext::getAdjustedParameterType(QualType T) const { 6735 if (T->isArrayType() || T->isFunctionType()) 6736 return getDecayedType(T); 6737 return T; 6738 } 6739 6740 QualType ASTContext::getSignatureParameterType(QualType T) const { 6741 T = getVariableArrayDecayedType(T); 6742 T = getAdjustedParameterType(T); 6743 return T.getUnqualifiedType(); 6744 } 6745 6746 QualType ASTContext::getExceptionObjectType(QualType T) const { 6747 // C++ [except.throw]p3: 6748 // A throw-expression initializes a temporary object, called the exception 6749 // object, the type of which is determined by removing any top-level 6750 // cv-qualifiers from the static type of the operand of throw and adjusting 6751 // the type from "array of T" or "function returning T" to "pointer to T" 6752 // or "pointer to function returning T", [...] 6753 T = getVariableArrayDecayedType(T); 6754 if (T->isArrayType() || T->isFunctionType()) 6755 T = getDecayedType(T); 6756 return T.getUnqualifiedType(); 6757 } 6758 6759 /// getArrayDecayedType - Return the properly qualified result of decaying the 6760 /// specified array type to a pointer. This operation is non-trivial when 6761 /// handling typedefs etc. The canonical type of "T" must be an array type, 6762 /// this returns a pointer to a properly qualified element of the array. 6763 /// 6764 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3. 6765 QualType ASTContext::getArrayDecayedType(QualType Ty) const { 6766 // Get the element type with 'getAsArrayType' so that we don't lose any 6767 // typedefs in the element type of the array. This also handles propagation 6768 // of type qualifiers from the array type into the element type if present 6769 // (C99 6.7.3p8). 6770 const ArrayType *PrettyArrayType = getAsArrayType(Ty); 6771 assert(PrettyArrayType && "Not an array type!"); 6772 6773 QualType PtrTy = getPointerType(PrettyArrayType->getElementType()); 6774 6775 // int x[restrict 4] -> int *restrict 6776 QualType Result = getQualifiedType(PtrTy, 6777 PrettyArrayType->getIndexTypeQualifiers()); 6778 6779 // int x[_Nullable] -> int * _Nullable 6780 if (auto Nullability = Ty->getNullability(*this)) { 6781 Result = const_cast<ASTContext *>(this)->getAttributedType( 6782 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result); 6783 } 6784 return Result; 6785 } 6786 6787 QualType ASTContext::getBaseElementType(const ArrayType *array) const { 6788 return getBaseElementType(array->getElementType()); 6789 } 6790 6791 QualType ASTContext::getBaseElementType(QualType type) const { 6792 Qualifiers qs; 6793 while (true) { 6794 SplitQualType split = type.getSplitDesugaredType(); 6795 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe(); 6796 if (!array) break; 6797 6798 type = array->getElementType(); 6799 qs.addConsistentQualifiers(split.Quals); 6800 } 6801 6802 return getQualifiedType(type, qs); 6803 } 6804 6805 /// getConstantArrayElementCount - Returns number of constant array elements. 6806 uint64_t 6807 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const { 6808 uint64_t ElementCount = 1; 6809 do { 6810 ElementCount *= CA->getSize().getZExtValue(); 6811 CA = dyn_cast_or_null<ConstantArrayType>( 6812 CA->getElementType()->getAsArrayTypeUnsafe()); 6813 } while (CA); 6814 return ElementCount; 6815 } 6816 6817 /// getFloatingRank - Return a relative rank for floating point types. 6818 /// This routine will assert if passed a built-in type that isn't a float. 6819 static FloatingRank getFloatingRank(QualType T) { 6820 if (const auto *CT = T->getAs<ComplexType>()) 6821 return getFloatingRank(CT->getElementType()); 6822 6823 switch (T->castAs<BuiltinType>()->getKind()) { 6824 default: llvm_unreachable("getFloatingRank(): not a floating type"); 6825 case BuiltinType::Float16: return Float16Rank; 6826 case BuiltinType::Half: return HalfRank; 6827 case BuiltinType::Float: return FloatRank; 6828 case BuiltinType::Double: return DoubleRank; 6829 case BuiltinType::LongDouble: return LongDoubleRank; 6830 case BuiltinType::Float128: return Float128Rank; 6831 case BuiltinType::BFloat16: return BFloat16Rank; 6832 case BuiltinType::Ibm128: return Ibm128Rank; 6833 } 6834 } 6835 6836 /// getFloatingTypeOrder - Compare the rank of the two specified floating 6837 /// point types, ignoring the domain of the type (i.e. 'double' == 6838 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If 6839 /// LHS < RHS, return -1. 6840 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const { 6841 FloatingRank LHSR = getFloatingRank(LHS); 6842 FloatingRank RHSR = getFloatingRank(RHS); 6843 6844 if (LHSR == RHSR) 6845 return 0; 6846 if (LHSR > RHSR) 6847 return 1; 6848 return -1; 6849 } 6850 6851 int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const { 6852 if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS)) 6853 return 0; 6854 return getFloatingTypeOrder(LHS, RHS); 6855 } 6856 6857 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This 6858 /// routine will assert if passed a built-in type that isn't an integer or enum, 6859 /// or if it is not canonicalized. 6860 unsigned ASTContext::getIntegerRank(const Type *T) const { 6861 assert(T->isCanonicalUnqualified() && "T should be canonicalized"); 6862 6863 // Results in this 'losing' to any type of the same size, but winning if 6864 // larger. 6865 if (const auto *EIT = dyn_cast<BitIntType>(T)) 6866 return 0 + (EIT->getNumBits() << 3); 6867 6868 switch (cast<BuiltinType>(T)->getKind()) { 6869 default: llvm_unreachable("getIntegerRank(): not a built-in integer"); 6870 case BuiltinType::Bool: 6871 return 1 + (getIntWidth(BoolTy) << 3); 6872 case BuiltinType::Char_S: 6873 case BuiltinType::Char_U: 6874 case BuiltinType::SChar: 6875 case BuiltinType::UChar: 6876 return 2 + (getIntWidth(CharTy) << 3); 6877 case BuiltinType::Short: 6878 case BuiltinType::UShort: 6879 return 3 + (getIntWidth(ShortTy) << 3); 6880 case BuiltinType::Int: 6881 case BuiltinType::UInt: 6882 return 4 + (getIntWidth(IntTy) << 3); 6883 case BuiltinType::Long: 6884 case BuiltinType::ULong: 6885 return 5 + (getIntWidth(LongTy) << 3); 6886 case BuiltinType::LongLong: 6887 case BuiltinType::ULongLong: 6888 return 6 + (getIntWidth(LongLongTy) << 3); 6889 case BuiltinType::Int128: 6890 case BuiltinType::UInt128: 6891 return 7 + (getIntWidth(Int128Ty) << 3); 6892 } 6893 } 6894 6895 /// Whether this is a promotable bitfield reference according 6896 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions). 6897 /// 6898 /// \returns the type this bit-field will promote to, or NULL if no 6899 /// promotion occurs. 6900 QualType ASTContext::isPromotableBitField(Expr *E) const { 6901 if (E->isTypeDependent() || E->isValueDependent()) 6902 return {}; 6903 6904 // C++ [conv.prom]p5: 6905 // If the bit-field has an enumerated type, it is treated as any other 6906 // value of that type for promotion purposes. 6907 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType()) 6908 return {}; 6909 6910 // FIXME: We should not do this unless E->refersToBitField() is true. This 6911 // matters in C where getSourceBitField() will find bit-fields for various 6912 // cases where the source expression is not a bit-field designator. 6913 6914 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields? 6915 if (!Field) 6916 return {}; 6917 6918 QualType FT = Field->getType(); 6919 6920 uint64_t BitWidth = Field->getBitWidthValue(*this); 6921 uint64_t IntSize = getTypeSize(IntTy); 6922 // C++ [conv.prom]p5: 6923 // A prvalue for an integral bit-field can be converted to a prvalue of type 6924 // int if int can represent all the values of the bit-field; otherwise, it 6925 // can be converted to unsigned int if unsigned int can represent all the 6926 // values of the bit-field. If the bit-field is larger yet, no integral 6927 // promotion applies to it. 6928 // C11 6.3.1.1/2: 6929 // [For a bit-field of type _Bool, int, signed int, or unsigned int:] 6930 // If an int can represent all values of the original type (as restricted by 6931 // the width, for a bit-field), the value is converted to an int; otherwise, 6932 // it is converted to an unsigned int. 6933 // 6934 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int. 6935 // We perform that promotion here to match GCC and C++. 6936 // FIXME: C does not permit promotion of an enum bit-field whose rank is 6937 // greater than that of 'int'. We perform that promotion to match GCC. 6938 if (BitWidth < IntSize) 6939 return IntTy; 6940 6941 if (BitWidth == IntSize) 6942 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy; 6943 6944 // Bit-fields wider than int are not subject to promotions, and therefore act 6945 // like the base type. GCC has some weird bugs in this area that we 6946 // deliberately do not follow (GCC follows a pre-standard resolution to 6947 // C's DR315 which treats bit-width as being part of the type, and this leaks 6948 // into their semantics in some cases). 6949 return {}; 6950 } 6951 6952 /// getPromotedIntegerType - Returns the type that Promotable will 6953 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable 6954 /// integer type. 6955 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const { 6956 assert(!Promotable.isNull()); 6957 assert(Promotable->isPromotableIntegerType()); 6958 if (const auto *ET = Promotable->getAs<EnumType>()) 6959 return ET->getDecl()->getPromotionType(); 6960 6961 if (const auto *BT = Promotable->getAs<BuiltinType>()) { 6962 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t 6963 // (3.9.1) can be converted to a prvalue of the first of the following 6964 // types that can represent all the values of its underlying type: 6965 // int, unsigned int, long int, unsigned long int, long long int, or 6966 // unsigned long long int [...] 6967 // FIXME: Is there some better way to compute this? 6968 if (BT->getKind() == BuiltinType::WChar_S || 6969 BT->getKind() == BuiltinType::WChar_U || 6970 BT->getKind() == BuiltinType::Char8 || 6971 BT->getKind() == BuiltinType::Char16 || 6972 BT->getKind() == BuiltinType::Char32) { 6973 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S; 6974 uint64_t FromSize = getTypeSize(BT); 6975 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy, 6976 LongLongTy, UnsignedLongLongTy }; 6977 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) { 6978 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]); 6979 if (FromSize < ToSize || 6980 (FromSize == ToSize && 6981 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) 6982 return PromoteTypes[Idx]; 6983 } 6984 llvm_unreachable("char type should fit into long long"); 6985 } 6986 } 6987 6988 // At this point, we should have a signed or unsigned integer type. 6989 if (Promotable->isSignedIntegerType()) 6990 return IntTy; 6991 uint64_t PromotableSize = getIntWidth(Promotable); 6992 uint64_t IntSize = getIntWidth(IntTy); 6993 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize); 6994 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy; 6995 } 6996 6997 /// Recurses in pointer/array types until it finds an objc retainable 6998 /// type and returns its ownership. 6999 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const { 7000 while (!T.isNull()) { 7001 if (T.getObjCLifetime() != Qualifiers::OCL_None) 7002 return T.getObjCLifetime(); 7003 if (T->isArrayType()) 7004 T = getBaseElementType(T); 7005 else if (const auto *PT = T->getAs<PointerType>()) 7006 T = PT->getPointeeType(); 7007 else if (const auto *RT = T->getAs<ReferenceType>()) 7008 T = RT->getPointeeType(); 7009 else 7010 break; 7011 } 7012 7013 return Qualifiers::OCL_None; 7014 } 7015 7016 static const Type *getIntegerTypeForEnum(const EnumType *ET) { 7017 // Incomplete enum types are not treated as integer types. 7018 // FIXME: In C++, enum types are never integer types. 7019 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped()) 7020 return ET->getDecl()->getIntegerType().getTypePtr(); 7021 return nullptr; 7022 } 7023 7024 /// getIntegerTypeOrder - Returns the highest ranked integer type: 7025 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If 7026 /// LHS < RHS, return -1. 7027 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const { 7028 const Type *LHSC = getCanonicalType(LHS).getTypePtr(); 7029 const Type *RHSC = getCanonicalType(RHS).getTypePtr(); 7030 7031 // Unwrap enums to their underlying type. 7032 if (const auto *ET = dyn_cast<EnumType>(LHSC)) 7033 LHSC = getIntegerTypeForEnum(ET); 7034 if (const auto *ET = dyn_cast<EnumType>(RHSC)) 7035 RHSC = getIntegerTypeForEnum(ET); 7036 7037 if (LHSC == RHSC) return 0; 7038 7039 bool LHSUnsigned = LHSC->isUnsignedIntegerType(); 7040 bool RHSUnsigned = RHSC->isUnsignedIntegerType(); 7041 7042 unsigned LHSRank = getIntegerRank(LHSC); 7043 unsigned RHSRank = getIntegerRank(RHSC); 7044 7045 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned. 7046 if (LHSRank == RHSRank) return 0; 7047 return LHSRank > RHSRank ? 1 : -1; 7048 } 7049 7050 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa. 7051 if (LHSUnsigned) { 7052 // If the unsigned [LHS] type is larger, return it. 7053 if (LHSRank >= RHSRank) 7054 return 1; 7055 7056 // If the signed type can represent all values of the unsigned type, it 7057 // wins. Because we are dealing with 2's complement and types that are 7058 // powers of two larger than each other, this is always safe. 7059 return -1; 7060 } 7061 7062 // If the unsigned [RHS] type is larger, return it. 7063 if (RHSRank >= LHSRank) 7064 return -1; 7065 7066 // If the signed type can represent all values of the unsigned type, it 7067 // wins. Because we are dealing with 2's complement and types that are 7068 // powers of two larger than each other, this is always safe. 7069 return 1; 7070 } 7071 7072 TypedefDecl *ASTContext::getCFConstantStringDecl() const { 7073 if (CFConstantStringTypeDecl) 7074 return CFConstantStringTypeDecl; 7075 7076 assert(!CFConstantStringTagDecl && 7077 "tag and typedef should be initialized together"); 7078 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag"); 7079 CFConstantStringTagDecl->startDefinition(); 7080 7081 struct { 7082 QualType Type; 7083 const char *Name; 7084 } Fields[5]; 7085 unsigned Count = 0; 7086 7087 /// Objective-C ABI 7088 /// 7089 /// typedef struct __NSConstantString_tag { 7090 /// const int *isa; 7091 /// int flags; 7092 /// const char *str; 7093 /// long length; 7094 /// } __NSConstantString; 7095 /// 7096 /// Swift ABI (4.1, 4.2) 7097 /// 7098 /// typedef struct __NSConstantString_tag { 7099 /// uintptr_t _cfisa; 7100 /// uintptr_t _swift_rc; 7101 /// _Atomic(uint64_t) _cfinfoa; 7102 /// const char *_ptr; 7103 /// uint32_t _length; 7104 /// } __NSConstantString; 7105 /// 7106 /// Swift ABI (5.0) 7107 /// 7108 /// typedef struct __NSConstantString_tag { 7109 /// uintptr_t _cfisa; 7110 /// uintptr_t _swift_rc; 7111 /// _Atomic(uint64_t) _cfinfoa; 7112 /// const char *_ptr; 7113 /// uintptr_t _length; 7114 /// } __NSConstantString; 7115 7116 const auto CFRuntime = getLangOpts().CFRuntime; 7117 if (static_cast<unsigned>(CFRuntime) < 7118 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) { 7119 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" }; 7120 Fields[Count++] = { IntTy, "flags" }; 7121 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" }; 7122 Fields[Count++] = { LongTy, "length" }; 7123 } else { 7124 Fields[Count++] = { getUIntPtrType(), "_cfisa" }; 7125 Fields[Count++] = { getUIntPtrType(), "_swift_rc" }; 7126 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" }; 7127 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" }; 7128 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 || 7129 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2) 7130 Fields[Count++] = { IntTy, "_ptr" }; 7131 else 7132 Fields[Count++] = { getUIntPtrType(), "_ptr" }; 7133 } 7134 7135 // Create fields 7136 for (unsigned i = 0; i < Count; ++i) { 7137 FieldDecl *Field = 7138 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(), 7139 SourceLocation(), &Idents.get(Fields[i].Name), 7140 Fields[i].Type, /*TInfo=*/nullptr, 7141 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); 7142 Field->setAccess(AS_public); 7143 CFConstantStringTagDecl->addDecl(Field); 7144 } 7145 7146 CFConstantStringTagDecl->completeDefinition(); 7147 // This type is designed to be compatible with NSConstantString, but cannot 7148 // use the same name, since NSConstantString is an interface. 7149 auto tagType = getTagDeclType(CFConstantStringTagDecl); 7150 CFConstantStringTypeDecl = 7151 buildImplicitTypedef(tagType, "__NSConstantString"); 7152 7153 return CFConstantStringTypeDecl; 7154 } 7155 7156 RecordDecl *ASTContext::getCFConstantStringTagDecl() const { 7157 if (!CFConstantStringTagDecl) 7158 getCFConstantStringDecl(); // Build the tag and the typedef. 7159 return CFConstantStringTagDecl; 7160 } 7161 7162 // getCFConstantStringType - Return the type used for constant CFStrings. 7163 QualType ASTContext::getCFConstantStringType() const { 7164 return getTypedefType(getCFConstantStringDecl()); 7165 } 7166 7167 QualType ASTContext::getObjCSuperType() const { 7168 if (ObjCSuperType.isNull()) { 7169 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super"); 7170 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl); 7171 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl); 7172 } 7173 return ObjCSuperType; 7174 } 7175 7176 void ASTContext::setCFConstantStringType(QualType T) { 7177 const auto *TD = T->castAs<TypedefType>(); 7178 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl()); 7179 const auto *TagType = 7180 CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>(); 7181 CFConstantStringTagDecl = TagType->getDecl(); 7182 } 7183 7184 QualType ASTContext::getBlockDescriptorType() const { 7185 if (BlockDescriptorType) 7186 return getTagDeclType(BlockDescriptorType); 7187 7188 RecordDecl *RD; 7189 // FIXME: Needs the FlagAppleBlock bit. 7190 RD = buildImplicitRecord("__block_descriptor"); 7191 RD->startDefinition(); 7192 7193 QualType FieldTypes[] = { 7194 UnsignedLongTy, 7195 UnsignedLongTy, 7196 }; 7197 7198 static const char *const FieldNames[] = { 7199 "reserved", 7200 "Size" 7201 }; 7202 7203 for (size_t i = 0; i < 2; ++i) { 7204 FieldDecl *Field = FieldDecl::Create( 7205 *this, RD, SourceLocation(), SourceLocation(), 7206 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, 7207 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); 7208 Field->setAccess(AS_public); 7209 RD->addDecl(Field); 7210 } 7211 7212 RD->completeDefinition(); 7213 7214 BlockDescriptorType = RD; 7215 7216 return getTagDeclType(BlockDescriptorType); 7217 } 7218 7219 QualType ASTContext::getBlockDescriptorExtendedType() const { 7220 if (BlockDescriptorExtendedType) 7221 return getTagDeclType(BlockDescriptorExtendedType); 7222 7223 RecordDecl *RD; 7224 // FIXME: Needs the FlagAppleBlock bit. 7225 RD = buildImplicitRecord("__block_descriptor_withcopydispose"); 7226 RD->startDefinition(); 7227 7228 QualType FieldTypes[] = { 7229 UnsignedLongTy, 7230 UnsignedLongTy, 7231 getPointerType(VoidPtrTy), 7232 getPointerType(VoidPtrTy) 7233 }; 7234 7235 static const char *const FieldNames[] = { 7236 "reserved", 7237 "Size", 7238 "CopyFuncPtr", 7239 "DestroyFuncPtr" 7240 }; 7241 7242 for (size_t i = 0; i < 4; ++i) { 7243 FieldDecl *Field = FieldDecl::Create( 7244 *this, RD, SourceLocation(), SourceLocation(), 7245 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, 7246 /*BitWidth=*/nullptr, 7247 /*Mutable=*/false, ICIS_NoInit); 7248 Field->setAccess(AS_public); 7249 RD->addDecl(Field); 7250 } 7251 7252 RD->completeDefinition(); 7253 7254 BlockDescriptorExtendedType = RD; 7255 return getTagDeclType(BlockDescriptorExtendedType); 7256 } 7257 7258 OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const { 7259 const auto *BT = dyn_cast<BuiltinType>(T); 7260 7261 if (!BT) { 7262 if (isa<PipeType>(T)) 7263 return OCLTK_Pipe; 7264 7265 return OCLTK_Default; 7266 } 7267 7268 switch (BT->getKind()) { 7269 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 7270 case BuiltinType::Id: \ 7271 return OCLTK_Image; 7272 #include "clang/Basic/OpenCLImageTypes.def" 7273 7274 case BuiltinType::OCLClkEvent: 7275 return OCLTK_ClkEvent; 7276 7277 case BuiltinType::OCLEvent: 7278 return OCLTK_Event; 7279 7280 case BuiltinType::OCLQueue: 7281 return OCLTK_Queue; 7282 7283 case BuiltinType::OCLReserveID: 7284 return OCLTK_ReserveID; 7285 7286 case BuiltinType::OCLSampler: 7287 return OCLTK_Sampler; 7288 7289 default: 7290 return OCLTK_Default; 7291 } 7292 } 7293 7294 LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const { 7295 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)); 7296 } 7297 7298 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty" 7299 /// requires copy/dispose. Note that this must match the logic 7300 /// in buildByrefHelpers. 7301 bool ASTContext::BlockRequiresCopying(QualType Ty, 7302 const VarDecl *D) { 7303 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) { 7304 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr(); 7305 if (!copyExpr && record->hasTrivialDestructor()) return false; 7306 7307 return true; 7308 } 7309 7310 // The block needs copy/destroy helpers if Ty is non-trivial to destructively 7311 // move or destroy. 7312 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType()) 7313 return true; 7314 7315 if (!Ty->isObjCRetainableType()) return false; 7316 7317 Qualifiers qs = Ty.getQualifiers(); 7318 7319 // If we have lifetime, that dominates. 7320 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) { 7321 switch (lifetime) { 7322 case Qualifiers::OCL_None: llvm_unreachable("impossible"); 7323 7324 // These are just bits as far as the runtime is concerned. 7325 case Qualifiers::OCL_ExplicitNone: 7326 case Qualifiers::OCL_Autoreleasing: 7327 return false; 7328 7329 // These cases should have been taken care of when checking the type's 7330 // non-triviality. 7331 case Qualifiers::OCL_Weak: 7332 case Qualifiers::OCL_Strong: 7333 llvm_unreachable("impossible"); 7334 } 7335 llvm_unreachable("fell out of lifetime switch!"); 7336 } 7337 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) || 7338 Ty->isObjCObjectPointerType()); 7339 } 7340 7341 bool ASTContext::getByrefLifetime(QualType Ty, 7342 Qualifiers::ObjCLifetime &LifeTime, 7343 bool &HasByrefExtendedLayout) const { 7344 if (!getLangOpts().ObjC || 7345 getLangOpts().getGC() != LangOptions::NonGC) 7346 return false; 7347 7348 HasByrefExtendedLayout = false; 7349 if (Ty->isRecordType()) { 7350 HasByrefExtendedLayout = true; 7351 LifeTime = Qualifiers::OCL_None; 7352 } else if ((LifeTime = Ty.getObjCLifetime())) { 7353 // Honor the ARC qualifiers. 7354 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) { 7355 // The MRR rule. 7356 LifeTime = Qualifiers::OCL_ExplicitNone; 7357 } else { 7358 LifeTime = Qualifiers::OCL_None; 7359 } 7360 return true; 7361 } 7362 7363 CanQualType ASTContext::getNSUIntegerType() const { 7364 assert(Target && "Expected target to be initialized"); 7365 const llvm::Triple &T = Target->getTriple(); 7366 // Windows is LLP64 rather than LP64 7367 if (T.isOSWindows() && T.isArch64Bit()) 7368 return UnsignedLongLongTy; 7369 return UnsignedLongTy; 7370 } 7371 7372 CanQualType ASTContext::getNSIntegerType() const { 7373 assert(Target && "Expected target to be initialized"); 7374 const llvm::Triple &T = Target->getTriple(); 7375 // Windows is LLP64 rather than LP64 7376 if (T.isOSWindows() && T.isArch64Bit()) 7377 return LongLongTy; 7378 return LongTy; 7379 } 7380 7381 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() { 7382 if (!ObjCInstanceTypeDecl) 7383 ObjCInstanceTypeDecl = 7384 buildImplicitTypedef(getObjCIdType(), "instancetype"); 7385 return ObjCInstanceTypeDecl; 7386 } 7387 7388 // This returns true if a type has been typedefed to BOOL: 7389 // typedef <type> BOOL; 7390 static bool isTypeTypedefedAsBOOL(QualType T) { 7391 if (const auto *TT = dyn_cast<TypedefType>(T)) 7392 if (IdentifierInfo *II = TT->getDecl()->getIdentifier()) 7393 return II->isStr("BOOL"); 7394 7395 return false; 7396 } 7397 7398 /// getObjCEncodingTypeSize returns size of type for objective-c encoding 7399 /// purpose. 7400 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const { 7401 if (!type->isIncompleteArrayType() && type->isIncompleteType()) 7402 return CharUnits::Zero(); 7403 7404 CharUnits sz = getTypeSizeInChars(type); 7405 7406 // Make all integer and enum types at least as large as an int 7407 if (sz.isPositive() && type->isIntegralOrEnumerationType()) 7408 sz = std::max(sz, getTypeSizeInChars(IntTy)); 7409 // Treat arrays as pointers, since that's how they're passed in. 7410 else if (type->isArrayType()) 7411 sz = getTypeSizeInChars(VoidPtrTy); 7412 return sz; 7413 } 7414 7415 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const { 7416 return getTargetInfo().getCXXABI().isMicrosoft() && 7417 VD->isStaticDataMember() && 7418 VD->getType()->isIntegralOrEnumerationType() && 7419 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit(); 7420 } 7421 7422 ASTContext::InlineVariableDefinitionKind 7423 ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const { 7424 if (!VD->isInline()) 7425 return InlineVariableDefinitionKind::None; 7426 7427 // In almost all cases, it's a weak definition. 7428 auto *First = VD->getFirstDecl(); 7429 if (First->isInlineSpecified() || !First->isStaticDataMember()) 7430 return InlineVariableDefinitionKind::Weak; 7431 7432 // If there's a file-context declaration in this translation unit, it's a 7433 // non-discardable definition. 7434 for (auto *D : VD->redecls()) 7435 if (D->getLexicalDeclContext()->isFileContext() && 7436 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr())) 7437 return InlineVariableDefinitionKind::Strong; 7438 7439 // If we've not seen one yet, we don't know. 7440 return InlineVariableDefinitionKind::WeakUnknown; 7441 } 7442 7443 static std::string charUnitsToString(const CharUnits &CU) { 7444 return llvm::itostr(CU.getQuantity()); 7445 } 7446 7447 /// getObjCEncodingForBlock - Return the encoded type for this block 7448 /// declaration. 7449 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const { 7450 std::string S; 7451 7452 const BlockDecl *Decl = Expr->getBlockDecl(); 7453 QualType BlockTy = 7454 Expr->getType()->castAs<BlockPointerType>()->getPointeeType(); 7455 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType(); 7456 // Encode result type. 7457 if (getLangOpts().EncodeExtendedBlockSig) 7458 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, BlockReturnTy, S, 7459 true /*Extended*/); 7460 else 7461 getObjCEncodingForType(BlockReturnTy, S); 7462 // Compute size of all parameters. 7463 // Start with computing size of a pointer in number of bytes. 7464 // FIXME: There might(should) be a better way of doing this computation! 7465 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 7466 CharUnits ParmOffset = PtrSize; 7467 for (auto PI : Decl->parameters()) { 7468 QualType PType = PI->getType(); 7469 CharUnits sz = getObjCEncodingTypeSize(PType); 7470 if (sz.isZero()) 7471 continue; 7472 assert(sz.isPositive() && "BlockExpr - Incomplete param type"); 7473 ParmOffset += sz; 7474 } 7475 // Size of the argument frame 7476 S += charUnitsToString(ParmOffset); 7477 // Block pointer and offset. 7478 S += "@?0"; 7479 7480 // Argument types. 7481 ParmOffset = PtrSize; 7482 for (auto PVDecl : Decl->parameters()) { 7483 QualType PType = PVDecl->getOriginalType(); 7484 if (const auto *AT = 7485 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 7486 // Use array's original type only if it has known number of 7487 // elements. 7488 if (!isa<ConstantArrayType>(AT)) 7489 PType = PVDecl->getType(); 7490 } else if (PType->isFunctionType()) 7491 PType = PVDecl->getType(); 7492 if (getLangOpts().EncodeExtendedBlockSig) 7493 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType, 7494 S, true /*Extended*/); 7495 else 7496 getObjCEncodingForType(PType, S); 7497 S += charUnitsToString(ParmOffset); 7498 ParmOffset += getObjCEncodingTypeSize(PType); 7499 } 7500 7501 return S; 7502 } 7503 7504 std::string 7505 ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const { 7506 std::string S; 7507 // Encode result type. 7508 getObjCEncodingForType(Decl->getReturnType(), S); 7509 CharUnits ParmOffset; 7510 // Compute size of all parameters. 7511 for (auto PI : Decl->parameters()) { 7512 QualType PType = PI->getType(); 7513 CharUnits sz = getObjCEncodingTypeSize(PType); 7514 if (sz.isZero()) 7515 continue; 7516 7517 assert(sz.isPositive() && 7518 "getObjCEncodingForFunctionDecl - Incomplete param type"); 7519 ParmOffset += sz; 7520 } 7521 S += charUnitsToString(ParmOffset); 7522 ParmOffset = CharUnits::Zero(); 7523 7524 // Argument types. 7525 for (auto PVDecl : Decl->parameters()) { 7526 QualType PType = PVDecl->getOriginalType(); 7527 if (const auto *AT = 7528 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 7529 // Use array's original type only if it has known number of 7530 // elements. 7531 if (!isa<ConstantArrayType>(AT)) 7532 PType = PVDecl->getType(); 7533 } else if (PType->isFunctionType()) 7534 PType = PVDecl->getType(); 7535 getObjCEncodingForType(PType, S); 7536 S += charUnitsToString(ParmOffset); 7537 ParmOffset += getObjCEncodingTypeSize(PType); 7538 } 7539 7540 return S; 7541 } 7542 7543 /// getObjCEncodingForMethodParameter - Return the encoded type for a single 7544 /// method parameter or return type. If Extended, include class names and 7545 /// block object types. 7546 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, 7547 QualType T, std::string& S, 7548 bool Extended) const { 7549 // Encode type qualifier, 'in', 'inout', etc. for the parameter. 7550 getObjCEncodingForTypeQualifier(QT, S); 7551 // Encode parameter type. 7552 ObjCEncOptions Options = ObjCEncOptions() 7553 .setExpandPointedToStructures() 7554 .setExpandStructures() 7555 .setIsOutermostType(); 7556 if (Extended) 7557 Options.setEncodeBlockParameters().setEncodeClassNames(); 7558 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr); 7559 } 7560 7561 /// getObjCEncodingForMethodDecl - Return the encoded type for this method 7562 /// declaration. 7563 std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, 7564 bool Extended) const { 7565 // FIXME: This is not very efficient. 7566 // Encode return type. 7567 std::string S; 7568 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(), 7569 Decl->getReturnType(), S, Extended); 7570 // Compute size of all parameters. 7571 // Start with computing size of a pointer in number of bytes. 7572 // FIXME: There might(should) be a better way of doing this computation! 7573 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 7574 // The first two arguments (self and _cmd) are pointers; account for 7575 // their size. 7576 CharUnits ParmOffset = 2 * PtrSize; 7577 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 7578 E = Decl->sel_param_end(); PI != E; ++PI) { 7579 QualType PType = (*PI)->getType(); 7580 CharUnits sz = getObjCEncodingTypeSize(PType); 7581 if (sz.isZero()) 7582 continue; 7583 7584 assert(sz.isPositive() && 7585 "getObjCEncodingForMethodDecl - Incomplete param type"); 7586 ParmOffset += sz; 7587 } 7588 S += charUnitsToString(ParmOffset); 7589 S += "@0:"; 7590 S += charUnitsToString(PtrSize); 7591 7592 // Argument types. 7593 ParmOffset = 2 * PtrSize; 7594 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 7595 E = Decl->sel_param_end(); PI != E; ++PI) { 7596 const ParmVarDecl *PVDecl = *PI; 7597 QualType PType = PVDecl->getOriginalType(); 7598 if (const auto *AT = 7599 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 7600 // Use array's original type only if it has known number of 7601 // elements. 7602 if (!isa<ConstantArrayType>(AT)) 7603 PType = PVDecl->getType(); 7604 } else if (PType->isFunctionType()) 7605 PType = PVDecl->getType(); 7606 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(), 7607 PType, S, Extended); 7608 S += charUnitsToString(ParmOffset); 7609 ParmOffset += getObjCEncodingTypeSize(PType); 7610 } 7611 7612 return S; 7613 } 7614 7615 ObjCPropertyImplDecl * 7616 ASTContext::getObjCPropertyImplDeclForPropertyDecl( 7617 const ObjCPropertyDecl *PD, 7618 const Decl *Container) const { 7619 if (!Container) 7620 return nullptr; 7621 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) { 7622 for (auto *PID : CID->property_impls()) 7623 if (PID->getPropertyDecl() == PD) 7624 return PID; 7625 } else { 7626 const auto *OID = cast<ObjCImplementationDecl>(Container); 7627 for (auto *PID : OID->property_impls()) 7628 if (PID->getPropertyDecl() == PD) 7629 return PID; 7630 } 7631 return nullptr; 7632 } 7633 7634 /// getObjCEncodingForPropertyDecl - Return the encoded type for this 7635 /// property declaration. If non-NULL, Container must be either an 7636 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be 7637 /// NULL when getting encodings for protocol properties. 7638 /// Property attributes are stored as a comma-delimited C string. The simple 7639 /// attributes readonly and bycopy are encoded as single characters. The 7640 /// parametrized attributes, getter=name, setter=name, and ivar=name, are 7641 /// encoded as single characters, followed by an identifier. Property types 7642 /// are also encoded as a parametrized attribute. The characters used to encode 7643 /// these attributes are defined by the following enumeration: 7644 /// @code 7645 /// enum PropertyAttributes { 7646 /// kPropertyReadOnly = 'R', // property is read-only. 7647 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned 7648 /// kPropertyByref = '&', // property is a reference to the value last assigned 7649 /// kPropertyDynamic = 'D', // property is dynamic 7650 /// kPropertyGetter = 'G', // followed by getter selector name 7651 /// kPropertySetter = 'S', // followed by setter selector name 7652 /// kPropertyInstanceVariable = 'V' // followed by instance variable name 7653 /// kPropertyType = 'T' // followed by old-style type encoding. 7654 /// kPropertyWeak = 'W' // 'weak' property 7655 /// kPropertyStrong = 'P' // property GC'able 7656 /// kPropertyNonAtomic = 'N' // property non-atomic 7657 /// }; 7658 /// @endcode 7659 std::string 7660 ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, 7661 const Decl *Container) const { 7662 // Collect information from the property implementation decl(s). 7663 bool Dynamic = false; 7664 ObjCPropertyImplDecl *SynthesizePID = nullptr; 7665 7666 if (ObjCPropertyImplDecl *PropertyImpDecl = 7667 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) { 7668 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) 7669 Dynamic = true; 7670 else 7671 SynthesizePID = PropertyImpDecl; 7672 } 7673 7674 // FIXME: This is not very efficient. 7675 std::string S = "T"; 7676 7677 // Encode result type. 7678 // GCC has some special rules regarding encoding of properties which 7679 // closely resembles encoding of ivars. 7680 getObjCEncodingForPropertyType(PD->getType(), S); 7681 7682 if (PD->isReadOnly()) { 7683 S += ",R"; 7684 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy) 7685 S += ",C"; 7686 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain) 7687 S += ",&"; 7688 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak) 7689 S += ",W"; 7690 } else { 7691 switch (PD->getSetterKind()) { 7692 case ObjCPropertyDecl::Assign: break; 7693 case ObjCPropertyDecl::Copy: S += ",C"; break; 7694 case ObjCPropertyDecl::Retain: S += ",&"; break; 7695 case ObjCPropertyDecl::Weak: S += ",W"; break; 7696 } 7697 } 7698 7699 // It really isn't clear at all what this means, since properties 7700 // are "dynamic by default". 7701 if (Dynamic) 7702 S += ",D"; 7703 7704 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_nonatomic) 7705 S += ",N"; 7706 7707 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) { 7708 S += ",G"; 7709 S += PD->getGetterName().getAsString(); 7710 } 7711 7712 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) { 7713 S += ",S"; 7714 S += PD->getSetterName().getAsString(); 7715 } 7716 7717 if (SynthesizePID) { 7718 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl(); 7719 S += ",V"; 7720 S += OID->getNameAsString(); 7721 } 7722 7723 // FIXME: OBJCGC: weak & strong 7724 return S; 7725 } 7726 7727 /// getLegacyIntegralTypeEncoding - 7728 /// Another legacy compatibility encoding: 32-bit longs are encoded as 7729 /// 'l' or 'L' , but not always. For typedefs, we need to use 7730 /// 'i' or 'I' instead if encoding a struct field, or a pointer! 7731 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const { 7732 if (isa<TypedefType>(PointeeTy.getTypePtr())) { 7733 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) { 7734 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32) 7735 PointeeTy = UnsignedIntTy; 7736 else 7737 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32) 7738 PointeeTy = IntTy; 7739 } 7740 } 7741 } 7742 7743 void ASTContext::getObjCEncodingForType(QualType T, std::string& S, 7744 const FieldDecl *Field, 7745 QualType *NotEncodedT) const { 7746 // We follow the behavior of gcc, expanding structures which are 7747 // directly pointed to, and expanding embedded structures. Note that 7748 // these rules are sufficient to prevent recursive encoding of the 7749 // same type. 7750 getObjCEncodingForTypeImpl(T, S, 7751 ObjCEncOptions() 7752 .setExpandPointedToStructures() 7753 .setExpandStructures() 7754 .setIsOutermostType(), 7755 Field, NotEncodedT); 7756 } 7757 7758 void ASTContext::getObjCEncodingForPropertyType(QualType T, 7759 std::string& S) const { 7760 // Encode result type. 7761 // GCC has some special rules regarding encoding of properties which 7762 // closely resembles encoding of ivars. 7763 getObjCEncodingForTypeImpl(T, S, 7764 ObjCEncOptions() 7765 .setExpandPointedToStructures() 7766 .setExpandStructures() 7767 .setIsOutermostType() 7768 .setEncodingProperty(), 7769 /*Field=*/nullptr); 7770 } 7771 7772 static char getObjCEncodingForPrimitiveType(const ASTContext *C, 7773 const BuiltinType *BT) { 7774 BuiltinType::Kind kind = BT->getKind(); 7775 switch (kind) { 7776 case BuiltinType::Void: return 'v'; 7777 case BuiltinType::Bool: return 'B'; 7778 case BuiltinType::Char8: 7779 case BuiltinType::Char_U: 7780 case BuiltinType::UChar: return 'C'; 7781 case BuiltinType::Char16: 7782 case BuiltinType::UShort: return 'S'; 7783 case BuiltinType::Char32: 7784 case BuiltinType::UInt: return 'I'; 7785 case BuiltinType::ULong: 7786 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q'; 7787 case BuiltinType::UInt128: return 'T'; 7788 case BuiltinType::ULongLong: return 'Q'; 7789 case BuiltinType::Char_S: 7790 case BuiltinType::SChar: return 'c'; 7791 case BuiltinType::Short: return 's'; 7792 case BuiltinType::WChar_S: 7793 case BuiltinType::WChar_U: 7794 case BuiltinType::Int: return 'i'; 7795 case BuiltinType::Long: 7796 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q'; 7797 case BuiltinType::LongLong: return 'q'; 7798 case BuiltinType::Int128: return 't'; 7799 case BuiltinType::Float: return 'f'; 7800 case BuiltinType::Double: return 'd'; 7801 case BuiltinType::LongDouble: return 'D'; 7802 case BuiltinType::NullPtr: return '*'; // like char* 7803 7804 case BuiltinType::BFloat16: 7805 case BuiltinType::Float16: 7806 case BuiltinType::Float128: 7807 case BuiltinType::Ibm128: 7808 case BuiltinType::Half: 7809 case BuiltinType::ShortAccum: 7810 case BuiltinType::Accum: 7811 case BuiltinType::LongAccum: 7812 case BuiltinType::UShortAccum: 7813 case BuiltinType::UAccum: 7814 case BuiltinType::ULongAccum: 7815 case BuiltinType::ShortFract: 7816 case BuiltinType::Fract: 7817 case BuiltinType::LongFract: 7818 case BuiltinType::UShortFract: 7819 case BuiltinType::UFract: 7820 case BuiltinType::ULongFract: 7821 case BuiltinType::SatShortAccum: 7822 case BuiltinType::SatAccum: 7823 case BuiltinType::SatLongAccum: 7824 case BuiltinType::SatUShortAccum: 7825 case BuiltinType::SatUAccum: 7826 case BuiltinType::SatULongAccum: 7827 case BuiltinType::SatShortFract: 7828 case BuiltinType::SatFract: 7829 case BuiltinType::SatLongFract: 7830 case BuiltinType::SatUShortFract: 7831 case BuiltinType::SatUFract: 7832 case BuiltinType::SatULongFract: 7833 // FIXME: potentially need @encodes for these! 7834 return ' '; 7835 7836 #define SVE_TYPE(Name, Id, SingletonId) \ 7837 case BuiltinType::Id: 7838 #include "clang/Basic/AArch64SVEACLETypes.def" 7839 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 7840 #include "clang/Basic/RISCVVTypes.def" 7841 { 7842 DiagnosticsEngine &Diags = C->getDiagnostics(); 7843 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 7844 "cannot yet @encode type %0"); 7845 Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy()); 7846 return ' '; 7847 } 7848 7849 case BuiltinType::ObjCId: 7850 case BuiltinType::ObjCClass: 7851 case BuiltinType::ObjCSel: 7852 llvm_unreachable("@encoding ObjC primitive type"); 7853 7854 // OpenCL and placeholder types don't need @encodings. 7855 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 7856 case BuiltinType::Id: 7857 #include "clang/Basic/OpenCLImageTypes.def" 7858 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 7859 case BuiltinType::Id: 7860 #include "clang/Basic/OpenCLExtensionTypes.def" 7861 case BuiltinType::OCLEvent: 7862 case BuiltinType::OCLClkEvent: 7863 case BuiltinType::OCLQueue: 7864 case BuiltinType::OCLReserveID: 7865 case BuiltinType::OCLSampler: 7866 case BuiltinType::Dependent: 7867 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 7868 case BuiltinType::Id: 7869 #include "clang/Basic/PPCTypes.def" 7870 #define BUILTIN_TYPE(KIND, ID) 7871 #define PLACEHOLDER_TYPE(KIND, ID) \ 7872 case BuiltinType::KIND: 7873 #include "clang/AST/BuiltinTypes.def" 7874 llvm_unreachable("invalid builtin type for @encode"); 7875 } 7876 llvm_unreachable("invalid BuiltinType::Kind value"); 7877 } 7878 7879 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) { 7880 EnumDecl *Enum = ET->getDecl(); 7881 7882 // The encoding of an non-fixed enum type is always 'i', regardless of size. 7883 if (!Enum->isFixed()) 7884 return 'i'; 7885 7886 // The encoding of a fixed enum type matches its fixed underlying type. 7887 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>(); 7888 return getObjCEncodingForPrimitiveType(C, BT); 7889 } 7890 7891 static void EncodeBitField(const ASTContext *Ctx, std::string& S, 7892 QualType T, const FieldDecl *FD) { 7893 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl"); 7894 S += 'b'; 7895 // The NeXT runtime encodes bit fields as b followed by the number of bits. 7896 // The GNU runtime requires more information; bitfields are encoded as b, 7897 // then the offset (in bits) of the first element, then the type of the 7898 // bitfield, then the size in bits. For example, in this structure: 7899 // 7900 // struct 7901 // { 7902 // int integer; 7903 // int flags:2; 7904 // }; 7905 // On a 32-bit system, the encoding for flags would be b2 for the NeXT 7906 // runtime, but b32i2 for the GNU runtime. The reason for this extra 7907 // information is not especially sensible, but we're stuck with it for 7908 // compatibility with GCC, although providing it breaks anything that 7909 // actually uses runtime introspection and wants to work on both runtimes... 7910 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) { 7911 uint64_t Offset; 7912 7913 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) { 7914 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr, 7915 IVD); 7916 } else { 7917 const RecordDecl *RD = FD->getParent(); 7918 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD); 7919 Offset = RL.getFieldOffset(FD->getFieldIndex()); 7920 } 7921 7922 S += llvm::utostr(Offset); 7923 7924 if (const auto *ET = T->getAs<EnumType>()) 7925 S += ObjCEncodingForEnumType(Ctx, ET); 7926 else { 7927 const auto *BT = T->castAs<BuiltinType>(); 7928 S += getObjCEncodingForPrimitiveType(Ctx, BT); 7929 } 7930 } 7931 S += llvm::utostr(FD->getBitWidthValue(*Ctx)); 7932 } 7933 7934 // Helper function for determining whether the encoded type string would include 7935 // a template specialization type. 7936 static bool hasTemplateSpecializationInEncodedString(const Type *T, 7937 bool VisitBasesAndFields) { 7938 T = T->getBaseElementTypeUnsafe(); 7939 7940 if (auto *PT = T->getAs<PointerType>()) 7941 return hasTemplateSpecializationInEncodedString( 7942 PT->getPointeeType().getTypePtr(), false); 7943 7944 auto *CXXRD = T->getAsCXXRecordDecl(); 7945 7946 if (!CXXRD) 7947 return false; 7948 7949 if (isa<ClassTemplateSpecializationDecl>(CXXRD)) 7950 return true; 7951 7952 if (!CXXRD->hasDefinition() || !VisitBasesAndFields) 7953 return false; 7954 7955 for (auto B : CXXRD->bases()) 7956 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(), 7957 true)) 7958 return true; 7959 7960 for (auto *FD : CXXRD->fields()) 7961 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(), 7962 true)) 7963 return true; 7964 7965 return false; 7966 } 7967 7968 // FIXME: Use SmallString for accumulating string. 7969 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S, 7970 const ObjCEncOptions Options, 7971 const FieldDecl *FD, 7972 QualType *NotEncodedT) const { 7973 CanQualType CT = getCanonicalType(T); 7974 switch (CT->getTypeClass()) { 7975 case Type::Builtin: 7976 case Type::Enum: 7977 if (FD && FD->isBitField()) 7978 return EncodeBitField(this, S, T, FD); 7979 if (const auto *BT = dyn_cast<BuiltinType>(CT)) 7980 S += getObjCEncodingForPrimitiveType(this, BT); 7981 else 7982 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT)); 7983 return; 7984 7985 case Type::Complex: 7986 S += 'j'; 7987 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S, 7988 ObjCEncOptions(), 7989 /*Field=*/nullptr); 7990 return; 7991 7992 case Type::Atomic: 7993 S += 'A'; 7994 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S, 7995 ObjCEncOptions(), 7996 /*Field=*/nullptr); 7997 return; 7998 7999 // encoding for pointer or reference types. 8000 case Type::Pointer: 8001 case Type::LValueReference: 8002 case Type::RValueReference: { 8003 QualType PointeeTy; 8004 if (isa<PointerType>(CT)) { 8005 const auto *PT = T->castAs<PointerType>(); 8006 if (PT->isObjCSelType()) { 8007 S += ':'; 8008 return; 8009 } 8010 PointeeTy = PT->getPointeeType(); 8011 } else { 8012 PointeeTy = T->castAs<ReferenceType>()->getPointeeType(); 8013 } 8014 8015 bool isReadOnly = false; 8016 // For historical/compatibility reasons, the read-only qualifier of the 8017 // pointee gets emitted _before_ the '^'. The read-only qualifier of 8018 // the pointer itself gets ignored, _unless_ we are looking at a typedef! 8019 // Also, do not emit the 'r' for anything but the outermost type! 8020 if (isa<TypedefType>(T.getTypePtr())) { 8021 if (Options.IsOutermostType() && T.isConstQualified()) { 8022 isReadOnly = true; 8023 S += 'r'; 8024 } 8025 } else if (Options.IsOutermostType()) { 8026 QualType P = PointeeTy; 8027 while (auto PT = P->getAs<PointerType>()) 8028 P = PT->getPointeeType(); 8029 if (P.isConstQualified()) { 8030 isReadOnly = true; 8031 S += 'r'; 8032 } 8033 } 8034 if (isReadOnly) { 8035 // Another legacy compatibility encoding. Some ObjC qualifier and type 8036 // combinations need to be rearranged. 8037 // Rewrite "in const" from "nr" to "rn" 8038 if (StringRef(S).endswith("nr")) 8039 S.replace(S.end()-2, S.end(), "rn"); 8040 } 8041 8042 if (PointeeTy->isCharType()) { 8043 // char pointer types should be encoded as '*' unless it is a 8044 // type that has been typedef'd to 'BOOL'. 8045 if (!isTypeTypedefedAsBOOL(PointeeTy)) { 8046 S += '*'; 8047 return; 8048 } 8049 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) { 8050 // GCC binary compat: Need to convert "struct objc_class *" to "#". 8051 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) { 8052 S += '#'; 8053 return; 8054 } 8055 // GCC binary compat: Need to convert "struct objc_object *" to "@". 8056 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) { 8057 S += '@'; 8058 return; 8059 } 8060 // If the encoded string for the class includes template names, just emit 8061 // "^v" for pointers to the class. 8062 if (getLangOpts().CPlusPlus && 8063 (!getLangOpts().EncodeCXXClassTemplateSpec && 8064 hasTemplateSpecializationInEncodedString( 8065 RTy, Options.ExpandPointedToStructures()))) { 8066 S += "^v"; 8067 return; 8068 } 8069 // fall through... 8070 } 8071 S += '^'; 8072 getLegacyIntegralTypeEncoding(PointeeTy); 8073 8074 ObjCEncOptions NewOptions; 8075 if (Options.ExpandPointedToStructures()) 8076 NewOptions.setExpandStructures(); 8077 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions, 8078 /*Field=*/nullptr, NotEncodedT); 8079 return; 8080 } 8081 8082 case Type::ConstantArray: 8083 case Type::IncompleteArray: 8084 case Type::VariableArray: { 8085 const auto *AT = cast<ArrayType>(CT); 8086 8087 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) { 8088 // Incomplete arrays are encoded as a pointer to the array element. 8089 S += '^'; 8090 8091 getObjCEncodingForTypeImpl( 8092 AT->getElementType(), S, 8093 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD); 8094 } else { 8095 S += '['; 8096 8097 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) 8098 S += llvm::utostr(CAT->getSize().getZExtValue()); 8099 else { 8100 //Variable length arrays are encoded as a regular array with 0 elements. 8101 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) && 8102 "Unknown array type!"); 8103 S += '0'; 8104 } 8105 8106 getObjCEncodingForTypeImpl( 8107 AT->getElementType(), S, 8108 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD, 8109 NotEncodedT); 8110 S += ']'; 8111 } 8112 return; 8113 } 8114 8115 case Type::FunctionNoProto: 8116 case Type::FunctionProto: 8117 S += '?'; 8118 return; 8119 8120 case Type::Record: { 8121 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl(); 8122 S += RDecl->isUnion() ? '(' : '{'; 8123 // Anonymous structures print as '?' 8124 if (const IdentifierInfo *II = RDecl->getIdentifier()) { 8125 S += II->getName(); 8126 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) { 8127 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 8128 llvm::raw_string_ostream OS(S); 8129 printTemplateArgumentList(OS, TemplateArgs.asArray(), 8130 getPrintingPolicy()); 8131 } 8132 } else { 8133 S += '?'; 8134 } 8135 if (Options.ExpandStructures()) { 8136 S += '='; 8137 if (!RDecl->isUnion()) { 8138 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT); 8139 } else { 8140 for (const auto *Field : RDecl->fields()) { 8141 if (FD) { 8142 S += '"'; 8143 S += Field->getNameAsString(); 8144 S += '"'; 8145 } 8146 8147 // Special case bit-fields. 8148 if (Field->isBitField()) { 8149 getObjCEncodingForTypeImpl(Field->getType(), S, 8150 ObjCEncOptions().setExpandStructures(), 8151 Field); 8152 } else { 8153 QualType qt = Field->getType(); 8154 getLegacyIntegralTypeEncoding(qt); 8155 getObjCEncodingForTypeImpl( 8156 qt, S, 8157 ObjCEncOptions().setExpandStructures().setIsStructField(), FD, 8158 NotEncodedT); 8159 } 8160 } 8161 } 8162 } 8163 S += RDecl->isUnion() ? ')' : '}'; 8164 return; 8165 } 8166 8167 case Type::BlockPointer: { 8168 const auto *BT = T->castAs<BlockPointerType>(); 8169 S += "@?"; // Unlike a pointer-to-function, which is "^?". 8170 if (Options.EncodeBlockParameters()) { 8171 const auto *FT = BT->getPointeeType()->castAs<FunctionType>(); 8172 8173 S += '<'; 8174 // Block return type 8175 getObjCEncodingForTypeImpl(FT->getReturnType(), S, 8176 Options.forComponentType(), FD, NotEncodedT); 8177 // Block self 8178 S += "@?"; 8179 // Block parameters 8180 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) { 8181 for (const auto &I : FPT->param_types()) 8182 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD, 8183 NotEncodedT); 8184 } 8185 S += '>'; 8186 } 8187 return; 8188 } 8189 8190 case Type::ObjCObject: { 8191 // hack to match legacy encoding of *id and *Class 8192 QualType Ty = getObjCObjectPointerType(CT); 8193 if (Ty->isObjCIdType()) { 8194 S += "{objc_object=}"; 8195 return; 8196 } 8197 else if (Ty->isObjCClassType()) { 8198 S += "{objc_class=}"; 8199 return; 8200 } 8201 // TODO: Double check to make sure this intentionally falls through. 8202 LLVM_FALLTHROUGH; 8203 } 8204 8205 case Type::ObjCInterface: { 8206 // Ignore protocol qualifiers when mangling at this level. 8207 // @encode(class_name) 8208 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface(); 8209 S += '{'; 8210 S += OI->getObjCRuntimeNameAsString(); 8211 if (Options.ExpandStructures()) { 8212 S += '='; 8213 SmallVector<const ObjCIvarDecl*, 32> Ivars; 8214 DeepCollectObjCIvars(OI, true, Ivars); 8215 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) { 8216 const FieldDecl *Field = Ivars[i]; 8217 if (Field->isBitField()) 8218 getObjCEncodingForTypeImpl(Field->getType(), S, 8219 ObjCEncOptions().setExpandStructures(), 8220 Field); 8221 else 8222 getObjCEncodingForTypeImpl(Field->getType(), S, 8223 ObjCEncOptions().setExpandStructures(), FD, 8224 NotEncodedT); 8225 } 8226 } 8227 S += '}'; 8228 return; 8229 } 8230 8231 case Type::ObjCObjectPointer: { 8232 const auto *OPT = T->castAs<ObjCObjectPointerType>(); 8233 if (OPT->isObjCIdType()) { 8234 S += '@'; 8235 return; 8236 } 8237 8238 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) { 8239 // FIXME: Consider if we need to output qualifiers for 'Class<p>'. 8240 // Since this is a binary compatibility issue, need to consult with 8241 // runtime folks. Fortunately, this is a *very* obscure construct. 8242 S += '#'; 8243 return; 8244 } 8245 8246 if (OPT->isObjCQualifiedIdType()) { 8247 getObjCEncodingForTypeImpl( 8248 getObjCIdType(), S, 8249 Options.keepingOnly(ObjCEncOptions() 8250 .setExpandPointedToStructures() 8251 .setExpandStructures()), 8252 FD); 8253 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) { 8254 // Note that we do extended encoding of protocol qualifier list 8255 // Only when doing ivar or property encoding. 8256 S += '"'; 8257 for (const auto *I : OPT->quals()) { 8258 S += '<'; 8259 S += I->getObjCRuntimeNameAsString(); 8260 S += '>'; 8261 } 8262 S += '"'; 8263 } 8264 return; 8265 } 8266 8267 S += '@'; 8268 if (OPT->getInterfaceDecl() && 8269 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) { 8270 S += '"'; 8271 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString(); 8272 for (const auto *I : OPT->quals()) { 8273 S += '<'; 8274 S += I->getObjCRuntimeNameAsString(); 8275 S += '>'; 8276 } 8277 S += '"'; 8278 } 8279 return; 8280 } 8281 8282 // gcc just blithely ignores member pointers. 8283 // FIXME: we should do better than that. 'M' is available. 8284 case Type::MemberPointer: 8285 // This matches gcc's encoding, even though technically it is insufficient. 8286 //FIXME. We should do a better job than gcc. 8287 case Type::Vector: 8288 case Type::ExtVector: 8289 // Until we have a coherent encoding of these three types, issue warning. 8290 if (NotEncodedT) 8291 *NotEncodedT = T; 8292 return; 8293 8294 case Type::ConstantMatrix: 8295 if (NotEncodedT) 8296 *NotEncodedT = T; 8297 return; 8298 8299 case Type::BitInt: 8300 if (NotEncodedT) 8301 *NotEncodedT = T; 8302 return; 8303 8304 // We could see an undeduced auto type here during error recovery. 8305 // Just ignore it. 8306 case Type::Auto: 8307 case Type::DeducedTemplateSpecialization: 8308 return; 8309 8310 case Type::Pipe: 8311 #define ABSTRACT_TYPE(KIND, BASE) 8312 #define TYPE(KIND, BASE) 8313 #define DEPENDENT_TYPE(KIND, BASE) \ 8314 case Type::KIND: 8315 #define NON_CANONICAL_TYPE(KIND, BASE) \ 8316 case Type::KIND: 8317 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \ 8318 case Type::KIND: 8319 #include "clang/AST/TypeNodes.inc" 8320 llvm_unreachable("@encode for dependent type!"); 8321 } 8322 llvm_unreachable("bad type kind!"); 8323 } 8324 8325 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl, 8326 std::string &S, 8327 const FieldDecl *FD, 8328 bool includeVBases, 8329 QualType *NotEncodedT) const { 8330 assert(RDecl && "Expected non-null RecordDecl"); 8331 assert(!RDecl->isUnion() && "Should not be called for unions"); 8332 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl()) 8333 return; 8334 8335 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl); 8336 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets; 8337 const ASTRecordLayout &layout = getASTRecordLayout(RDecl); 8338 8339 if (CXXRec) { 8340 for (const auto &BI : CXXRec->bases()) { 8341 if (!BI.isVirtual()) { 8342 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); 8343 if (base->isEmpty()) 8344 continue; 8345 uint64_t offs = toBits(layout.getBaseClassOffset(base)); 8346 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 8347 std::make_pair(offs, base)); 8348 } 8349 } 8350 } 8351 8352 unsigned i = 0; 8353 for (FieldDecl *Field : RDecl->fields()) { 8354 if (!Field->isZeroLengthBitField(*this) && Field->isZeroSize(*this)) 8355 continue; 8356 uint64_t offs = layout.getFieldOffset(i); 8357 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 8358 std::make_pair(offs, Field)); 8359 ++i; 8360 } 8361 8362 if (CXXRec && includeVBases) { 8363 for (const auto &BI : CXXRec->vbases()) { 8364 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); 8365 if (base->isEmpty()) 8366 continue; 8367 uint64_t offs = toBits(layout.getVBaseClassOffset(base)); 8368 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) && 8369 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end()) 8370 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(), 8371 std::make_pair(offs, base)); 8372 } 8373 } 8374 8375 CharUnits size; 8376 if (CXXRec) { 8377 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize(); 8378 } else { 8379 size = layout.getSize(); 8380 } 8381 8382 #ifndef NDEBUG 8383 uint64_t CurOffs = 0; 8384 #endif 8385 std::multimap<uint64_t, NamedDecl *>::iterator 8386 CurLayObj = FieldOrBaseOffsets.begin(); 8387 8388 if (CXXRec && CXXRec->isDynamicClass() && 8389 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) { 8390 if (FD) { 8391 S += "\"_vptr$"; 8392 std::string recname = CXXRec->getNameAsString(); 8393 if (recname.empty()) recname = "?"; 8394 S += recname; 8395 S += '"'; 8396 } 8397 S += "^^?"; 8398 #ifndef NDEBUG 8399 CurOffs += getTypeSize(VoidPtrTy); 8400 #endif 8401 } 8402 8403 if (!RDecl->hasFlexibleArrayMember()) { 8404 // Mark the end of the structure. 8405 uint64_t offs = toBits(size); 8406 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 8407 std::make_pair(offs, nullptr)); 8408 } 8409 8410 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) { 8411 #ifndef NDEBUG 8412 assert(CurOffs <= CurLayObj->first); 8413 if (CurOffs < CurLayObj->first) { 8414 uint64_t padding = CurLayObj->first - CurOffs; 8415 // FIXME: There doesn't seem to be a way to indicate in the encoding that 8416 // packing/alignment of members is different that normal, in which case 8417 // the encoding will be out-of-sync with the real layout. 8418 // If the runtime switches to just consider the size of types without 8419 // taking into account alignment, we could make padding explicit in the 8420 // encoding (e.g. using arrays of chars). The encoding strings would be 8421 // longer then though. 8422 CurOffs += padding; 8423 } 8424 #endif 8425 8426 NamedDecl *dcl = CurLayObj->second; 8427 if (!dcl) 8428 break; // reached end of structure. 8429 8430 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) { 8431 // We expand the bases without their virtual bases since those are going 8432 // in the initial structure. Note that this differs from gcc which 8433 // expands virtual bases each time one is encountered in the hierarchy, 8434 // making the encoding type bigger than it really is. 8435 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false, 8436 NotEncodedT); 8437 assert(!base->isEmpty()); 8438 #ifndef NDEBUG 8439 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize()); 8440 #endif 8441 } else { 8442 const auto *field = cast<FieldDecl>(dcl); 8443 if (FD) { 8444 S += '"'; 8445 S += field->getNameAsString(); 8446 S += '"'; 8447 } 8448 8449 if (field->isBitField()) { 8450 EncodeBitField(this, S, field->getType(), field); 8451 #ifndef NDEBUG 8452 CurOffs += field->getBitWidthValue(*this); 8453 #endif 8454 } else { 8455 QualType qt = field->getType(); 8456 getLegacyIntegralTypeEncoding(qt); 8457 getObjCEncodingForTypeImpl( 8458 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(), 8459 FD, NotEncodedT); 8460 #ifndef NDEBUG 8461 CurOffs += getTypeSize(field->getType()); 8462 #endif 8463 } 8464 } 8465 } 8466 } 8467 8468 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, 8469 std::string& S) const { 8470 if (QT & Decl::OBJC_TQ_In) 8471 S += 'n'; 8472 if (QT & Decl::OBJC_TQ_Inout) 8473 S += 'N'; 8474 if (QT & Decl::OBJC_TQ_Out) 8475 S += 'o'; 8476 if (QT & Decl::OBJC_TQ_Bycopy) 8477 S += 'O'; 8478 if (QT & Decl::OBJC_TQ_Byref) 8479 S += 'R'; 8480 if (QT & Decl::OBJC_TQ_Oneway) 8481 S += 'V'; 8482 } 8483 8484 TypedefDecl *ASTContext::getObjCIdDecl() const { 8485 if (!ObjCIdDecl) { 8486 QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {}); 8487 T = getObjCObjectPointerType(T); 8488 ObjCIdDecl = buildImplicitTypedef(T, "id"); 8489 } 8490 return ObjCIdDecl; 8491 } 8492 8493 TypedefDecl *ASTContext::getObjCSelDecl() const { 8494 if (!ObjCSelDecl) { 8495 QualType T = getPointerType(ObjCBuiltinSelTy); 8496 ObjCSelDecl = buildImplicitTypedef(T, "SEL"); 8497 } 8498 return ObjCSelDecl; 8499 } 8500 8501 TypedefDecl *ASTContext::getObjCClassDecl() const { 8502 if (!ObjCClassDecl) { 8503 QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {}); 8504 T = getObjCObjectPointerType(T); 8505 ObjCClassDecl = buildImplicitTypedef(T, "Class"); 8506 } 8507 return ObjCClassDecl; 8508 } 8509 8510 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const { 8511 if (!ObjCProtocolClassDecl) { 8512 ObjCProtocolClassDecl 8513 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(), 8514 SourceLocation(), 8515 &Idents.get("Protocol"), 8516 /*typeParamList=*/nullptr, 8517 /*PrevDecl=*/nullptr, 8518 SourceLocation(), true); 8519 } 8520 8521 return ObjCProtocolClassDecl; 8522 } 8523 8524 //===----------------------------------------------------------------------===// 8525 // __builtin_va_list Construction Functions 8526 //===----------------------------------------------------------------------===// 8527 8528 static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context, 8529 StringRef Name) { 8530 // typedef char* __builtin[_ms]_va_list; 8531 QualType T = Context->getPointerType(Context->CharTy); 8532 return Context->buildImplicitTypedef(T, Name); 8533 } 8534 8535 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) { 8536 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list"); 8537 } 8538 8539 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) { 8540 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list"); 8541 } 8542 8543 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) { 8544 // typedef void* __builtin_va_list; 8545 QualType T = Context->getPointerType(Context->VoidTy); 8546 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 8547 } 8548 8549 static TypedefDecl * 8550 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) { 8551 // struct __va_list 8552 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list"); 8553 if (Context->getLangOpts().CPlusPlus) { 8554 // namespace std { struct __va_list { 8555 auto *NS = NamespaceDecl::Create( 8556 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(), 8557 /*Inline*/ false, SourceLocation(), SourceLocation(), 8558 &Context->Idents.get("std"), 8559 /*PrevDecl*/ nullptr); 8560 NS->setImplicit(); 8561 VaListTagDecl->setDeclContext(NS); 8562 } 8563 8564 VaListTagDecl->startDefinition(); 8565 8566 const size_t NumFields = 5; 8567 QualType FieldTypes[NumFields]; 8568 const char *FieldNames[NumFields]; 8569 8570 // void *__stack; 8571 FieldTypes[0] = Context->getPointerType(Context->VoidTy); 8572 FieldNames[0] = "__stack"; 8573 8574 // void *__gr_top; 8575 FieldTypes[1] = Context->getPointerType(Context->VoidTy); 8576 FieldNames[1] = "__gr_top"; 8577 8578 // void *__vr_top; 8579 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8580 FieldNames[2] = "__vr_top"; 8581 8582 // int __gr_offs; 8583 FieldTypes[3] = Context->IntTy; 8584 FieldNames[3] = "__gr_offs"; 8585 8586 // int __vr_offs; 8587 FieldTypes[4] = Context->IntTy; 8588 FieldNames[4] = "__vr_offs"; 8589 8590 // Create fields 8591 for (unsigned i = 0; i < NumFields; ++i) { 8592 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8593 VaListTagDecl, 8594 SourceLocation(), 8595 SourceLocation(), 8596 &Context->Idents.get(FieldNames[i]), 8597 FieldTypes[i], /*TInfo=*/nullptr, 8598 /*BitWidth=*/nullptr, 8599 /*Mutable=*/false, 8600 ICIS_NoInit); 8601 Field->setAccess(AS_public); 8602 VaListTagDecl->addDecl(Field); 8603 } 8604 VaListTagDecl->completeDefinition(); 8605 Context->VaListTagDecl = VaListTagDecl; 8606 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8607 8608 // } __builtin_va_list; 8609 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list"); 8610 } 8611 8612 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) { 8613 // typedef struct __va_list_tag { 8614 RecordDecl *VaListTagDecl; 8615 8616 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8617 VaListTagDecl->startDefinition(); 8618 8619 const size_t NumFields = 5; 8620 QualType FieldTypes[NumFields]; 8621 const char *FieldNames[NumFields]; 8622 8623 // unsigned char gpr; 8624 FieldTypes[0] = Context->UnsignedCharTy; 8625 FieldNames[0] = "gpr"; 8626 8627 // unsigned char fpr; 8628 FieldTypes[1] = Context->UnsignedCharTy; 8629 FieldNames[1] = "fpr"; 8630 8631 // unsigned short reserved; 8632 FieldTypes[2] = Context->UnsignedShortTy; 8633 FieldNames[2] = "reserved"; 8634 8635 // void* overflow_arg_area; 8636 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 8637 FieldNames[3] = "overflow_arg_area"; 8638 8639 // void* reg_save_area; 8640 FieldTypes[4] = Context->getPointerType(Context->VoidTy); 8641 FieldNames[4] = "reg_save_area"; 8642 8643 // Create fields 8644 for (unsigned i = 0; i < NumFields; ++i) { 8645 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl, 8646 SourceLocation(), 8647 SourceLocation(), 8648 &Context->Idents.get(FieldNames[i]), 8649 FieldTypes[i], /*TInfo=*/nullptr, 8650 /*BitWidth=*/nullptr, 8651 /*Mutable=*/false, 8652 ICIS_NoInit); 8653 Field->setAccess(AS_public); 8654 VaListTagDecl->addDecl(Field); 8655 } 8656 VaListTagDecl->completeDefinition(); 8657 Context->VaListTagDecl = VaListTagDecl; 8658 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8659 8660 // } __va_list_tag; 8661 TypedefDecl *VaListTagTypedefDecl = 8662 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); 8663 8664 QualType VaListTagTypedefType = 8665 Context->getTypedefType(VaListTagTypedefDecl); 8666 8667 // typedef __va_list_tag __builtin_va_list[1]; 8668 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8669 QualType VaListTagArrayType 8670 = Context->getConstantArrayType(VaListTagTypedefType, 8671 Size, nullptr, ArrayType::Normal, 0); 8672 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8673 } 8674 8675 static TypedefDecl * 8676 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) { 8677 // struct __va_list_tag { 8678 RecordDecl *VaListTagDecl; 8679 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8680 VaListTagDecl->startDefinition(); 8681 8682 const size_t NumFields = 4; 8683 QualType FieldTypes[NumFields]; 8684 const char *FieldNames[NumFields]; 8685 8686 // unsigned gp_offset; 8687 FieldTypes[0] = Context->UnsignedIntTy; 8688 FieldNames[0] = "gp_offset"; 8689 8690 // unsigned fp_offset; 8691 FieldTypes[1] = Context->UnsignedIntTy; 8692 FieldNames[1] = "fp_offset"; 8693 8694 // void* overflow_arg_area; 8695 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8696 FieldNames[2] = "overflow_arg_area"; 8697 8698 // void* reg_save_area; 8699 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 8700 FieldNames[3] = "reg_save_area"; 8701 8702 // Create fields 8703 for (unsigned i = 0; i < NumFields; ++i) { 8704 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8705 VaListTagDecl, 8706 SourceLocation(), 8707 SourceLocation(), 8708 &Context->Idents.get(FieldNames[i]), 8709 FieldTypes[i], /*TInfo=*/nullptr, 8710 /*BitWidth=*/nullptr, 8711 /*Mutable=*/false, 8712 ICIS_NoInit); 8713 Field->setAccess(AS_public); 8714 VaListTagDecl->addDecl(Field); 8715 } 8716 VaListTagDecl->completeDefinition(); 8717 Context->VaListTagDecl = VaListTagDecl; 8718 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8719 8720 // }; 8721 8722 // typedef struct __va_list_tag __builtin_va_list[1]; 8723 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8724 QualType VaListTagArrayType = Context->getConstantArrayType( 8725 VaListTagType, Size, nullptr, ArrayType::Normal, 0); 8726 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8727 } 8728 8729 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) { 8730 // typedef int __builtin_va_list[4]; 8731 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4); 8732 QualType IntArrayType = Context->getConstantArrayType( 8733 Context->IntTy, Size, nullptr, ArrayType::Normal, 0); 8734 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list"); 8735 } 8736 8737 static TypedefDecl * 8738 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) { 8739 // struct __va_list 8740 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list"); 8741 if (Context->getLangOpts().CPlusPlus) { 8742 // namespace std { struct __va_list { 8743 NamespaceDecl *NS; 8744 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context), 8745 Context->getTranslationUnitDecl(), 8746 /*Inline*/false, SourceLocation(), 8747 SourceLocation(), &Context->Idents.get("std"), 8748 /*PrevDecl*/ nullptr); 8749 NS->setImplicit(); 8750 VaListDecl->setDeclContext(NS); 8751 } 8752 8753 VaListDecl->startDefinition(); 8754 8755 // void * __ap; 8756 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8757 VaListDecl, 8758 SourceLocation(), 8759 SourceLocation(), 8760 &Context->Idents.get("__ap"), 8761 Context->getPointerType(Context->VoidTy), 8762 /*TInfo=*/nullptr, 8763 /*BitWidth=*/nullptr, 8764 /*Mutable=*/false, 8765 ICIS_NoInit); 8766 Field->setAccess(AS_public); 8767 VaListDecl->addDecl(Field); 8768 8769 // }; 8770 VaListDecl->completeDefinition(); 8771 Context->VaListTagDecl = VaListDecl; 8772 8773 // typedef struct __va_list __builtin_va_list; 8774 QualType T = Context->getRecordType(VaListDecl); 8775 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 8776 } 8777 8778 static TypedefDecl * 8779 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) { 8780 // struct __va_list_tag { 8781 RecordDecl *VaListTagDecl; 8782 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8783 VaListTagDecl->startDefinition(); 8784 8785 const size_t NumFields = 4; 8786 QualType FieldTypes[NumFields]; 8787 const char *FieldNames[NumFields]; 8788 8789 // long __gpr; 8790 FieldTypes[0] = Context->LongTy; 8791 FieldNames[0] = "__gpr"; 8792 8793 // long __fpr; 8794 FieldTypes[1] = Context->LongTy; 8795 FieldNames[1] = "__fpr"; 8796 8797 // void *__overflow_arg_area; 8798 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8799 FieldNames[2] = "__overflow_arg_area"; 8800 8801 // void *__reg_save_area; 8802 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 8803 FieldNames[3] = "__reg_save_area"; 8804 8805 // Create fields 8806 for (unsigned i = 0; i < NumFields; ++i) { 8807 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8808 VaListTagDecl, 8809 SourceLocation(), 8810 SourceLocation(), 8811 &Context->Idents.get(FieldNames[i]), 8812 FieldTypes[i], /*TInfo=*/nullptr, 8813 /*BitWidth=*/nullptr, 8814 /*Mutable=*/false, 8815 ICIS_NoInit); 8816 Field->setAccess(AS_public); 8817 VaListTagDecl->addDecl(Field); 8818 } 8819 VaListTagDecl->completeDefinition(); 8820 Context->VaListTagDecl = VaListTagDecl; 8821 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8822 8823 // }; 8824 8825 // typedef __va_list_tag __builtin_va_list[1]; 8826 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8827 QualType VaListTagArrayType = Context->getConstantArrayType( 8828 VaListTagType, Size, nullptr, ArrayType::Normal, 0); 8829 8830 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8831 } 8832 8833 static TypedefDecl *CreateHexagonBuiltinVaListDecl(const ASTContext *Context) { 8834 // typedef struct __va_list_tag { 8835 RecordDecl *VaListTagDecl; 8836 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8837 VaListTagDecl->startDefinition(); 8838 8839 const size_t NumFields = 3; 8840 QualType FieldTypes[NumFields]; 8841 const char *FieldNames[NumFields]; 8842 8843 // void *CurrentSavedRegisterArea; 8844 FieldTypes[0] = Context->getPointerType(Context->VoidTy); 8845 FieldNames[0] = "__current_saved_reg_area_pointer"; 8846 8847 // void *SavedRegAreaEnd; 8848 FieldTypes[1] = Context->getPointerType(Context->VoidTy); 8849 FieldNames[1] = "__saved_reg_area_end_pointer"; 8850 8851 // void *OverflowArea; 8852 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8853 FieldNames[2] = "__overflow_area_pointer"; 8854 8855 // Create fields 8856 for (unsigned i = 0; i < NumFields; ++i) { 8857 FieldDecl *Field = FieldDecl::Create( 8858 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(), 8859 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i], 8860 /*TInfo=*/nullptr, 8861 /*BitWidth=*/nullptr, 8862 /*Mutable=*/false, ICIS_NoInit); 8863 Field->setAccess(AS_public); 8864 VaListTagDecl->addDecl(Field); 8865 } 8866 VaListTagDecl->completeDefinition(); 8867 Context->VaListTagDecl = VaListTagDecl; 8868 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8869 8870 // } __va_list_tag; 8871 TypedefDecl *VaListTagTypedefDecl = 8872 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); 8873 8874 QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl); 8875 8876 // typedef __va_list_tag __builtin_va_list[1]; 8877 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8878 QualType VaListTagArrayType = Context->getConstantArrayType( 8879 VaListTagTypedefType, Size, nullptr, ArrayType::Normal, 0); 8880 8881 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8882 } 8883 8884 static TypedefDecl *CreateVaListDecl(const ASTContext *Context, 8885 TargetInfo::BuiltinVaListKind Kind) { 8886 switch (Kind) { 8887 case TargetInfo::CharPtrBuiltinVaList: 8888 return CreateCharPtrBuiltinVaListDecl(Context); 8889 case TargetInfo::VoidPtrBuiltinVaList: 8890 return CreateVoidPtrBuiltinVaListDecl(Context); 8891 case TargetInfo::AArch64ABIBuiltinVaList: 8892 return CreateAArch64ABIBuiltinVaListDecl(Context); 8893 case TargetInfo::PowerABIBuiltinVaList: 8894 return CreatePowerABIBuiltinVaListDecl(Context); 8895 case TargetInfo::X86_64ABIBuiltinVaList: 8896 return CreateX86_64ABIBuiltinVaListDecl(Context); 8897 case TargetInfo::PNaClABIBuiltinVaList: 8898 return CreatePNaClABIBuiltinVaListDecl(Context); 8899 case TargetInfo::AAPCSABIBuiltinVaList: 8900 return CreateAAPCSABIBuiltinVaListDecl(Context); 8901 case TargetInfo::SystemZBuiltinVaList: 8902 return CreateSystemZBuiltinVaListDecl(Context); 8903 case TargetInfo::HexagonBuiltinVaList: 8904 return CreateHexagonBuiltinVaListDecl(Context); 8905 } 8906 8907 llvm_unreachable("Unhandled __builtin_va_list type kind"); 8908 } 8909 8910 TypedefDecl *ASTContext::getBuiltinVaListDecl() const { 8911 if (!BuiltinVaListDecl) { 8912 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind()); 8913 assert(BuiltinVaListDecl->isImplicit()); 8914 } 8915 8916 return BuiltinVaListDecl; 8917 } 8918 8919 Decl *ASTContext::getVaListTagDecl() const { 8920 // Force the creation of VaListTagDecl by building the __builtin_va_list 8921 // declaration. 8922 if (!VaListTagDecl) 8923 (void)getBuiltinVaListDecl(); 8924 8925 return VaListTagDecl; 8926 } 8927 8928 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const { 8929 if (!BuiltinMSVaListDecl) 8930 BuiltinMSVaListDecl = CreateMSVaListDecl(this); 8931 8932 return BuiltinMSVaListDecl; 8933 } 8934 8935 bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const { 8936 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID()); 8937 } 8938 8939 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) { 8940 assert(ObjCConstantStringType.isNull() && 8941 "'NSConstantString' type already set!"); 8942 8943 ObjCConstantStringType = getObjCInterfaceType(Decl); 8944 } 8945 8946 /// Retrieve the template name that corresponds to a non-empty 8947 /// lookup. 8948 TemplateName 8949 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin, 8950 UnresolvedSetIterator End) const { 8951 unsigned size = End - Begin; 8952 assert(size > 1 && "set is not overloaded!"); 8953 8954 void *memory = Allocate(sizeof(OverloadedTemplateStorage) + 8955 size * sizeof(FunctionTemplateDecl*)); 8956 auto *OT = new (memory) OverloadedTemplateStorage(size); 8957 8958 NamedDecl **Storage = OT->getStorage(); 8959 for (UnresolvedSetIterator I = Begin; I != End; ++I) { 8960 NamedDecl *D = *I; 8961 assert(isa<FunctionTemplateDecl>(D) || 8962 isa<UnresolvedUsingValueDecl>(D) || 8963 (isa<UsingShadowDecl>(D) && 8964 isa<FunctionTemplateDecl>(D->getUnderlyingDecl()))); 8965 *Storage++ = D; 8966 } 8967 8968 return TemplateName(OT); 8969 } 8970 8971 /// Retrieve a template name representing an unqualified-id that has been 8972 /// assumed to name a template for ADL purposes. 8973 TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const { 8974 auto *OT = new (*this) AssumedTemplateStorage(Name); 8975 return TemplateName(OT); 8976 } 8977 8978 /// Retrieve the template name that represents a qualified 8979 /// template name such as \c std::vector. 8980 TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, 8981 bool TemplateKeyword, 8982 TemplateName Template) const { 8983 assert(NNS && "Missing nested-name-specifier in qualified template name"); 8984 8985 // FIXME: Canonicalization? 8986 llvm::FoldingSetNodeID ID; 8987 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template); 8988 8989 void *InsertPos = nullptr; 8990 QualifiedTemplateName *QTN = 8991 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 8992 if (!QTN) { 8993 QTN = new (*this, alignof(QualifiedTemplateName)) 8994 QualifiedTemplateName(NNS, TemplateKeyword, Template); 8995 QualifiedTemplateNames.InsertNode(QTN, InsertPos); 8996 } 8997 8998 return TemplateName(QTN); 8999 } 9000 9001 /// Retrieve the template name that represents a dependent 9002 /// template name such as \c MetaFun::template apply. 9003 TemplateName 9004 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 9005 const IdentifierInfo *Name) const { 9006 assert((!NNS || NNS->isDependent()) && 9007 "Nested name specifier must be dependent"); 9008 9009 llvm::FoldingSetNodeID ID; 9010 DependentTemplateName::Profile(ID, NNS, Name); 9011 9012 void *InsertPos = nullptr; 9013 DependentTemplateName *QTN = 9014 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 9015 9016 if (QTN) 9017 return TemplateName(QTN); 9018 9019 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 9020 if (CanonNNS == NNS) { 9021 QTN = new (*this, alignof(DependentTemplateName)) 9022 DependentTemplateName(NNS, Name); 9023 } else { 9024 TemplateName Canon = getDependentTemplateName(CanonNNS, Name); 9025 QTN = new (*this, alignof(DependentTemplateName)) 9026 DependentTemplateName(NNS, Name, Canon); 9027 DependentTemplateName *CheckQTN = 9028 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 9029 assert(!CheckQTN && "Dependent type name canonicalization broken"); 9030 (void)CheckQTN; 9031 } 9032 9033 DependentTemplateNames.InsertNode(QTN, InsertPos); 9034 return TemplateName(QTN); 9035 } 9036 9037 /// Retrieve the template name that represents a dependent 9038 /// template name such as \c MetaFun::template operator+. 9039 TemplateName 9040 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 9041 OverloadedOperatorKind Operator) const { 9042 assert((!NNS || NNS->isDependent()) && 9043 "Nested name specifier must be dependent"); 9044 9045 llvm::FoldingSetNodeID ID; 9046 DependentTemplateName::Profile(ID, NNS, Operator); 9047 9048 void *InsertPos = nullptr; 9049 DependentTemplateName *QTN 9050 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 9051 9052 if (QTN) 9053 return TemplateName(QTN); 9054 9055 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 9056 if (CanonNNS == NNS) { 9057 QTN = new (*this, alignof(DependentTemplateName)) 9058 DependentTemplateName(NNS, Operator); 9059 } else { 9060 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator); 9061 QTN = new (*this, alignof(DependentTemplateName)) 9062 DependentTemplateName(NNS, Operator, Canon); 9063 9064 DependentTemplateName *CheckQTN 9065 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 9066 assert(!CheckQTN && "Dependent template name canonicalization broken"); 9067 (void)CheckQTN; 9068 } 9069 9070 DependentTemplateNames.InsertNode(QTN, InsertPos); 9071 return TemplateName(QTN); 9072 } 9073 9074 TemplateName 9075 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param, 9076 TemplateName replacement) const { 9077 llvm::FoldingSetNodeID ID; 9078 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement); 9079 9080 void *insertPos = nullptr; 9081 SubstTemplateTemplateParmStorage *subst 9082 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos); 9083 9084 if (!subst) { 9085 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement); 9086 SubstTemplateTemplateParms.InsertNode(subst, insertPos); 9087 } 9088 9089 return TemplateName(subst); 9090 } 9091 9092 TemplateName 9093 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param, 9094 const TemplateArgument &ArgPack) const { 9095 auto &Self = const_cast<ASTContext &>(*this); 9096 llvm::FoldingSetNodeID ID; 9097 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack); 9098 9099 void *InsertPos = nullptr; 9100 SubstTemplateTemplateParmPackStorage *Subst 9101 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos); 9102 9103 if (!Subst) { 9104 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param, 9105 ArgPack.pack_size(), 9106 ArgPack.pack_begin()); 9107 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos); 9108 } 9109 9110 return TemplateName(Subst); 9111 } 9112 9113 /// getFromTargetType - Given one of the integer types provided by 9114 /// TargetInfo, produce the corresponding type. The unsigned @p Type 9115 /// is actually a value of type @c TargetInfo::IntType. 9116 CanQualType ASTContext::getFromTargetType(unsigned Type) const { 9117 switch (Type) { 9118 case TargetInfo::NoInt: return {}; 9119 case TargetInfo::SignedChar: return SignedCharTy; 9120 case TargetInfo::UnsignedChar: return UnsignedCharTy; 9121 case TargetInfo::SignedShort: return ShortTy; 9122 case TargetInfo::UnsignedShort: return UnsignedShortTy; 9123 case TargetInfo::SignedInt: return IntTy; 9124 case TargetInfo::UnsignedInt: return UnsignedIntTy; 9125 case TargetInfo::SignedLong: return LongTy; 9126 case TargetInfo::UnsignedLong: return UnsignedLongTy; 9127 case TargetInfo::SignedLongLong: return LongLongTy; 9128 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy; 9129 } 9130 9131 llvm_unreachable("Unhandled TargetInfo::IntType value"); 9132 } 9133 9134 //===----------------------------------------------------------------------===// 9135 // Type Predicates. 9136 //===----------------------------------------------------------------------===// 9137 9138 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's 9139 /// garbage collection attribute. 9140 /// 9141 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const { 9142 if (getLangOpts().getGC() == LangOptions::NonGC) 9143 return Qualifiers::GCNone; 9144 9145 assert(getLangOpts().ObjC); 9146 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr(); 9147 9148 // Default behaviour under objective-C's gc is for ObjC pointers 9149 // (or pointers to them) be treated as though they were declared 9150 // as __strong. 9151 if (GCAttrs == Qualifiers::GCNone) { 9152 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) 9153 return Qualifiers::Strong; 9154 else if (Ty->isPointerType()) 9155 return getObjCGCAttrKind(Ty->castAs<PointerType>()->getPointeeType()); 9156 } else { 9157 // It's not valid to set GC attributes on anything that isn't a 9158 // pointer. 9159 #ifndef NDEBUG 9160 QualType CT = Ty->getCanonicalTypeInternal(); 9161 while (const auto *AT = dyn_cast<ArrayType>(CT)) 9162 CT = AT->getElementType(); 9163 assert(CT->isAnyPointerType() || CT->isBlockPointerType()); 9164 #endif 9165 } 9166 return GCAttrs; 9167 } 9168 9169 //===----------------------------------------------------------------------===// 9170 // Type Compatibility Testing 9171 //===----------------------------------------------------------------------===// 9172 9173 /// areCompatVectorTypes - Return true if the two specified vector types are 9174 /// compatible. 9175 static bool areCompatVectorTypes(const VectorType *LHS, 9176 const VectorType *RHS) { 9177 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 9178 return LHS->getElementType() == RHS->getElementType() && 9179 LHS->getNumElements() == RHS->getNumElements(); 9180 } 9181 9182 /// areCompatMatrixTypes - Return true if the two specified matrix types are 9183 /// compatible. 9184 static bool areCompatMatrixTypes(const ConstantMatrixType *LHS, 9185 const ConstantMatrixType *RHS) { 9186 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 9187 return LHS->getElementType() == RHS->getElementType() && 9188 LHS->getNumRows() == RHS->getNumRows() && 9189 LHS->getNumColumns() == RHS->getNumColumns(); 9190 } 9191 9192 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec, 9193 QualType SecondVec) { 9194 assert(FirstVec->isVectorType() && "FirstVec should be a vector type"); 9195 assert(SecondVec->isVectorType() && "SecondVec should be a vector type"); 9196 9197 if (hasSameUnqualifiedType(FirstVec, SecondVec)) 9198 return true; 9199 9200 // Treat Neon vector types and most AltiVec vector types as if they are the 9201 // equivalent GCC vector types. 9202 const auto *First = FirstVec->castAs<VectorType>(); 9203 const auto *Second = SecondVec->castAs<VectorType>(); 9204 if (First->getNumElements() == Second->getNumElements() && 9205 hasSameType(First->getElementType(), Second->getElementType()) && 9206 First->getVectorKind() != VectorType::AltiVecPixel && 9207 First->getVectorKind() != VectorType::AltiVecBool && 9208 Second->getVectorKind() != VectorType::AltiVecPixel && 9209 Second->getVectorKind() != VectorType::AltiVecBool && 9210 First->getVectorKind() != VectorType::SveFixedLengthDataVector && 9211 First->getVectorKind() != VectorType::SveFixedLengthPredicateVector && 9212 Second->getVectorKind() != VectorType::SveFixedLengthDataVector && 9213 Second->getVectorKind() != VectorType::SveFixedLengthPredicateVector) 9214 return true; 9215 9216 return false; 9217 } 9218 9219 /// getSVETypeSize - Return SVE vector or predicate register size. 9220 static uint64_t getSVETypeSize(ASTContext &Context, const BuiltinType *Ty) { 9221 assert(Ty->isVLSTBuiltinType() && "Invalid SVE Type"); 9222 return Ty->getKind() == BuiltinType::SveBool 9223 ? (Context.getLangOpts().VScaleMin * 128) / Context.getCharWidth() 9224 : Context.getLangOpts().VScaleMin * 128; 9225 } 9226 9227 bool ASTContext::areCompatibleSveTypes(QualType FirstType, 9228 QualType SecondType) { 9229 assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) || 9230 (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) && 9231 "Expected SVE builtin type and vector type!"); 9232 9233 auto IsValidCast = [this](QualType FirstType, QualType SecondType) { 9234 if (const auto *BT = FirstType->getAs<BuiltinType>()) { 9235 if (const auto *VT = SecondType->getAs<VectorType>()) { 9236 // Predicates have the same representation as uint8 so we also have to 9237 // check the kind to make these types incompatible. 9238 if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 9239 return BT->getKind() == BuiltinType::SveBool; 9240 else if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) 9241 return VT->getElementType().getCanonicalType() == 9242 FirstType->getSveEltType(*this); 9243 else if (VT->getVectorKind() == VectorType::GenericVector) 9244 return getTypeSize(SecondType) == getSVETypeSize(*this, BT) && 9245 hasSameType(VT->getElementType(), 9246 getBuiltinVectorTypeInfo(BT).ElementType); 9247 } 9248 } 9249 return false; 9250 }; 9251 9252 return IsValidCast(FirstType, SecondType) || 9253 IsValidCast(SecondType, FirstType); 9254 } 9255 9256 bool ASTContext::areLaxCompatibleSveTypes(QualType FirstType, 9257 QualType SecondType) { 9258 assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) || 9259 (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) && 9260 "Expected SVE builtin type and vector type!"); 9261 9262 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) { 9263 const auto *BT = FirstType->getAs<BuiltinType>(); 9264 if (!BT) 9265 return false; 9266 9267 const auto *VecTy = SecondType->getAs<VectorType>(); 9268 if (VecTy && 9269 (VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector || 9270 VecTy->getVectorKind() == VectorType::GenericVector)) { 9271 const LangOptions::LaxVectorConversionKind LVCKind = 9272 getLangOpts().getLaxVectorConversions(); 9273 9274 // Can not convert between sve predicates and sve vectors because of 9275 // different size. 9276 if (BT->getKind() == BuiltinType::SveBool && 9277 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector) 9278 return false; 9279 9280 // If __ARM_FEATURE_SVE_BITS != N do not allow GNU vector lax conversion. 9281 // "Whenever __ARM_FEATURE_SVE_BITS==N, GNUT implicitly 9282 // converts to VLAT and VLAT implicitly converts to GNUT." 9283 // ACLE Spec Version 00bet6, 3.7.3.2. Behavior common to vectors and 9284 // predicates. 9285 if (VecTy->getVectorKind() == VectorType::GenericVector && 9286 getTypeSize(SecondType) != getSVETypeSize(*this, BT)) 9287 return false; 9288 9289 // If -flax-vector-conversions=all is specified, the types are 9290 // certainly compatible. 9291 if (LVCKind == LangOptions::LaxVectorConversionKind::All) 9292 return true; 9293 9294 // If -flax-vector-conversions=integer is specified, the types are 9295 // compatible if the elements are integer types. 9296 if (LVCKind == LangOptions::LaxVectorConversionKind::Integer) 9297 return VecTy->getElementType().getCanonicalType()->isIntegerType() && 9298 FirstType->getSveEltType(*this)->isIntegerType(); 9299 } 9300 9301 return false; 9302 }; 9303 9304 return IsLaxCompatible(FirstType, SecondType) || 9305 IsLaxCompatible(SecondType, FirstType); 9306 } 9307 9308 bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const { 9309 while (true) { 9310 // __strong id 9311 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) { 9312 if (Attr->getAttrKind() == attr::ObjCOwnership) 9313 return true; 9314 9315 Ty = Attr->getModifiedType(); 9316 9317 // X *__strong (...) 9318 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) { 9319 Ty = Paren->getInnerType(); 9320 9321 // We do not want to look through typedefs, typeof(expr), 9322 // typeof(type), or any other way that the type is somehow 9323 // abstracted. 9324 } else { 9325 return false; 9326 } 9327 } 9328 } 9329 9330 //===----------------------------------------------------------------------===// 9331 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's. 9332 //===----------------------------------------------------------------------===// 9333 9334 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the 9335 /// inheritance hierarchy of 'rProto'. 9336 bool 9337 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, 9338 ObjCProtocolDecl *rProto) const { 9339 if (declaresSameEntity(lProto, rProto)) 9340 return true; 9341 for (auto *PI : rProto->protocols()) 9342 if (ProtocolCompatibleWithProtocol(lProto, PI)) 9343 return true; 9344 return false; 9345 } 9346 9347 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and 9348 /// Class<pr1, ...>. 9349 bool ASTContext::ObjCQualifiedClassTypesAreCompatible( 9350 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) { 9351 for (auto *lhsProto : lhs->quals()) { 9352 bool match = false; 9353 for (auto *rhsProto : rhs->quals()) { 9354 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) { 9355 match = true; 9356 break; 9357 } 9358 } 9359 if (!match) 9360 return false; 9361 } 9362 return true; 9363 } 9364 9365 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an 9366 /// ObjCQualifiedIDType. 9367 bool ASTContext::ObjCQualifiedIdTypesAreCompatible( 9368 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs, 9369 bool compare) { 9370 // Allow id<P..> and an 'id' in all cases. 9371 if (lhs->isObjCIdType() || rhs->isObjCIdType()) 9372 return true; 9373 9374 // Don't allow id<P..> to convert to Class or Class<P..> in either direction. 9375 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() || 9376 rhs->isObjCClassType() || rhs->isObjCQualifiedClassType()) 9377 return false; 9378 9379 if (lhs->isObjCQualifiedIdType()) { 9380 if (rhs->qual_empty()) { 9381 // If the RHS is a unqualified interface pointer "NSString*", 9382 // make sure we check the class hierarchy. 9383 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) { 9384 for (auto *I : lhs->quals()) { 9385 // when comparing an id<P> on lhs with a static type on rhs, 9386 // see if static class implements all of id's protocols, directly or 9387 // through its super class and categories. 9388 if (!rhsID->ClassImplementsProtocol(I, true)) 9389 return false; 9390 } 9391 } 9392 // If there are no qualifiers and no interface, we have an 'id'. 9393 return true; 9394 } 9395 // Both the right and left sides have qualifiers. 9396 for (auto *lhsProto : lhs->quals()) { 9397 bool match = false; 9398 9399 // when comparing an id<P> on lhs with a static type on rhs, 9400 // see if static class implements all of id's protocols, directly or 9401 // through its super class and categories. 9402 for (auto *rhsProto : rhs->quals()) { 9403 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 9404 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 9405 match = true; 9406 break; 9407 } 9408 } 9409 // If the RHS is a qualified interface pointer "NSString<P>*", 9410 // make sure we check the class hierarchy. 9411 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) { 9412 for (auto *I : lhs->quals()) { 9413 // when comparing an id<P> on lhs with a static type on rhs, 9414 // see if static class implements all of id's protocols, directly or 9415 // through its super class and categories. 9416 if (rhsID->ClassImplementsProtocol(I, true)) { 9417 match = true; 9418 break; 9419 } 9420 } 9421 } 9422 if (!match) 9423 return false; 9424 } 9425 9426 return true; 9427 } 9428 9429 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>"); 9430 9431 if (lhs->getInterfaceType()) { 9432 // If both the right and left sides have qualifiers. 9433 for (auto *lhsProto : lhs->quals()) { 9434 bool match = false; 9435 9436 // when comparing an id<P> on rhs with a static type on lhs, 9437 // see if static class implements all of id's protocols, directly or 9438 // through its super class and categories. 9439 // First, lhs protocols in the qualifier list must be found, direct 9440 // or indirect in rhs's qualifier list or it is a mismatch. 9441 for (auto *rhsProto : rhs->quals()) { 9442 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 9443 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 9444 match = true; 9445 break; 9446 } 9447 } 9448 if (!match) 9449 return false; 9450 } 9451 9452 // Static class's protocols, or its super class or category protocols 9453 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch. 9454 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) { 9455 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols; 9456 CollectInheritedProtocols(lhsID, LHSInheritedProtocols); 9457 // This is rather dubious but matches gcc's behavior. If lhs has 9458 // no type qualifier and its class has no static protocol(s) 9459 // assume that it is mismatch. 9460 if (LHSInheritedProtocols.empty() && lhs->qual_empty()) 9461 return false; 9462 for (auto *lhsProto : LHSInheritedProtocols) { 9463 bool match = false; 9464 for (auto *rhsProto : rhs->quals()) { 9465 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 9466 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 9467 match = true; 9468 break; 9469 } 9470 } 9471 if (!match) 9472 return false; 9473 } 9474 } 9475 return true; 9476 } 9477 return false; 9478 } 9479 9480 /// canAssignObjCInterfaces - Return true if the two interface types are 9481 /// compatible for assignment from RHS to LHS. This handles validation of any 9482 /// protocol qualifiers on the LHS or RHS. 9483 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, 9484 const ObjCObjectPointerType *RHSOPT) { 9485 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 9486 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 9487 9488 // If either type represents the built-in 'id' type, return true. 9489 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId()) 9490 return true; 9491 9492 // Function object that propagates a successful result or handles 9493 // __kindof types. 9494 auto finish = [&](bool succeeded) -> bool { 9495 if (succeeded) 9496 return true; 9497 9498 if (!RHS->isKindOfType()) 9499 return false; 9500 9501 // Strip off __kindof and protocol qualifiers, then check whether 9502 // we can assign the other way. 9503 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this), 9504 LHSOPT->stripObjCKindOfTypeAndQuals(*this)); 9505 }; 9506 9507 // Casts from or to id<P> are allowed when the other side has compatible 9508 // protocols. 9509 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) { 9510 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false)); 9511 } 9512 9513 // Verify protocol compatibility for casts from Class<P1> to Class<P2>. 9514 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) { 9515 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT)); 9516 } 9517 9518 // Casts from Class to Class<Foo>, or vice-versa, are allowed. 9519 if (LHS->isObjCClass() && RHS->isObjCClass()) { 9520 return true; 9521 } 9522 9523 // If we have 2 user-defined types, fall into that path. 9524 if (LHS->getInterface() && RHS->getInterface()) { 9525 return finish(canAssignObjCInterfaces(LHS, RHS)); 9526 } 9527 9528 return false; 9529 } 9530 9531 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written 9532 /// for providing type-safety for objective-c pointers used to pass/return 9533 /// arguments in block literals. When passed as arguments, passing 'A*' where 9534 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is 9535 /// not OK. For the return type, the opposite is not OK. 9536 bool ASTContext::canAssignObjCInterfacesInBlockPointer( 9537 const ObjCObjectPointerType *LHSOPT, 9538 const ObjCObjectPointerType *RHSOPT, 9539 bool BlockReturnType) { 9540 9541 // Function object that propagates a successful result or handles 9542 // __kindof types. 9543 auto finish = [&](bool succeeded) -> bool { 9544 if (succeeded) 9545 return true; 9546 9547 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT; 9548 if (!Expected->isKindOfType()) 9549 return false; 9550 9551 // Strip off __kindof and protocol qualifiers, then check whether 9552 // we can assign the other way. 9553 return canAssignObjCInterfacesInBlockPointer( 9554 RHSOPT->stripObjCKindOfTypeAndQuals(*this), 9555 LHSOPT->stripObjCKindOfTypeAndQuals(*this), 9556 BlockReturnType); 9557 }; 9558 9559 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType()) 9560 return true; 9561 9562 if (LHSOPT->isObjCBuiltinType()) { 9563 return finish(RHSOPT->isObjCBuiltinType() || 9564 RHSOPT->isObjCQualifiedIdType()); 9565 } 9566 9567 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) { 9568 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking) 9569 // Use for block parameters previous type checking for compatibility. 9570 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) || 9571 // Or corrected type checking as in non-compat mode. 9572 (!BlockReturnType && 9573 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false))); 9574 else 9575 return finish(ObjCQualifiedIdTypesAreCompatible( 9576 (BlockReturnType ? LHSOPT : RHSOPT), 9577 (BlockReturnType ? RHSOPT : LHSOPT), false)); 9578 } 9579 9580 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType(); 9581 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType(); 9582 if (LHS && RHS) { // We have 2 user-defined types. 9583 if (LHS != RHS) { 9584 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl())) 9585 return finish(BlockReturnType); 9586 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl())) 9587 return finish(!BlockReturnType); 9588 } 9589 else 9590 return true; 9591 } 9592 return false; 9593 } 9594 9595 /// Comparison routine for Objective-C protocols to be used with 9596 /// llvm::array_pod_sort. 9597 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs, 9598 ObjCProtocolDecl * const *rhs) { 9599 return (*lhs)->getName().compare((*rhs)->getName()); 9600 } 9601 9602 /// getIntersectionOfProtocols - This routine finds the intersection of set 9603 /// of protocols inherited from two distinct objective-c pointer objects with 9604 /// the given common base. 9605 /// It is used to build composite qualifier list of the composite type of 9606 /// the conditional expression involving two objective-c pointer objects. 9607 static 9608 void getIntersectionOfProtocols(ASTContext &Context, 9609 const ObjCInterfaceDecl *CommonBase, 9610 const ObjCObjectPointerType *LHSOPT, 9611 const ObjCObjectPointerType *RHSOPT, 9612 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) { 9613 9614 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 9615 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 9616 assert(LHS->getInterface() && "LHS must have an interface base"); 9617 assert(RHS->getInterface() && "RHS must have an interface base"); 9618 9619 // Add all of the protocols for the LHS. 9620 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet; 9621 9622 // Start with the protocol qualifiers. 9623 for (auto proto : LHS->quals()) { 9624 Context.CollectInheritedProtocols(proto, LHSProtocolSet); 9625 } 9626 9627 // Also add the protocols associated with the LHS interface. 9628 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet); 9629 9630 // Add all of the protocols for the RHS. 9631 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet; 9632 9633 // Start with the protocol qualifiers. 9634 for (auto proto : RHS->quals()) { 9635 Context.CollectInheritedProtocols(proto, RHSProtocolSet); 9636 } 9637 9638 // Also add the protocols associated with the RHS interface. 9639 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet); 9640 9641 // Compute the intersection of the collected protocol sets. 9642 for (auto proto : LHSProtocolSet) { 9643 if (RHSProtocolSet.count(proto)) 9644 IntersectionSet.push_back(proto); 9645 } 9646 9647 // Compute the set of protocols that is implied by either the common type or 9648 // the protocols within the intersection. 9649 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols; 9650 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols); 9651 9652 // Remove any implied protocols from the list of inherited protocols. 9653 if (!ImpliedProtocols.empty()) { 9654 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool { 9655 return ImpliedProtocols.contains(proto); 9656 }); 9657 } 9658 9659 // Sort the remaining protocols by name. 9660 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(), 9661 compareObjCProtocolsByName); 9662 } 9663 9664 /// Determine whether the first type is a subtype of the second. 9665 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs, 9666 QualType rhs) { 9667 // Common case: two object pointers. 9668 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>(); 9669 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 9670 if (lhsOPT && rhsOPT) 9671 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT); 9672 9673 // Two block pointers. 9674 const auto *lhsBlock = lhs->getAs<BlockPointerType>(); 9675 const auto *rhsBlock = rhs->getAs<BlockPointerType>(); 9676 if (lhsBlock && rhsBlock) 9677 return ctx.typesAreBlockPointerCompatible(lhs, rhs); 9678 9679 // If either is an unqualified 'id' and the other is a block, it's 9680 // acceptable. 9681 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) || 9682 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock)) 9683 return true; 9684 9685 return false; 9686 } 9687 9688 // Check that the given Objective-C type argument lists are equivalent. 9689 static bool sameObjCTypeArgs(ASTContext &ctx, 9690 const ObjCInterfaceDecl *iface, 9691 ArrayRef<QualType> lhsArgs, 9692 ArrayRef<QualType> rhsArgs, 9693 bool stripKindOf) { 9694 if (lhsArgs.size() != rhsArgs.size()) 9695 return false; 9696 9697 ObjCTypeParamList *typeParams = iface->getTypeParamList(); 9698 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) { 9699 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i])) 9700 continue; 9701 9702 switch (typeParams->begin()[i]->getVariance()) { 9703 case ObjCTypeParamVariance::Invariant: 9704 if (!stripKindOf || 9705 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx), 9706 rhsArgs[i].stripObjCKindOfType(ctx))) { 9707 return false; 9708 } 9709 break; 9710 9711 case ObjCTypeParamVariance::Covariant: 9712 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i])) 9713 return false; 9714 break; 9715 9716 case ObjCTypeParamVariance::Contravariant: 9717 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i])) 9718 return false; 9719 break; 9720 } 9721 } 9722 9723 return true; 9724 } 9725 9726 QualType ASTContext::areCommonBaseCompatible( 9727 const ObjCObjectPointerType *Lptr, 9728 const ObjCObjectPointerType *Rptr) { 9729 const ObjCObjectType *LHS = Lptr->getObjectType(); 9730 const ObjCObjectType *RHS = Rptr->getObjectType(); 9731 const ObjCInterfaceDecl* LDecl = LHS->getInterface(); 9732 const ObjCInterfaceDecl* RDecl = RHS->getInterface(); 9733 9734 if (!LDecl || !RDecl) 9735 return {}; 9736 9737 // When either LHS or RHS is a kindof type, we should return a kindof type. 9738 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return 9739 // kindof(A). 9740 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType(); 9741 9742 // Follow the left-hand side up the class hierarchy until we either hit a 9743 // root or find the RHS. Record the ancestors in case we don't find it. 9744 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4> 9745 LHSAncestors; 9746 while (true) { 9747 // Record this ancestor. We'll need this if the common type isn't in the 9748 // path from the LHS to the root. 9749 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS; 9750 9751 if (declaresSameEntity(LHS->getInterface(), RDecl)) { 9752 // Get the type arguments. 9753 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten(); 9754 bool anyChanges = false; 9755 if (LHS->isSpecialized() && RHS->isSpecialized()) { 9756 // Both have type arguments, compare them. 9757 if (!sameObjCTypeArgs(*this, LHS->getInterface(), 9758 LHS->getTypeArgs(), RHS->getTypeArgs(), 9759 /*stripKindOf=*/true)) 9760 return {}; 9761 } else if (LHS->isSpecialized() != RHS->isSpecialized()) { 9762 // If only one has type arguments, the result will not have type 9763 // arguments. 9764 LHSTypeArgs = {}; 9765 anyChanges = true; 9766 } 9767 9768 // Compute the intersection of protocols. 9769 SmallVector<ObjCProtocolDecl *, 8> Protocols; 9770 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr, 9771 Protocols); 9772 if (!Protocols.empty()) 9773 anyChanges = true; 9774 9775 // If anything in the LHS will have changed, build a new result type. 9776 // If we need to return a kindof type but LHS is not a kindof type, we 9777 // build a new result type. 9778 if (anyChanges || LHS->isKindOfType() != anyKindOf) { 9779 QualType Result = getObjCInterfaceType(LHS->getInterface()); 9780 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols, 9781 anyKindOf || LHS->isKindOfType()); 9782 return getObjCObjectPointerType(Result); 9783 } 9784 9785 return getObjCObjectPointerType(QualType(LHS, 0)); 9786 } 9787 9788 // Find the superclass. 9789 QualType LHSSuperType = LHS->getSuperClassType(); 9790 if (LHSSuperType.isNull()) 9791 break; 9792 9793 LHS = LHSSuperType->castAs<ObjCObjectType>(); 9794 } 9795 9796 // We didn't find anything by following the LHS to its root; now check 9797 // the RHS against the cached set of ancestors. 9798 while (true) { 9799 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl()); 9800 if (KnownLHS != LHSAncestors.end()) { 9801 LHS = KnownLHS->second; 9802 9803 // Get the type arguments. 9804 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten(); 9805 bool anyChanges = false; 9806 if (LHS->isSpecialized() && RHS->isSpecialized()) { 9807 // Both have type arguments, compare them. 9808 if (!sameObjCTypeArgs(*this, LHS->getInterface(), 9809 LHS->getTypeArgs(), RHS->getTypeArgs(), 9810 /*stripKindOf=*/true)) 9811 return {}; 9812 } else if (LHS->isSpecialized() != RHS->isSpecialized()) { 9813 // If only one has type arguments, the result will not have type 9814 // arguments. 9815 RHSTypeArgs = {}; 9816 anyChanges = true; 9817 } 9818 9819 // Compute the intersection of protocols. 9820 SmallVector<ObjCProtocolDecl *, 8> Protocols; 9821 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr, 9822 Protocols); 9823 if (!Protocols.empty()) 9824 anyChanges = true; 9825 9826 // If we need to return a kindof type but RHS is not a kindof type, we 9827 // build a new result type. 9828 if (anyChanges || RHS->isKindOfType() != anyKindOf) { 9829 QualType Result = getObjCInterfaceType(RHS->getInterface()); 9830 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols, 9831 anyKindOf || RHS->isKindOfType()); 9832 return getObjCObjectPointerType(Result); 9833 } 9834 9835 return getObjCObjectPointerType(QualType(RHS, 0)); 9836 } 9837 9838 // Find the superclass of the RHS. 9839 QualType RHSSuperType = RHS->getSuperClassType(); 9840 if (RHSSuperType.isNull()) 9841 break; 9842 9843 RHS = RHSSuperType->castAs<ObjCObjectType>(); 9844 } 9845 9846 return {}; 9847 } 9848 9849 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS, 9850 const ObjCObjectType *RHS) { 9851 assert(LHS->getInterface() && "LHS is not an interface type"); 9852 assert(RHS->getInterface() && "RHS is not an interface type"); 9853 9854 // Verify that the base decls are compatible: the RHS must be a subclass of 9855 // the LHS. 9856 ObjCInterfaceDecl *LHSInterface = LHS->getInterface(); 9857 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface()); 9858 if (!IsSuperClass) 9859 return false; 9860 9861 // If the LHS has protocol qualifiers, determine whether all of them are 9862 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the 9863 // LHS). 9864 if (LHS->getNumProtocols() > 0) { 9865 // OK if conversion of LHS to SuperClass results in narrowing of types 9866 // ; i.e., SuperClass may implement at least one of the protocols 9867 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok. 9868 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>. 9869 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols; 9870 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols); 9871 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's 9872 // qualifiers. 9873 for (auto *RHSPI : RHS->quals()) 9874 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols); 9875 // If there is no protocols associated with RHS, it is not a match. 9876 if (SuperClassInheritedProtocols.empty()) 9877 return false; 9878 9879 for (const auto *LHSProto : LHS->quals()) { 9880 bool SuperImplementsProtocol = false; 9881 for (auto *SuperClassProto : SuperClassInheritedProtocols) 9882 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) { 9883 SuperImplementsProtocol = true; 9884 break; 9885 } 9886 if (!SuperImplementsProtocol) 9887 return false; 9888 } 9889 } 9890 9891 // If the LHS is specialized, we may need to check type arguments. 9892 if (LHS->isSpecialized()) { 9893 // Follow the superclass chain until we've matched the LHS class in the 9894 // hierarchy. This substitutes type arguments through. 9895 const ObjCObjectType *RHSSuper = RHS; 9896 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface)) 9897 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>(); 9898 9899 // If the RHS is specializd, compare type arguments. 9900 if (RHSSuper->isSpecialized() && 9901 !sameObjCTypeArgs(*this, LHS->getInterface(), 9902 LHS->getTypeArgs(), RHSSuper->getTypeArgs(), 9903 /*stripKindOf=*/true)) { 9904 return false; 9905 } 9906 } 9907 9908 return true; 9909 } 9910 9911 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) { 9912 // get the "pointed to" types 9913 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>(); 9914 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>(); 9915 9916 if (!LHSOPT || !RHSOPT) 9917 return false; 9918 9919 return canAssignObjCInterfaces(LHSOPT, RHSOPT) || 9920 canAssignObjCInterfaces(RHSOPT, LHSOPT); 9921 } 9922 9923 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) { 9924 return canAssignObjCInterfaces( 9925 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(), 9926 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>()); 9927 } 9928 9929 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible, 9930 /// both shall have the identically qualified version of a compatible type. 9931 /// C99 6.2.7p1: Two types have compatible types if their types are the 9932 /// same. See 6.7.[2,3,5] for additional rules. 9933 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS, 9934 bool CompareUnqualified) { 9935 if (getLangOpts().CPlusPlus) 9936 return hasSameType(LHS, RHS); 9937 9938 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull(); 9939 } 9940 9941 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) { 9942 return typesAreCompatible(LHS, RHS); 9943 } 9944 9945 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) { 9946 return !mergeTypes(LHS, RHS, true).isNull(); 9947 } 9948 9949 /// mergeTransparentUnionType - if T is a transparent union type and a member 9950 /// of T is compatible with SubType, return the merged type, else return 9951 /// QualType() 9952 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType, 9953 bool OfBlockPointer, 9954 bool Unqualified) { 9955 if (const RecordType *UT = T->getAsUnionType()) { 9956 RecordDecl *UD = UT->getDecl(); 9957 if (UD->hasAttr<TransparentUnionAttr>()) { 9958 for (const auto *I : UD->fields()) { 9959 QualType ET = I->getType().getUnqualifiedType(); 9960 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified); 9961 if (!MT.isNull()) 9962 return MT; 9963 } 9964 } 9965 } 9966 9967 return {}; 9968 } 9969 9970 /// mergeFunctionParameterTypes - merge two types which appear as function 9971 /// parameter types 9972 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs, 9973 bool OfBlockPointer, 9974 bool Unqualified) { 9975 // GNU extension: two types are compatible if they appear as a function 9976 // argument, one of the types is a transparent union type and the other 9977 // type is compatible with a union member 9978 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer, 9979 Unqualified); 9980 if (!lmerge.isNull()) 9981 return lmerge; 9982 9983 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer, 9984 Unqualified); 9985 if (!rmerge.isNull()) 9986 return rmerge; 9987 9988 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified); 9989 } 9990 9991 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, 9992 bool OfBlockPointer, bool Unqualified, 9993 bool AllowCXX) { 9994 const auto *lbase = lhs->castAs<FunctionType>(); 9995 const auto *rbase = rhs->castAs<FunctionType>(); 9996 const auto *lproto = dyn_cast<FunctionProtoType>(lbase); 9997 const auto *rproto = dyn_cast<FunctionProtoType>(rbase); 9998 bool allLTypes = true; 9999 bool allRTypes = true; 10000 10001 // Check return type 10002 QualType retType; 10003 if (OfBlockPointer) { 10004 QualType RHS = rbase->getReturnType(); 10005 QualType LHS = lbase->getReturnType(); 10006 bool UnqualifiedResult = Unqualified; 10007 if (!UnqualifiedResult) 10008 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers()); 10009 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true); 10010 } 10011 else 10012 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false, 10013 Unqualified); 10014 if (retType.isNull()) 10015 return {}; 10016 10017 if (Unqualified) 10018 retType = retType.getUnqualifiedType(); 10019 10020 CanQualType LRetType = getCanonicalType(lbase->getReturnType()); 10021 CanQualType RRetType = getCanonicalType(rbase->getReturnType()); 10022 if (Unqualified) { 10023 LRetType = LRetType.getUnqualifiedType(); 10024 RRetType = RRetType.getUnqualifiedType(); 10025 } 10026 10027 if (getCanonicalType(retType) != LRetType) 10028 allLTypes = false; 10029 if (getCanonicalType(retType) != RRetType) 10030 allRTypes = false; 10031 10032 // FIXME: double check this 10033 // FIXME: should we error if lbase->getRegParmAttr() != 0 && 10034 // rbase->getRegParmAttr() != 0 && 10035 // lbase->getRegParmAttr() != rbase->getRegParmAttr()? 10036 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo(); 10037 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo(); 10038 10039 // Compatible functions must have compatible calling conventions 10040 if (lbaseInfo.getCC() != rbaseInfo.getCC()) 10041 return {}; 10042 10043 // Regparm is part of the calling convention. 10044 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm()) 10045 return {}; 10046 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm()) 10047 return {}; 10048 10049 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult()) 10050 return {}; 10051 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs()) 10052 return {}; 10053 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck()) 10054 return {}; 10055 10056 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'. 10057 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn(); 10058 10059 if (lbaseInfo.getNoReturn() != NoReturn) 10060 allLTypes = false; 10061 if (rbaseInfo.getNoReturn() != NoReturn) 10062 allRTypes = false; 10063 10064 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn); 10065 10066 if (lproto && rproto) { // two C99 style function prototypes 10067 assert((AllowCXX || 10068 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) && 10069 "C++ shouldn't be here"); 10070 // Compatible functions must have the same number of parameters 10071 if (lproto->getNumParams() != rproto->getNumParams()) 10072 return {}; 10073 10074 // Variadic and non-variadic functions aren't compatible 10075 if (lproto->isVariadic() != rproto->isVariadic()) 10076 return {}; 10077 10078 if (lproto->getMethodQuals() != rproto->getMethodQuals()) 10079 return {}; 10080 10081 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos; 10082 bool canUseLeft, canUseRight; 10083 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight, 10084 newParamInfos)) 10085 return {}; 10086 10087 if (!canUseLeft) 10088 allLTypes = false; 10089 if (!canUseRight) 10090 allRTypes = false; 10091 10092 // Check parameter type compatibility 10093 SmallVector<QualType, 10> types; 10094 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) { 10095 QualType lParamType = lproto->getParamType(i).getUnqualifiedType(); 10096 QualType rParamType = rproto->getParamType(i).getUnqualifiedType(); 10097 QualType paramType = mergeFunctionParameterTypes( 10098 lParamType, rParamType, OfBlockPointer, Unqualified); 10099 if (paramType.isNull()) 10100 return {}; 10101 10102 if (Unqualified) 10103 paramType = paramType.getUnqualifiedType(); 10104 10105 types.push_back(paramType); 10106 if (Unqualified) { 10107 lParamType = lParamType.getUnqualifiedType(); 10108 rParamType = rParamType.getUnqualifiedType(); 10109 } 10110 10111 if (getCanonicalType(paramType) != getCanonicalType(lParamType)) 10112 allLTypes = false; 10113 if (getCanonicalType(paramType) != getCanonicalType(rParamType)) 10114 allRTypes = false; 10115 } 10116 10117 if (allLTypes) return lhs; 10118 if (allRTypes) return rhs; 10119 10120 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo(); 10121 EPI.ExtInfo = einfo; 10122 EPI.ExtParameterInfos = 10123 newParamInfos.empty() ? nullptr : newParamInfos.data(); 10124 return getFunctionType(retType, types, EPI); 10125 } 10126 10127 if (lproto) allRTypes = false; 10128 if (rproto) allLTypes = false; 10129 10130 const FunctionProtoType *proto = lproto ? lproto : rproto; 10131 if (proto) { 10132 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here"); 10133 if (proto->isVariadic()) 10134 return {}; 10135 // Check that the types are compatible with the types that 10136 // would result from default argument promotions (C99 6.7.5.3p15). 10137 // The only types actually affected are promotable integer 10138 // types and floats, which would be passed as a different 10139 // type depending on whether the prototype is visible. 10140 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) { 10141 QualType paramTy = proto->getParamType(i); 10142 10143 // Look at the converted type of enum types, since that is the type used 10144 // to pass enum values. 10145 if (const auto *Enum = paramTy->getAs<EnumType>()) { 10146 paramTy = Enum->getDecl()->getIntegerType(); 10147 if (paramTy.isNull()) 10148 return {}; 10149 } 10150 10151 if (paramTy->isPromotableIntegerType() || 10152 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy) 10153 return {}; 10154 } 10155 10156 if (allLTypes) return lhs; 10157 if (allRTypes) return rhs; 10158 10159 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo(); 10160 EPI.ExtInfo = einfo; 10161 return getFunctionType(retType, proto->getParamTypes(), EPI); 10162 } 10163 10164 if (allLTypes) return lhs; 10165 if (allRTypes) return rhs; 10166 return getFunctionNoProtoType(retType, einfo); 10167 } 10168 10169 /// Given that we have an enum type and a non-enum type, try to merge them. 10170 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET, 10171 QualType other, bool isBlockReturnType) { 10172 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char, 10173 // a signed integer type, or an unsigned integer type. 10174 // Compatibility is based on the underlying type, not the promotion 10175 // type. 10176 QualType underlyingType = ET->getDecl()->getIntegerType(); 10177 if (underlyingType.isNull()) 10178 return {}; 10179 if (Context.hasSameType(underlyingType, other)) 10180 return other; 10181 10182 // In block return types, we're more permissive and accept any 10183 // integral type of the same size. 10184 if (isBlockReturnType && other->isIntegerType() && 10185 Context.getTypeSize(underlyingType) == Context.getTypeSize(other)) 10186 return other; 10187 10188 return {}; 10189 } 10190 10191 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, 10192 bool OfBlockPointer, 10193 bool Unqualified, bool BlockReturnType) { 10194 // For C++ we will not reach this code with reference types (see below), 10195 // for OpenMP variant call overloading we might. 10196 // 10197 // C++ [expr]: If an expression initially has the type "reference to T", the 10198 // type is adjusted to "T" prior to any further analysis, the expression 10199 // designates the object or function denoted by the reference, and the 10200 // expression is an lvalue unless the reference is an rvalue reference and 10201 // the expression is a function call (possibly inside parentheses). 10202 auto *LHSRefTy = LHS->getAs<ReferenceType>(); 10203 auto *RHSRefTy = RHS->getAs<ReferenceType>(); 10204 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy && 10205 LHS->getTypeClass() == RHS->getTypeClass()) 10206 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(), 10207 OfBlockPointer, Unqualified, BlockReturnType); 10208 if (LHSRefTy || RHSRefTy) 10209 return {}; 10210 10211 if (Unqualified) { 10212 LHS = LHS.getUnqualifiedType(); 10213 RHS = RHS.getUnqualifiedType(); 10214 } 10215 10216 QualType LHSCan = getCanonicalType(LHS), 10217 RHSCan = getCanonicalType(RHS); 10218 10219 // If two types are identical, they are compatible. 10220 if (LHSCan == RHSCan) 10221 return LHS; 10222 10223 // If the qualifiers are different, the types aren't compatible... mostly. 10224 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 10225 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 10226 if (LQuals != RQuals) { 10227 // If any of these qualifiers are different, we have a type 10228 // mismatch. 10229 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 10230 LQuals.getAddressSpace() != RQuals.getAddressSpace() || 10231 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() || 10232 LQuals.hasUnaligned() != RQuals.hasUnaligned()) 10233 return {}; 10234 10235 // Exactly one GC qualifier difference is allowed: __strong is 10236 // okay if the other type has no GC qualifier but is an Objective 10237 // C object pointer (i.e. implicitly strong by default). We fix 10238 // this by pretending that the unqualified type was actually 10239 // qualified __strong. 10240 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 10241 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 10242 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 10243 10244 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 10245 return {}; 10246 10247 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) { 10248 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong)); 10249 } 10250 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) { 10251 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS); 10252 } 10253 return {}; 10254 } 10255 10256 // Okay, qualifiers are equal. 10257 10258 Type::TypeClass LHSClass = LHSCan->getTypeClass(); 10259 Type::TypeClass RHSClass = RHSCan->getTypeClass(); 10260 10261 // We want to consider the two function types to be the same for these 10262 // comparisons, just force one to the other. 10263 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto; 10264 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto; 10265 10266 // Same as above for arrays 10267 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray) 10268 LHSClass = Type::ConstantArray; 10269 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray) 10270 RHSClass = Type::ConstantArray; 10271 10272 // ObjCInterfaces are just specialized ObjCObjects. 10273 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject; 10274 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject; 10275 10276 // Canonicalize ExtVector -> Vector. 10277 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector; 10278 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector; 10279 10280 // If the canonical type classes don't match. 10281 if (LHSClass != RHSClass) { 10282 // Note that we only have special rules for turning block enum 10283 // returns into block int returns, not vice-versa. 10284 if (const auto *ETy = LHS->getAs<EnumType>()) { 10285 return mergeEnumWithInteger(*this, ETy, RHS, false); 10286 } 10287 if (const EnumType* ETy = RHS->getAs<EnumType>()) { 10288 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType); 10289 } 10290 // allow block pointer type to match an 'id' type. 10291 if (OfBlockPointer && !BlockReturnType) { 10292 if (LHS->isObjCIdType() && RHS->isBlockPointerType()) 10293 return LHS; 10294 if (RHS->isObjCIdType() && LHS->isBlockPointerType()) 10295 return RHS; 10296 } 10297 // Allow __auto_type to match anything; it merges to the type with more 10298 // information. 10299 if (const auto *AT = LHS->getAs<AutoType>()) { 10300 if (AT->isGNUAutoType()) 10301 return RHS; 10302 } 10303 if (const auto *AT = RHS->getAs<AutoType>()) { 10304 if (AT->isGNUAutoType()) 10305 return LHS; 10306 } 10307 return {}; 10308 } 10309 10310 // The canonical type classes match. 10311 switch (LHSClass) { 10312 #define TYPE(Class, Base) 10313 #define ABSTRACT_TYPE(Class, Base) 10314 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 10315 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 10316 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 10317 #include "clang/AST/TypeNodes.inc" 10318 llvm_unreachable("Non-canonical and dependent types shouldn't get here"); 10319 10320 case Type::Auto: 10321 case Type::DeducedTemplateSpecialization: 10322 case Type::LValueReference: 10323 case Type::RValueReference: 10324 case Type::MemberPointer: 10325 llvm_unreachable("C++ should never be in mergeTypes"); 10326 10327 case Type::ObjCInterface: 10328 case Type::IncompleteArray: 10329 case Type::VariableArray: 10330 case Type::FunctionProto: 10331 case Type::ExtVector: 10332 llvm_unreachable("Types are eliminated above"); 10333 10334 case Type::Pointer: 10335 { 10336 // Merge two pointer types, while trying to preserve typedef info 10337 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType(); 10338 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType(); 10339 if (Unqualified) { 10340 LHSPointee = LHSPointee.getUnqualifiedType(); 10341 RHSPointee = RHSPointee.getUnqualifiedType(); 10342 } 10343 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false, 10344 Unqualified); 10345 if (ResultType.isNull()) 10346 return {}; 10347 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 10348 return LHS; 10349 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 10350 return RHS; 10351 return getPointerType(ResultType); 10352 } 10353 case Type::BlockPointer: 10354 { 10355 // Merge two block pointer types, while trying to preserve typedef info 10356 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType(); 10357 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType(); 10358 if (Unqualified) { 10359 LHSPointee = LHSPointee.getUnqualifiedType(); 10360 RHSPointee = RHSPointee.getUnqualifiedType(); 10361 } 10362 if (getLangOpts().OpenCL) { 10363 Qualifiers LHSPteeQual = LHSPointee.getQualifiers(); 10364 Qualifiers RHSPteeQual = RHSPointee.getQualifiers(); 10365 // Blocks can't be an expression in a ternary operator (OpenCL v2.0 10366 // 6.12.5) thus the following check is asymmetric. 10367 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual)) 10368 return {}; 10369 LHSPteeQual.removeAddressSpace(); 10370 RHSPteeQual.removeAddressSpace(); 10371 LHSPointee = 10372 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue()); 10373 RHSPointee = 10374 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue()); 10375 } 10376 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer, 10377 Unqualified); 10378 if (ResultType.isNull()) 10379 return {}; 10380 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 10381 return LHS; 10382 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 10383 return RHS; 10384 return getBlockPointerType(ResultType); 10385 } 10386 case Type::Atomic: 10387 { 10388 // Merge two pointer types, while trying to preserve typedef info 10389 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType(); 10390 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType(); 10391 if (Unqualified) { 10392 LHSValue = LHSValue.getUnqualifiedType(); 10393 RHSValue = RHSValue.getUnqualifiedType(); 10394 } 10395 QualType ResultType = mergeTypes(LHSValue, RHSValue, false, 10396 Unqualified); 10397 if (ResultType.isNull()) 10398 return {}; 10399 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType)) 10400 return LHS; 10401 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType)) 10402 return RHS; 10403 return getAtomicType(ResultType); 10404 } 10405 case Type::ConstantArray: 10406 { 10407 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS); 10408 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS); 10409 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize()) 10410 return {}; 10411 10412 QualType LHSElem = getAsArrayType(LHS)->getElementType(); 10413 QualType RHSElem = getAsArrayType(RHS)->getElementType(); 10414 if (Unqualified) { 10415 LHSElem = LHSElem.getUnqualifiedType(); 10416 RHSElem = RHSElem.getUnqualifiedType(); 10417 } 10418 10419 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified); 10420 if (ResultType.isNull()) 10421 return {}; 10422 10423 const VariableArrayType* LVAT = getAsVariableArrayType(LHS); 10424 const VariableArrayType* RVAT = getAsVariableArrayType(RHS); 10425 10426 // If either side is a variable array, and both are complete, check whether 10427 // the current dimension is definite. 10428 if (LVAT || RVAT) { 10429 auto SizeFetch = [this](const VariableArrayType* VAT, 10430 const ConstantArrayType* CAT) 10431 -> std::pair<bool,llvm::APInt> { 10432 if (VAT) { 10433 Optional<llvm::APSInt> TheInt; 10434 Expr *E = VAT->getSizeExpr(); 10435 if (E && (TheInt = E->getIntegerConstantExpr(*this))) 10436 return std::make_pair(true, *TheInt); 10437 return std::make_pair(false, llvm::APSInt()); 10438 } 10439 if (CAT) 10440 return std::make_pair(true, CAT->getSize()); 10441 return std::make_pair(false, llvm::APInt()); 10442 }; 10443 10444 bool HaveLSize, HaveRSize; 10445 llvm::APInt LSize, RSize; 10446 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT); 10447 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT); 10448 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize)) 10449 return {}; // Definite, but unequal, array dimension 10450 } 10451 10452 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 10453 return LHS; 10454 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 10455 return RHS; 10456 if (LCAT) 10457 return getConstantArrayType(ResultType, LCAT->getSize(), 10458 LCAT->getSizeExpr(), 10459 ArrayType::ArraySizeModifier(), 0); 10460 if (RCAT) 10461 return getConstantArrayType(ResultType, RCAT->getSize(), 10462 RCAT->getSizeExpr(), 10463 ArrayType::ArraySizeModifier(), 0); 10464 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 10465 return LHS; 10466 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 10467 return RHS; 10468 if (LVAT) { 10469 // FIXME: This isn't correct! But tricky to implement because 10470 // the array's size has to be the size of LHS, but the type 10471 // has to be different. 10472 return LHS; 10473 } 10474 if (RVAT) { 10475 // FIXME: This isn't correct! But tricky to implement because 10476 // the array's size has to be the size of RHS, but the type 10477 // has to be different. 10478 return RHS; 10479 } 10480 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS; 10481 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS; 10482 return getIncompleteArrayType(ResultType, 10483 ArrayType::ArraySizeModifier(), 0); 10484 } 10485 case Type::FunctionNoProto: 10486 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified); 10487 case Type::Record: 10488 case Type::Enum: 10489 return {}; 10490 case Type::Builtin: 10491 // Only exactly equal builtin types are compatible, which is tested above. 10492 return {}; 10493 case Type::Complex: 10494 // Distinct complex types are incompatible. 10495 return {}; 10496 case Type::Vector: 10497 // FIXME: The merged type should be an ExtVector! 10498 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(), 10499 RHSCan->castAs<VectorType>())) 10500 return LHS; 10501 return {}; 10502 case Type::ConstantMatrix: 10503 if (areCompatMatrixTypes(LHSCan->castAs<ConstantMatrixType>(), 10504 RHSCan->castAs<ConstantMatrixType>())) 10505 return LHS; 10506 return {}; 10507 case Type::ObjCObject: { 10508 // Check if the types are assignment compatible. 10509 // FIXME: This should be type compatibility, e.g. whether 10510 // "LHS x; RHS x;" at global scope is legal. 10511 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectType>(), 10512 RHS->castAs<ObjCObjectType>())) 10513 return LHS; 10514 return {}; 10515 } 10516 case Type::ObjCObjectPointer: 10517 if (OfBlockPointer) { 10518 if (canAssignObjCInterfacesInBlockPointer( 10519 LHS->castAs<ObjCObjectPointerType>(), 10520 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType)) 10521 return LHS; 10522 return {}; 10523 } 10524 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectPointerType>(), 10525 RHS->castAs<ObjCObjectPointerType>())) 10526 return LHS; 10527 return {}; 10528 case Type::Pipe: 10529 assert(LHS != RHS && 10530 "Equivalent pipe types should have already been handled!"); 10531 return {}; 10532 case Type::BitInt: { 10533 // Merge two bit-precise int types, while trying to preserve typedef info. 10534 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned(); 10535 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned(); 10536 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits(); 10537 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits(); 10538 10539 // Like unsigned/int, shouldn't have a type if they don't match. 10540 if (LHSUnsigned != RHSUnsigned) 10541 return {}; 10542 10543 if (LHSBits != RHSBits) 10544 return {}; 10545 return LHS; 10546 } 10547 } 10548 10549 llvm_unreachable("Invalid Type::Class!"); 10550 } 10551 10552 bool ASTContext::mergeExtParameterInfo( 10553 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType, 10554 bool &CanUseFirst, bool &CanUseSecond, 10555 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) { 10556 assert(NewParamInfos.empty() && "param info list not empty"); 10557 CanUseFirst = CanUseSecond = true; 10558 bool FirstHasInfo = FirstFnType->hasExtParameterInfos(); 10559 bool SecondHasInfo = SecondFnType->hasExtParameterInfos(); 10560 10561 // Fast path: if the first type doesn't have ext parameter infos, 10562 // we match if and only if the second type also doesn't have them. 10563 if (!FirstHasInfo && !SecondHasInfo) 10564 return true; 10565 10566 bool NeedParamInfo = false; 10567 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size() 10568 : SecondFnType->getExtParameterInfos().size(); 10569 10570 for (size_t I = 0; I < E; ++I) { 10571 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam; 10572 if (FirstHasInfo) 10573 FirstParam = FirstFnType->getExtParameterInfo(I); 10574 if (SecondHasInfo) 10575 SecondParam = SecondFnType->getExtParameterInfo(I); 10576 10577 // Cannot merge unless everything except the noescape flag matches. 10578 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false)) 10579 return false; 10580 10581 bool FirstNoEscape = FirstParam.isNoEscape(); 10582 bool SecondNoEscape = SecondParam.isNoEscape(); 10583 bool IsNoEscape = FirstNoEscape && SecondNoEscape; 10584 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape)); 10585 if (NewParamInfos.back().getOpaqueValue()) 10586 NeedParamInfo = true; 10587 if (FirstNoEscape != IsNoEscape) 10588 CanUseFirst = false; 10589 if (SecondNoEscape != IsNoEscape) 10590 CanUseSecond = false; 10591 } 10592 10593 if (!NeedParamInfo) 10594 NewParamInfos.clear(); 10595 10596 return true; 10597 } 10598 10599 void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) { 10600 ObjCLayouts[CD] = nullptr; 10601 } 10602 10603 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 10604 /// 'RHS' attributes and returns the merged version; including for function 10605 /// return types. 10606 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) { 10607 QualType LHSCan = getCanonicalType(LHS), 10608 RHSCan = getCanonicalType(RHS); 10609 // If two types are identical, they are compatible. 10610 if (LHSCan == RHSCan) 10611 return LHS; 10612 if (RHSCan->isFunctionType()) { 10613 if (!LHSCan->isFunctionType()) 10614 return {}; 10615 QualType OldReturnType = 10616 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType(); 10617 QualType NewReturnType = 10618 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType(); 10619 QualType ResReturnType = 10620 mergeObjCGCQualifiers(NewReturnType, OldReturnType); 10621 if (ResReturnType.isNull()) 10622 return {}; 10623 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) { 10624 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo(); 10625 // In either case, use OldReturnType to build the new function type. 10626 const auto *F = LHS->castAs<FunctionType>(); 10627 if (const auto *FPT = cast<FunctionProtoType>(F)) { 10628 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10629 EPI.ExtInfo = getFunctionExtInfo(LHS); 10630 QualType ResultType = 10631 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI); 10632 return ResultType; 10633 } 10634 } 10635 return {}; 10636 } 10637 10638 // If the qualifiers are different, the types can still be merged. 10639 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 10640 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 10641 if (LQuals != RQuals) { 10642 // If any of these qualifiers are different, we have a type mismatch. 10643 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 10644 LQuals.getAddressSpace() != RQuals.getAddressSpace()) 10645 return {}; 10646 10647 // Exactly one GC qualifier difference is allowed: __strong is 10648 // okay if the other type has no GC qualifier but is an Objective 10649 // C object pointer (i.e. implicitly strong by default). We fix 10650 // this by pretending that the unqualified type was actually 10651 // qualified __strong. 10652 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 10653 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 10654 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 10655 10656 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 10657 return {}; 10658 10659 if (GC_L == Qualifiers::Strong) 10660 return LHS; 10661 if (GC_R == Qualifiers::Strong) 10662 return RHS; 10663 return {}; 10664 } 10665 10666 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) { 10667 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType(); 10668 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType(); 10669 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT); 10670 if (ResQT == LHSBaseQT) 10671 return LHS; 10672 if (ResQT == RHSBaseQT) 10673 return RHS; 10674 } 10675 return {}; 10676 } 10677 10678 //===----------------------------------------------------------------------===// 10679 // Integer Predicates 10680 //===----------------------------------------------------------------------===// 10681 10682 unsigned ASTContext::getIntWidth(QualType T) const { 10683 if (const auto *ET = T->getAs<EnumType>()) 10684 T = ET->getDecl()->getIntegerType(); 10685 if (T->isBooleanType()) 10686 return 1; 10687 if (const auto *EIT = T->getAs<BitIntType>()) 10688 return EIT->getNumBits(); 10689 // For builtin types, just use the standard type sizing method 10690 return (unsigned)getTypeSize(T); 10691 } 10692 10693 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const { 10694 assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) && 10695 "Unexpected type"); 10696 10697 // Turn <4 x signed int> -> <4 x unsigned int> 10698 if (const auto *VTy = T->getAs<VectorType>()) 10699 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()), 10700 VTy->getNumElements(), VTy->getVectorKind()); 10701 10702 // For _BitInt, return an unsigned _BitInt with same width. 10703 if (const auto *EITy = T->getAs<BitIntType>()) 10704 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits()); 10705 10706 // For enums, get the underlying integer type of the enum, and let the general 10707 // integer type signchanging code handle it. 10708 if (const auto *ETy = T->getAs<EnumType>()) 10709 T = ETy->getDecl()->getIntegerType(); 10710 10711 switch (T->castAs<BuiltinType>()->getKind()) { 10712 case BuiltinType::Char_S: 10713 case BuiltinType::SChar: 10714 return UnsignedCharTy; 10715 case BuiltinType::Short: 10716 return UnsignedShortTy; 10717 case BuiltinType::Int: 10718 return UnsignedIntTy; 10719 case BuiltinType::Long: 10720 return UnsignedLongTy; 10721 case BuiltinType::LongLong: 10722 return UnsignedLongLongTy; 10723 case BuiltinType::Int128: 10724 return UnsignedInt128Ty; 10725 // wchar_t is special. It is either signed or not, but when it's signed, 10726 // there's no matching "unsigned wchar_t". Therefore we return the unsigned 10727 // version of it's underlying type instead. 10728 case BuiltinType::WChar_S: 10729 return getUnsignedWCharType(); 10730 10731 case BuiltinType::ShortAccum: 10732 return UnsignedShortAccumTy; 10733 case BuiltinType::Accum: 10734 return UnsignedAccumTy; 10735 case BuiltinType::LongAccum: 10736 return UnsignedLongAccumTy; 10737 case BuiltinType::SatShortAccum: 10738 return SatUnsignedShortAccumTy; 10739 case BuiltinType::SatAccum: 10740 return SatUnsignedAccumTy; 10741 case BuiltinType::SatLongAccum: 10742 return SatUnsignedLongAccumTy; 10743 case BuiltinType::ShortFract: 10744 return UnsignedShortFractTy; 10745 case BuiltinType::Fract: 10746 return UnsignedFractTy; 10747 case BuiltinType::LongFract: 10748 return UnsignedLongFractTy; 10749 case BuiltinType::SatShortFract: 10750 return SatUnsignedShortFractTy; 10751 case BuiltinType::SatFract: 10752 return SatUnsignedFractTy; 10753 case BuiltinType::SatLongFract: 10754 return SatUnsignedLongFractTy; 10755 default: 10756 llvm_unreachable("Unexpected signed integer or fixed point type"); 10757 } 10758 } 10759 10760 QualType ASTContext::getCorrespondingSignedType(QualType T) const { 10761 assert((T->hasUnsignedIntegerRepresentation() || 10762 T->isUnsignedFixedPointType()) && 10763 "Unexpected type"); 10764 10765 // Turn <4 x unsigned int> -> <4 x signed int> 10766 if (const auto *VTy = T->getAs<VectorType>()) 10767 return getVectorType(getCorrespondingSignedType(VTy->getElementType()), 10768 VTy->getNumElements(), VTy->getVectorKind()); 10769 10770 // For _BitInt, return a signed _BitInt with same width. 10771 if (const auto *EITy = T->getAs<BitIntType>()) 10772 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits()); 10773 10774 // For enums, get the underlying integer type of the enum, and let the general 10775 // integer type signchanging code handle it. 10776 if (const auto *ETy = T->getAs<EnumType>()) 10777 T = ETy->getDecl()->getIntegerType(); 10778 10779 switch (T->castAs<BuiltinType>()->getKind()) { 10780 case BuiltinType::Char_U: 10781 case BuiltinType::UChar: 10782 return SignedCharTy; 10783 case BuiltinType::UShort: 10784 return ShortTy; 10785 case BuiltinType::UInt: 10786 return IntTy; 10787 case BuiltinType::ULong: 10788 return LongTy; 10789 case BuiltinType::ULongLong: 10790 return LongLongTy; 10791 case BuiltinType::UInt128: 10792 return Int128Ty; 10793 // wchar_t is special. It is either unsigned or not, but when it's unsigned, 10794 // there's no matching "signed wchar_t". Therefore we return the signed 10795 // version of it's underlying type instead. 10796 case BuiltinType::WChar_U: 10797 return getSignedWCharType(); 10798 10799 case BuiltinType::UShortAccum: 10800 return ShortAccumTy; 10801 case BuiltinType::UAccum: 10802 return AccumTy; 10803 case BuiltinType::ULongAccum: 10804 return LongAccumTy; 10805 case BuiltinType::SatUShortAccum: 10806 return SatShortAccumTy; 10807 case BuiltinType::SatUAccum: 10808 return SatAccumTy; 10809 case BuiltinType::SatULongAccum: 10810 return SatLongAccumTy; 10811 case BuiltinType::UShortFract: 10812 return ShortFractTy; 10813 case BuiltinType::UFract: 10814 return FractTy; 10815 case BuiltinType::ULongFract: 10816 return LongFractTy; 10817 case BuiltinType::SatUShortFract: 10818 return SatShortFractTy; 10819 case BuiltinType::SatUFract: 10820 return SatFractTy; 10821 case BuiltinType::SatULongFract: 10822 return SatLongFractTy; 10823 default: 10824 llvm_unreachable("Unexpected unsigned integer or fixed point type"); 10825 } 10826 } 10827 10828 ASTMutationListener::~ASTMutationListener() = default; 10829 10830 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD, 10831 QualType ReturnType) {} 10832 10833 //===----------------------------------------------------------------------===// 10834 // Builtin Type Computation 10835 //===----------------------------------------------------------------------===// 10836 10837 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the 10838 /// pointer over the consumed characters. This returns the resultant type. If 10839 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic 10840 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of 10841 /// a vector of "i*". 10842 /// 10843 /// RequiresICE is filled in on return to indicate whether the value is required 10844 /// to be an Integer Constant Expression. 10845 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, 10846 ASTContext::GetBuiltinTypeError &Error, 10847 bool &RequiresICE, 10848 bool AllowTypeModifiers) { 10849 // Modifiers. 10850 int HowLong = 0; 10851 bool Signed = false, Unsigned = false; 10852 RequiresICE = false; 10853 10854 // Read the prefixed modifiers first. 10855 bool Done = false; 10856 #ifndef NDEBUG 10857 bool IsSpecial = false; 10858 #endif 10859 while (!Done) { 10860 switch (*Str++) { 10861 default: Done = true; --Str; break; 10862 case 'I': 10863 RequiresICE = true; 10864 break; 10865 case 'S': 10866 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!"); 10867 assert(!Signed && "Can't use 'S' modifier multiple times!"); 10868 Signed = true; 10869 break; 10870 case 'U': 10871 assert(!Signed && "Can't use both 'S' and 'U' modifiers!"); 10872 assert(!Unsigned && "Can't use 'U' modifier multiple times!"); 10873 Unsigned = true; 10874 break; 10875 case 'L': 10876 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers"); 10877 assert(HowLong <= 2 && "Can't have LLLL modifier"); 10878 ++HowLong; 10879 break; 10880 case 'N': 10881 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise. 10882 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10883 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!"); 10884 #ifndef NDEBUG 10885 IsSpecial = true; 10886 #endif 10887 if (Context.getTargetInfo().getLongWidth() == 32) 10888 ++HowLong; 10889 break; 10890 case 'W': 10891 // This modifier represents int64 type. 10892 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10893 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!"); 10894 #ifndef NDEBUG 10895 IsSpecial = true; 10896 #endif 10897 switch (Context.getTargetInfo().getInt64Type()) { 10898 default: 10899 llvm_unreachable("Unexpected integer type"); 10900 case TargetInfo::SignedLong: 10901 HowLong = 1; 10902 break; 10903 case TargetInfo::SignedLongLong: 10904 HowLong = 2; 10905 break; 10906 } 10907 break; 10908 case 'Z': 10909 // This modifier represents int32 type. 10910 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10911 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!"); 10912 #ifndef NDEBUG 10913 IsSpecial = true; 10914 #endif 10915 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) { 10916 default: 10917 llvm_unreachable("Unexpected integer type"); 10918 case TargetInfo::SignedInt: 10919 HowLong = 0; 10920 break; 10921 case TargetInfo::SignedLong: 10922 HowLong = 1; 10923 break; 10924 case TargetInfo::SignedLongLong: 10925 HowLong = 2; 10926 break; 10927 } 10928 break; 10929 case 'O': 10930 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10931 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!"); 10932 #ifndef NDEBUG 10933 IsSpecial = true; 10934 #endif 10935 if (Context.getLangOpts().OpenCL) 10936 HowLong = 1; 10937 else 10938 HowLong = 2; 10939 break; 10940 } 10941 } 10942 10943 QualType Type; 10944 10945 // Read the base type. 10946 switch (*Str++) { 10947 default: llvm_unreachable("Unknown builtin type letter!"); 10948 case 'x': 10949 assert(HowLong == 0 && !Signed && !Unsigned && 10950 "Bad modifiers used with 'x'!"); 10951 Type = Context.Float16Ty; 10952 break; 10953 case 'y': 10954 assert(HowLong == 0 && !Signed && !Unsigned && 10955 "Bad modifiers used with 'y'!"); 10956 Type = Context.BFloat16Ty; 10957 break; 10958 case 'v': 10959 assert(HowLong == 0 && !Signed && !Unsigned && 10960 "Bad modifiers used with 'v'!"); 10961 Type = Context.VoidTy; 10962 break; 10963 case 'h': 10964 assert(HowLong == 0 && !Signed && !Unsigned && 10965 "Bad modifiers used with 'h'!"); 10966 Type = Context.HalfTy; 10967 break; 10968 case 'f': 10969 assert(HowLong == 0 && !Signed && !Unsigned && 10970 "Bad modifiers used with 'f'!"); 10971 Type = Context.FloatTy; 10972 break; 10973 case 'd': 10974 assert(HowLong < 3 && !Signed && !Unsigned && 10975 "Bad modifiers used with 'd'!"); 10976 if (HowLong == 1) 10977 Type = Context.LongDoubleTy; 10978 else if (HowLong == 2) 10979 Type = Context.Float128Ty; 10980 else 10981 Type = Context.DoubleTy; 10982 break; 10983 case 's': 10984 assert(HowLong == 0 && "Bad modifiers used with 's'!"); 10985 if (Unsigned) 10986 Type = Context.UnsignedShortTy; 10987 else 10988 Type = Context.ShortTy; 10989 break; 10990 case 'i': 10991 if (HowLong == 3) 10992 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty; 10993 else if (HowLong == 2) 10994 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy; 10995 else if (HowLong == 1) 10996 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy; 10997 else 10998 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy; 10999 break; 11000 case 'c': 11001 assert(HowLong == 0 && "Bad modifiers used with 'c'!"); 11002 if (Signed) 11003 Type = Context.SignedCharTy; 11004 else if (Unsigned) 11005 Type = Context.UnsignedCharTy; 11006 else 11007 Type = Context.CharTy; 11008 break; 11009 case 'b': // boolean 11010 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!"); 11011 Type = Context.BoolTy; 11012 break; 11013 case 'z': // size_t. 11014 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!"); 11015 Type = Context.getSizeType(); 11016 break; 11017 case 'w': // wchar_t. 11018 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!"); 11019 Type = Context.getWideCharType(); 11020 break; 11021 case 'F': 11022 Type = Context.getCFConstantStringType(); 11023 break; 11024 case 'G': 11025 Type = Context.getObjCIdType(); 11026 break; 11027 case 'H': 11028 Type = Context.getObjCSelType(); 11029 break; 11030 case 'M': 11031 Type = Context.getObjCSuperType(); 11032 break; 11033 case 'a': 11034 Type = Context.getBuiltinVaListType(); 11035 assert(!Type.isNull() && "builtin va list type not initialized!"); 11036 break; 11037 case 'A': 11038 // This is a "reference" to a va_list; however, what exactly 11039 // this means depends on how va_list is defined. There are two 11040 // different kinds of va_list: ones passed by value, and ones 11041 // passed by reference. An example of a by-value va_list is 11042 // x86, where va_list is a char*. An example of by-ref va_list 11043 // is x86-64, where va_list is a __va_list_tag[1]. For x86, 11044 // we want this argument to be a char*&; for x86-64, we want 11045 // it to be a __va_list_tag*. 11046 Type = Context.getBuiltinVaListType(); 11047 assert(!Type.isNull() && "builtin va list type not initialized!"); 11048 if (Type->isArrayType()) 11049 Type = Context.getArrayDecayedType(Type); 11050 else 11051 Type = Context.getLValueReferenceType(Type); 11052 break; 11053 case 'q': { 11054 char *End; 11055 unsigned NumElements = strtoul(Str, &End, 10); 11056 assert(End != Str && "Missing vector size"); 11057 Str = End; 11058 11059 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 11060 RequiresICE, false); 11061 assert(!RequiresICE && "Can't require vector ICE"); 11062 11063 Type = Context.getScalableVectorType(ElementType, NumElements); 11064 break; 11065 } 11066 case 'V': { 11067 char *End; 11068 unsigned NumElements = strtoul(Str, &End, 10); 11069 assert(End != Str && "Missing vector size"); 11070 Str = End; 11071 11072 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 11073 RequiresICE, false); 11074 assert(!RequiresICE && "Can't require vector ICE"); 11075 11076 // TODO: No way to make AltiVec vectors in builtins yet. 11077 Type = Context.getVectorType(ElementType, NumElements, 11078 VectorType::GenericVector); 11079 break; 11080 } 11081 case 'E': { 11082 char *End; 11083 11084 unsigned NumElements = strtoul(Str, &End, 10); 11085 assert(End != Str && "Missing vector size"); 11086 11087 Str = End; 11088 11089 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 11090 false); 11091 Type = Context.getExtVectorType(ElementType, NumElements); 11092 break; 11093 } 11094 case 'X': { 11095 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 11096 false); 11097 assert(!RequiresICE && "Can't require complex ICE"); 11098 Type = Context.getComplexType(ElementType); 11099 break; 11100 } 11101 case 'Y': 11102 Type = Context.getPointerDiffType(); 11103 break; 11104 case 'P': 11105 Type = Context.getFILEType(); 11106 if (Type.isNull()) { 11107 Error = ASTContext::GE_Missing_stdio; 11108 return {}; 11109 } 11110 break; 11111 case 'J': 11112 if (Signed) 11113 Type = Context.getsigjmp_bufType(); 11114 else 11115 Type = Context.getjmp_bufType(); 11116 11117 if (Type.isNull()) { 11118 Error = ASTContext::GE_Missing_setjmp; 11119 return {}; 11120 } 11121 break; 11122 case 'K': 11123 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!"); 11124 Type = Context.getucontext_tType(); 11125 11126 if (Type.isNull()) { 11127 Error = ASTContext::GE_Missing_ucontext; 11128 return {}; 11129 } 11130 break; 11131 case 'p': 11132 Type = Context.getProcessIDType(); 11133 break; 11134 } 11135 11136 // If there are modifiers and if we're allowed to parse them, go for it. 11137 Done = !AllowTypeModifiers; 11138 while (!Done) { 11139 switch (char c = *Str++) { 11140 default: Done = true; --Str; break; 11141 case '*': 11142 case '&': { 11143 // Both pointers and references can have their pointee types 11144 // qualified with an address space. 11145 char *End; 11146 unsigned AddrSpace = strtoul(Str, &End, 10); 11147 if (End != Str) { 11148 // Note AddrSpace == 0 is not the same as an unspecified address space. 11149 Type = Context.getAddrSpaceQualType( 11150 Type, 11151 Context.getLangASForBuiltinAddressSpace(AddrSpace)); 11152 Str = End; 11153 } 11154 if (c == '*') 11155 Type = Context.getPointerType(Type); 11156 else 11157 Type = Context.getLValueReferenceType(Type); 11158 break; 11159 } 11160 // FIXME: There's no way to have a built-in with an rvalue ref arg. 11161 case 'C': 11162 Type = Type.withConst(); 11163 break; 11164 case 'D': 11165 Type = Context.getVolatileType(Type); 11166 break; 11167 case 'R': 11168 Type = Type.withRestrict(); 11169 break; 11170 } 11171 } 11172 11173 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) && 11174 "Integer constant 'I' type must be an integer"); 11175 11176 return Type; 11177 } 11178 11179 // On some targets such as PowerPC, some of the builtins are defined with custom 11180 // type descriptors for target-dependent types. These descriptors are decoded in 11181 // other functions, but it may be useful to be able to fall back to default 11182 // descriptor decoding to define builtins mixing target-dependent and target- 11183 // independent types. This function allows decoding one type descriptor with 11184 // default decoding. 11185 QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context, 11186 GetBuiltinTypeError &Error, bool &RequireICE, 11187 bool AllowTypeModifiers) const { 11188 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers); 11189 } 11190 11191 /// GetBuiltinType - Return the type for the specified builtin. 11192 QualType ASTContext::GetBuiltinType(unsigned Id, 11193 GetBuiltinTypeError &Error, 11194 unsigned *IntegerConstantArgs) const { 11195 const char *TypeStr = BuiltinInfo.getTypeString(Id); 11196 if (TypeStr[0] == '\0') { 11197 Error = GE_Missing_type; 11198 return {}; 11199 } 11200 11201 SmallVector<QualType, 8> ArgTypes; 11202 11203 bool RequiresICE = false; 11204 Error = GE_None; 11205 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error, 11206 RequiresICE, true); 11207 if (Error != GE_None) 11208 return {}; 11209 11210 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE"); 11211 11212 while (TypeStr[0] && TypeStr[0] != '.') { 11213 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true); 11214 if (Error != GE_None) 11215 return {}; 11216 11217 // If this argument is required to be an IntegerConstantExpression and the 11218 // caller cares, fill in the bitmask we return. 11219 if (RequiresICE && IntegerConstantArgs) 11220 *IntegerConstantArgs |= 1 << ArgTypes.size(); 11221 11222 // Do array -> pointer decay. The builtin should use the decayed type. 11223 if (Ty->isArrayType()) 11224 Ty = getArrayDecayedType(Ty); 11225 11226 ArgTypes.push_back(Ty); 11227 } 11228 11229 if (Id == Builtin::BI__GetExceptionInfo) 11230 return {}; 11231 11232 assert((TypeStr[0] != '.' || TypeStr[1] == 0) && 11233 "'.' should only occur at end of builtin type list!"); 11234 11235 bool Variadic = (TypeStr[0] == '.'); 11236 11237 FunctionType::ExtInfo EI(getDefaultCallingConvention( 11238 Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true)); 11239 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true); 11240 11241 11242 // We really shouldn't be making a no-proto type here. 11243 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes()) 11244 return getFunctionNoProtoType(ResType, EI); 11245 11246 FunctionProtoType::ExtProtoInfo EPI; 11247 EPI.ExtInfo = EI; 11248 EPI.Variadic = Variadic; 11249 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id)) 11250 EPI.ExceptionSpec.Type = 11251 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone; 11252 11253 return getFunctionType(ResType, ArgTypes, EPI); 11254 } 11255 11256 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, 11257 const FunctionDecl *FD) { 11258 if (!FD->isExternallyVisible()) 11259 return GVA_Internal; 11260 11261 // Non-user-provided functions get emitted as weak definitions with every 11262 // use, no matter whether they've been explicitly instantiated etc. 11263 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 11264 if (!MD->isUserProvided()) 11265 return GVA_DiscardableODR; 11266 11267 GVALinkage External; 11268 switch (FD->getTemplateSpecializationKind()) { 11269 case TSK_Undeclared: 11270 case TSK_ExplicitSpecialization: 11271 External = GVA_StrongExternal; 11272 break; 11273 11274 case TSK_ExplicitInstantiationDefinition: 11275 return GVA_StrongODR; 11276 11277 // C++11 [temp.explicit]p10: 11278 // [ Note: The intent is that an inline function that is the subject of 11279 // an explicit instantiation declaration will still be implicitly 11280 // instantiated when used so that the body can be considered for 11281 // inlining, but that no out-of-line copy of the inline function would be 11282 // generated in the translation unit. -- end note ] 11283 case TSK_ExplicitInstantiationDeclaration: 11284 return GVA_AvailableExternally; 11285 11286 case TSK_ImplicitInstantiation: 11287 External = GVA_DiscardableODR; 11288 break; 11289 } 11290 11291 if (!FD->isInlined()) 11292 return External; 11293 11294 if ((!Context.getLangOpts().CPlusPlus && 11295 !Context.getTargetInfo().getCXXABI().isMicrosoft() && 11296 !FD->hasAttr<DLLExportAttr>()) || 11297 FD->hasAttr<GNUInlineAttr>()) { 11298 // FIXME: This doesn't match gcc's behavior for dllexport inline functions. 11299 11300 // GNU or C99 inline semantics. Determine whether this symbol should be 11301 // externally visible. 11302 if (FD->isInlineDefinitionExternallyVisible()) 11303 return External; 11304 11305 // C99 inline semantics, where the symbol is not externally visible. 11306 return GVA_AvailableExternally; 11307 } 11308 11309 // Functions specified with extern and inline in -fms-compatibility mode 11310 // forcibly get emitted. While the body of the function cannot be later 11311 // replaced, the function definition cannot be discarded. 11312 if (FD->isMSExternInline()) 11313 return GVA_StrongODR; 11314 11315 return GVA_DiscardableODR; 11316 } 11317 11318 static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context, 11319 const Decl *D, GVALinkage L) { 11320 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx 11321 // dllexport/dllimport on inline functions. 11322 if (D->hasAttr<DLLImportAttr>()) { 11323 if (L == GVA_DiscardableODR || L == GVA_StrongODR) 11324 return GVA_AvailableExternally; 11325 } else if (D->hasAttr<DLLExportAttr>()) { 11326 if (L == GVA_DiscardableODR) 11327 return GVA_StrongODR; 11328 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) { 11329 // Device-side functions with __global__ attribute must always be 11330 // visible externally so they can be launched from host. 11331 if (D->hasAttr<CUDAGlobalAttr>() && 11332 (L == GVA_DiscardableODR || L == GVA_Internal)) 11333 return GVA_StrongODR; 11334 // Single source offloading languages like CUDA/HIP need to be able to 11335 // access static device variables from host code of the same compilation 11336 // unit. This is done by externalizing the static variable with a shared 11337 // name between the host and device compilation which is the same for the 11338 // same compilation unit whereas different among different compilation 11339 // units. 11340 if (Context.shouldExternalize(D)) 11341 return GVA_StrongExternal; 11342 } 11343 return L; 11344 } 11345 11346 /// Adjust the GVALinkage for a declaration based on what an external AST source 11347 /// knows about whether there can be other definitions of this declaration. 11348 static GVALinkage 11349 adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D, 11350 GVALinkage L) { 11351 ExternalASTSource *Source = Ctx.getExternalSource(); 11352 if (!Source) 11353 return L; 11354 11355 switch (Source->hasExternalDefinitions(D)) { 11356 case ExternalASTSource::EK_Never: 11357 // Other translation units rely on us to provide the definition. 11358 if (L == GVA_DiscardableODR) 11359 return GVA_StrongODR; 11360 break; 11361 11362 case ExternalASTSource::EK_Always: 11363 return GVA_AvailableExternally; 11364 11365 case ExternalASTSource::EK_ReplyHazy: 11366 break; 11367 } 11368 return L; 11369 } 11370 11371 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const { 11372 return adjustGVALinkageForExternalDefinitionKind(*this, FD, 11373 adjustGVALinkageForAttributes(*this, FD, 11374 basicGVALinkageForFunction(*this, FD))); 11375 } 11376 11377 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context, 11378 const VarDecl *VD) { 11379 if (!VD->isExternallyVisible()) 11380 return GVA_Internal; 11381 11382 if (VD->isStaticLocal()) { 11383 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod(); 11384 while (LexicalContext && !isa<FunctionDecl>(LexicalContext)) 11385 LexicalContext = LexicalContext->getLexicalParent(); 11386 11387 // ObjC Blocks can create local variables that don't have a FunctionDecl 11388 // LexicalContext. 11389 if (!LexicalContext) 11390 return GVA_DiscardableODR; 11391 11392 // Otherwise, let the static local variable inherit its linkage from the 11393 // nearest enclosing function. 11394 auto StaticLocalLinkage = 11395 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext)); 11396 11397 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must 11398 // be emitted in any object with references to the symbol for the object it 11399 // contains, whether inline or out-of-line." 11400 // Similar behavior is observed with MSVC. An alternative ABI could use 11401 // StrongODR/AvailableExternally to match the function, but none are 11402 // known/supported currently. 11403 if (StaticLocalLinkage == GVA_StrongODR || 11404 StaticLocalLinkage == GVA_AvailableExternally) 11405 return GVA_DiscardableODR; 11406 return StaticLocalLinkage; 11407 } 11408 11409 // MSVC treats in-class initialized static data members as definitions. 11410 // By giving them non-strong linkage, out-of-line definitions won't 11411 // cause link errors. 11412 if (Context.isMSStaticDataMemberInlineDefinition(VD)) 11413 return GVA_DiscardableODR; 11414 11415 // Most non-template variables have strong linkage; inline variables are 11416 // linkonce_odr or (occasionally, for compatibility) weak_odr. 11417 GVALinkage StrongLinkage; 11418 switch (Context.getInlineVariableDefinitionKind(VD)) { 11419 case ASTContext::InlineVariableDefinitionKind::None: 11420 StrongLinkage = GVA_StrongExternal; 11421 break; 11422 case ASTContext::InlineVariableDefinitionKind::Weak: 11423 case ASTContext::InlineVariableDefinitionKind::WeakUnknown: 11424 StrongLinkage = GVA_DiscardableODR; 11425 break; 11426 case ASTContext::InlineVariableDefinitionKind::Strong: 11427 StrongLinkage = GVA_StrongODR; 11428 break; 11429 } 11430 11431 switch (VD->getTemplateSpecializationKind()) { 11432 case TSK_Undeclared: 11433 return StrongLinkage; 11434 11435 case TSK_ExplicitSpecialization: 11436 return Context.getTargetInfo().getCXXABI().isMicrosoft() && 11437 VD->isStaticDataMember() 11438 ? GVA_StrongODR 11439 : StrongLinkage; 11440 11441 case TSK_ExplicitInstantiationDefinition: 11442 return GVA_StrongODR; 11443 11444 case TSK_ExplicitInstantiationDeclaration: 11445 return GVA_AvailableExternally; 11446 11447 case TSK_ImplicitInstantiation: 11448 return GVA_DiscardableODR; 11449 } 11450 11451 llvm_unreachable("Invalid Linkage!"); 11452 } 11453 11454 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) { 11455 return adjustGVALinkageForExternalDefinitionKind(*this, VD, 11456 adjustGVALinkageForAttributes(*this, VD, 11457 basicGVALinkageForVariable(*this, VD))); 11458 } 11459 11460 bool ASTContext::DeclMustBeEmitted(const Decl *D) { 11461 if (const auto *VD = dyn_cast<VarDecl>(D)) { 11462 if (!VD->isFileVarDecl()) 11463 return false; 11464 // Global named register variables (GNU extension) are never emitted. 11465 if (VD->getStorageClass() == SC_Register) 11466 return false; 11467 if (VD->getDescribedVarTemplate() || 11468 isa<VarTemplatePartialSpecializationDecl>(VD)) 11469 return false; 11470 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 11471 // We never need to emit an uninstantiated function template. 11472 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 11473 return false; 11474 } else if (isa<PragmaCommentDecl>(D)) 11475 return true; 11476 else if (isa<PragmaDetectMismatchDecl>(D)) 11477 return true; 11478 else if (isa<OMPRequiresDecl>(D)) 11479 return true; 11480 else if (isa<OMPThreadPrivateDecl>(D)) 11481 return !D->getDeclContext()->isDependentContext(); 11482 else if (isa<OMPAllocateDecl>(D)) 11483 return !D->getDeclContext()->isDependentContext(); 11484 else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D)) 11485 return !D->getDeclContext()->isDependentContext(); 11486 else if (isa<ImportDecl>(D)) 11487 return true; 11488 else 11489 return false; 11490 11491 // If this is a member of a class template, we do not need to emit it. 11492 if (D->getDeclContext()->isDependentContext()) 11493 return false; 11494 11495 // Weak references don't produce any output by themselves. 11496 if (D->hasAttr<WeakRefAttr>()) 11497 return false; 11498 11499 // Aliases and used decls are required. 11500 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>()) 11501 return true; 11502 11503 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 11504 // Forward declarations aren't required. 11505 if (!FD->doesThisDeclarationHaveABody()) 11506 return FD->doesDeclarationForceExternallyVisibleDefinition(); 11507 11508 // Constructors and destructors are required. 11509 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>()) 11510 return true; 11511 11512 // The key function for a class is required. This rule only comes 11513 // into play when inline functions can be key functions, though. 11514 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 11515 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 11516 const CXXRecordDecl *RD = MD->getParent(); 11517 if (MD->isOutOfLine() && RD->isDynamicClass()) { 11518 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD); 11519 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl()) 11520 return true; 11521 } 11522 } 11523 } 11524 11525 GVALinkage Linkage = GetGVALinkageForFunction(FD); 11526 11527 // static, static inline, always_inline, and extern inline functions can 11528 // always be deferred. Normal inline functions can be deferred in C99/C++. 11529 // Implicit template instantiations can also be deferred in C++. 11530 return !isDiscardableGVALinkage(Linkage); 11531 } 11532 11533 const auto *VD = cast<VarDecl>(D); 11534 assert(VD->isFileVarDecl() && "Expected file scoped var"); 11535 11536 // If the decl is marked as `declare target to`, it should be emitted for the 11537 // host and for the device. 11538 if (LangOpts.OpenMP && 11539 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 11540 return true; 11541 11542 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly && 11543 !isMSStaticDataMemberInlineDefinition(VD)) 11544 return false; 11545 11546 // Variables that can be needed in other TUs are required. 11547 auto Linkage = GetGVALinkageForVariable(VD); 11548 if (!isDiscardableGVALinkage(Linkage)) 11549 return true; 11550 11551 // We never need to emit a variable that is available in another TU. 11552 if (Linkage == GVA_AvailableExternally) 11553 return false; 11554 11555 // Variables that have destruction with side-effects are required. 11556 if (VD->needsDestruction(*this)) 11557 return true; 11558 11559 // Variables that have initialization with side-effects are required. 11560 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) && 11561 // We can get a value-dependent initializer during error recovery. 11562 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 11563 return true; 11564 11565 // Likewise, variables with tuple-like bindings are required if their 11566 // bindings have side-effects. 11567 if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) 11568 for (const auto *BD : DD->bindings()) 11569 if (const auto *BindingVD = BD->getHoldingVar()) 11570 if (DeclMustBeEmitted(BindingVD)) 11571 return true; 11572 11573 return false; 11574 } 11575 11576 void ASTContext::forEachMultiversionedFunctionVersion( 11577 const FunctionDecl *FD, 11578 llvm::function_ref<void(FunctionDecl *)> Pred) const { 11579 assert(FD->isMultiVersion() && "Only valid for multiversioned functions"); 11580 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls; 11581 FD = FD->getMostRecentDecl(); 11582 // FIXME: The order of traversal here matters and depends on the order of 11583 // lookup results, which happens to be (mostly) oldest-to-newest, but we 11584 // shouldn't rely on that. 11585 for (auto *CurDecl : 11586 FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) { 11587 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl(); 11588 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) && 11589 std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) { 11590 SeenDecls.insert(CurFD); 11591 Pred(CurFD); 11592 } 11593 } 11594 } 11595 11596 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic, 11597 bool IsCXXMethod, 11598 bool IsBuiltin) const { 11599 // Pass through to the C++ ABI object 11600 if (IsCXXMethod) 11601 return ABI->getDefaultMethodCallConv(IsVariadic); 11602 11603 // Builtins ignore user-specified default calling convention and remain the 11604 // Target's default calling convention. 11605 if (!IsBuiltin) { 11606 switch (LangOpts.getDefaultCallingConv()) { 11607 case LangOptions::DCC_None: 11608 break; 11609 case LangOptions::DCC_CDecl: 11610 return CC_C; 11611 case LangOptions::DCC_FastCall: 11612 if (getTargetInfo().hasFeature("sse2") && !IsVariadic) 11613 return CC_X86FastCall; 11614 break; 11615 case LangOptions::DCC_StdCall: 11616 if (!IsVariadic) 11617 return CC_X86StdCall; 11618 break; 11619 case LangOptions::DCC_VectorCall: 11620 // __vectorcall cannot be applied to variadic functions. 11621 if (!IsVariadic) 11622 return CC_X86VectorCall; 11623 break; 11624 case LangOptions::DCC_RegCall: 11625 // __regcall cannot be applied to variadic functions. 11626 if (!IsVariadic) 11627 return CC_X86RegCall; 11628 break; 11629 } 11630 } 11631 return Target->getDefaultCallingConv(); 11632 } 11633 11634 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const { 11635 // Pass through to the C++ ABI object 11636 return ABI->isNearlyEmpty(RD); 11637 } 11638 11639 VTableContextBase *ASTContext::getVTableContext() { 11640 if (!VTContext.get()) { 11641 auto ABI = Target->getCXXABI(); 11642 if (ABI.isMicrosoft()) 11643 VTContext.reset(new MicrosoftVTableContext(*this)); 11644 else { 11645 auto ComponentLayout = getLangOpts().RelativeCXXABIVTables 11646 ? ItaniumVTableContext::Relative 11647 : ItaniumVTableContext::Pointer; 11648 VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout)); 11649 } 11650 } 11651 return VTContext.get(); 11652 } 11653 11654 MangleContext *ASTContext::createMangleContext(const TargetInfo *T) { 11655 if (!T) 11656 T = Target; 11657 switch (T->getCXXABI().getKind()) { 11658 case TargetCXXABI::AppleARM64: 11659 case TargetCXXABI::Fuchsia: 11660 case TargetCXXABI::GenericAArch64: 11661 case TargetCXXABI::GenericItanium: 11662 case TargetCXXABI::GenericARM: 11663 case TargetCXXABI::GenericMIPS: 11664 case TargetCXXABI::iOS: 11665 case TargetCXXABI::WebAssembly: 11666 case TargetCXXABI::WatchOS: 11667 case TargetCXXABI::XL: 11668 return ItaniumMangleContext::create(*this, getDiagnostics()); 11669 case TargetCXXABI::Microsoft: 11670 return MicrosoftMangleContext::create(*this, getDiagnostics()); 11671 } 11672 llvm_unreachable("Unsupported ABI"); 11673 } 11674 11675 MangleContext *ASTContext::createDeviceMangleContext(const TargetInfo &T) { 11676 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft && 11677 "Device mangle context does not support Microsoft mangling."); 11678 switch (T.getCXXABI().getKind()) { 11679 case TargetCXXABI::AppleARM64: 11680 case TargetCXXABI::Fuchsia: 11681 case TargetCXXABI::GenericAArch64: 11682 case TargetCXXABI::GenericItanium: 11683 case TargetCXXABI::GenericARM: 11684 case TargetCXXABI::GenericMIPS: 11685 case TargetCXXABI::iOS: 11686 case TargetCXXABI::WebAssembly: 11687 case TargetCXXABI::WatchOS: 11688 case TargetCXXABI::XL: 11689 return ItaniumMangleContext::create( 11690 *this, getDiagnostics(), 11691 [](ASTContext &, const NamedDecl *ND) -> llvm::Optional<unsigned> { 11692 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) 11693 return RD->getDeviceLambdaManglingNumber(); 11694 return llvm::None; 11695 }, 11696 /*IsAux=*/true); 11697 case TargetCXXABI::Microsoft: 11698 return MicrosoftMangleContext::create(*this, getDiagnostics(), 11699 /*IsAux=*/true); 11700 } 11701 llvm_unreachable("Unsupported ABI"); 11702 } 11703 11704 CXXABI::~CXXABI() = default; 11705 11706 size_t ASTContext::getSideTableAllocatedMemory() const { 11707 return ASTRecordLayouts.getMemorySize() + 11708 llvm::capacity_in_bytes(ObjCLayouts) + 11709 llvm::capacity_in_bytes(KeyFunctions) + 11710 llvm::capacity_in_bytes(ObjCImpls) + 11711 llvm::capacity_in_bytes(BlockVarCopyInits) + 11712 llvm::capacity_in_bytes(DeclAttrs) + 11713 llvm::capacity_in_bytes(TemplateOrInstantiation) + 11714 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) + 11715 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) + 11716 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) + 11717 llvm::capacity_in_bytes(OverriddenMethods) + 11718 llvm::capacity_in_bytes(Types) + 11719 llvm::capacity_in_bytes(VariableArrayTypes); 11720 } 11721 11722 /// getIntTypeForBitwidth - 11723 /// sets integer QualTy according to specified details: 11724 /// bitwidth, signed/unsigned. 11725 /// Returns empty type if there is no appropriate target types. 11726 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth, 11727 unsigned Signed) const { 11728 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed); 11729 CanQualType QualTy = getFromTargetType(Ty); 11730 if (!QualTy && DestWidth == 128) 11731 return Signed ? Int128Ty : UnsignedInt128Ty; 11732 return QualTy; 11733 } 11734 11735 /// getRealTypeForBitwidth - 11736 /// sets floating point QualTy according to specified bitwidth. 11737 /// Returns empty type if there is no appropriate target types. 11738 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth, 11739 FloatModeKind ExplicitType) const { 11740 FloatModeKind Ty = 11741 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType); 11742 switch (Ty) { 11743 case FloatModeKind::Float: 11744 return FloatTy; 11745 case FloatModeKind::Double: 11746 return DoubleTy; 11747 case FloatModeKind::LongDouble: 11748 return LongDoubleTy; 11749 case FloatModeKind::Float128: 11750 return Float128Ty; 11751 case FloatModeKind::Ibm128: 11752 return Ibm128Ty; 11753 case FloatModeKind::NoFloat: 11754 return {}; 11755 } 11756 11757 llvm_unreachable("Unhandled TargetInfo::RealType value"); 11758 } 11759 11760 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) { 11761 if (Number > 1) 11762 MangleNumbers[ND] = Number; 11763 } 11764 11765 unsigned ASTContext::getManglingNumber(const NamedDecl *ND, 11766 bool ForAuxTarget) const { 11767 auto I = MangleNumbers.find(ND); 11768 unsigned Res = I != MangleNumbers.end() ? I->second : 1; 11769 // CUDA/HIP host compilation encodes host and device mangling numbers 11770 // as lower and upper half of 32 bit integer. 11771 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) { 11772 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF; 11773 } else { 11774 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling " 11775 "number for aux target"); 11776 } 11777 return Res > 1 ? Res : 1; 11778 } 11779 11780 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) { 11781 if (Number > 1) 11782 StaticLocalNumbers[VD] = Number; 11783 } 11784 11785 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const { 11786 auto I = StaticLocalNumbers.find(VD); 11787 return I != StaticLocalNumbers.end() ? I->second : 1; 11788 } 11789 11790 MangleNumberingContext & 11791 ASTContext::getManglingNumberContext(const DeclContext *DC) { 11792 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C. 11793 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC]; 11794 if (!MCtx) 11795 MCtx = createMangleNumberingContext(); 11796 return *MCtx; 11797 } 11798 11799 MangleNumberingContext & 11800 ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) { 11801 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C. 11802 std::unique_ptr<MangleNumberingContext> &MCtx = 11803 ExtraMangleNumberingContexts[D]; 11804 if (!MCtx) 11805 MCtx = createMangleNumberingContext(); 11806 return *MCtx; 11807 } 11808 11809 std::unique_ptr<MangleNumberingContext> 11810 ASTContext::createMangleNumberingContext() const { 11811 return ABI->createMangleNumberingContext(); 11812 } 11813 11814 const CXXConstructorDecl * 11815 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) { 11816 return ABI->getCopyConstructorForExceptionObject( 11817 cast<CXXRecordDecl>(RD->getFirstDecl())); 11818 } 11819 11820 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD, 11821 CXXConstructorDecl *CD) { 11822 return ABI->addCopyConstructorForExceptionObject( 11823 cast<CXXRecordDecl>(RD->getFirstDecl()), 11824 cast<CXXConstructorDecl>(CD->getFirstDecl())); 11825 } 11826 11827 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD, 11828 TypedefNameDecl *DD) { 11829 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD); 11830 } 11831 11832 TypedefNameDecl * 11833 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) { 11834 return ABI->getTypedefNameForUnnamedTagDecl(TD); 11835 } 11836 11837 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD, 11838 DeclaratorDecl *DD) { 11839 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD); 11840 } 11841 11842 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) { 11843 return ABI->getDeclaratorForUnnamedTagDecl(TD); 11844 } 11845 11846 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) { 11847 ParamIndices[D] = index; 11848 } 11849 11850 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const { 11851 ParameterIndexTable::const_iterator I = ParamIndices.find(D); 11852 assert(I != ParamIndices.end() && 11853 "ParmIndices lacks entry set by ParmVarDecl"); 11854 return I->second; 11855 } 11856 11857 QualType ASTContext::getStringLiteralArrayType(QualType EltTy, 11858 unsigned Length) const { 11859 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 11860 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 11861 EltTy = EltTy.withConst(); 11862 11863 EltTy = adjustStringLiteralBaseType(EltTy); 11864 11865 // Get an array type for the string, according to C99 6.4.5. This includes 11866 // the null terminator character. 11867 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr, 11868 ArrayType::Normal, /*IndexTypeQuals*/ 0); 11869 } 11870 11871 StringLiteral * 11872 ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const { 11873 StringLiteral *&Result = StringLiteralCache[Key]; 11874 if (!Result) 11875 Result = StringLiteral::Create( 11876 *this, Key, StringLiteral::Ascii, 11877 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()), 11878 SourceLocation()); 11879 return Result; 11880 } 11881 11882 MSGuidDecl * 11883 ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const { 11884 assert(MSGuidTagDecl && "building MS GUID without MS extensions?"); 11885 11886 llvm::FoldingSetNodeID ID; 11887 MSGuidDecl::Profile(ID, Parts); 11888 11889 void *InsertPos; 11890 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos)) 11891 return Existing; 11892 11893 QualType GUIDType = getMSGuidType().withConst(); 11894 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts); 11895 MSGuidDecls.InsertNode(New, InsertPos); 11896 return New; 11897 } 11898 11899 UnnamedGlobalConstantDecl * 11900 ASTContext::getUnnamedGlobalConstantDecl(QualType Ty, 11901 const APValue &APVal) const { 11902 llvm::FoldingSetNodeID ID; 11903 UnnamedGlobalConstantDecl::Profile(ID, Ty, APVal); 11904 11905 void *InsertPos; 11906 if (UnnamedGlobalConstantDecl *Existing = 11907 UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos)) 11908 return Existing; 11909 11910 UnnamedGlobalConstantDecl *New = 11911 UnnamedGlobalConstantDecl::Create(*this, Ty, APVal); 11912 UnnamedGlobalConstantDecls.InsertNode(New, InsertPos); 11913 return New; 11914 } 11915 11916 TemplateParamObjectDecl * 11917 ASTContext::getTemplateParamObjectDecl(QualType T, const APValue &V) const { 11918 assert(T->isRecordType() && "template param object of unexpected type"); 11919 11920 // C++ [temp.param]p8: 11921 // [...] a static storage duration object of type 'const T' [...] 11922 T.addConst(); 11923 11924 llvm::FoldingSetNodeID ID; 11925 TemplateParamObjectDecl::Profile(ID, T, V); 11926 11927 void *InsertPos; 11928 if (TemplateParamObjectDecl *Existing = 11929 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos)) 11930 return Existing; 11931 11932 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V); 11933 TemplateParamObjectDecls.InsertNode(New, InsertPos); 11934 return New; 11935 } 11936 11937 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const { 11938 const llvm::Triple &T = getTargetInfo().getTriple(); 11939 if (!T.isOSDarwin()) 11940 return false; 11941 11942 if (!(T.isiOS() && T.isOSVersionLT(7)) && 11943 !(T.isMacOSX() && T.isOSVersionLT(10, 9))) 11944 return false; 11945 11946 QualType AtomicTy = E->getPtr()->getType()->getPointeeType(); 11947 CharUnits sizeChars = getTypeSizeInChars(AtomicTy); 11948 uint64_t Size = sizeChars.getQuantity(); 11949 CharUnits alignChars = getTypeAlignInChars(AtomicTy); 11950 unsigned Align = alignChars.getQuantity(); 11951 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth(); 11952 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits); 11953 } 11954 11955 bool 11956 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, 11957 const ObjCMethodDecl *MethodImpl) { 11958 // No point trying to match an unavailable/deprecated mothod. 11959 if (MethodDecl->hasAttr<UnavailableAttr>() 11960 || MethodDecl->hasAttr<DeprecatedAttr>()) 11961 return false; 11962 if (MethodDecl->getObjCDeclQualifier() != 11963 MethodImpl->getObjCDeclQualifier()) 11964 return false; 11965 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType())) 11966 return false; 11967 11968 if (MethodDecl->param_size() != MethodImpl->param_size()) 11969 return false; 11970 11971 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(), 11972 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(), 11973 EF = MethodDecl->param_end(); 11974 IM != EM && IF != EF; ++IM, ++IF) { 11975 const ParmVarDecl *DeclVar = (*IF); 11976 const ParmVarDecl *ImplVar = (*IM); 11977 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier()) 11978 return false; 11979 if (!hasSameType(DeclVar->getType(), ImplVar->getType())) 11980 return false; 11981 } 11982 11983 return (MethodDecl->isVariadic() == MethodImpl->isVariadic()); 11984 } 11985 11986 uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const { 11987 LangAS AS; 11988 if (QT->getUnqualifiedDesugaredType()->isNullPtrType()) 11989 AS = LangAS::Default; 11990 else 11991 AS = QT->getPointeeType().getAddressSpace(); 11992 11993 return getTargetInfo().getNullPointerValue(AS); 11994 } 11995 11996 unsigned ASTContext::getTargetAddressSpace(QualType T) const { 11997 // Return the address space for the type. If the type is a 11998 // function type without an address space qualifier, the 11999 // program address space is used. Otherwise, the target picks 12000 // the best address space based on the type information 12001 return T->isFunctionType() && !T.hasAddressSpace() 12002 ? getTargetInfo().getProgramAddressSpace() 12003 : getTargetAddressSpace(T.getQualifiers()); 12004 } 12005 12006 unsigned ASTContext::getTargetAddressSpace(Qualifiers Q) const { 12007 return getTargetAddressSpace(Q.getAddressSpace()); 12008 } 12009 12010 unsigned ASTContext::getTargetAddressSpace(LangAS AS) const { 12011 if (isTargetAddressSpace(AS)) 12012 return toTargetAddressSpace(AS); 12013 else 12014 return (*AddrSpaceMap)[(unsigned)AS]; 12015 } 12016 12017 QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const { 12018 assert(Ty->isFixedPointType()); 12019 12020 if (Ty->isSaturatedFixedPointType()) return Ty; 12021 12022 switch (Ty->castAs<BuiltinType>()->getKind()) { 12023 default: 12024 llvm_unreachable("Not a fixed point type!"); 12025 case BuiltinType::ShortAccum: 12026 return SatShortAccumTy; 12027 case BuiltinType::Accum: 12028 return SatAccumTy; 12029 case BuiltinType::LongAccum: 12030 return SatLongAccumTy; 12031 case BuiltinType::UShortAccum: 12032 return SatUnsignedShortAccumTy; 12033 case BuiltinType::UAccum: 12034 return SatUnsignedAccumTy; 12035 case BuiltinType::ULongAccum: 12036 return SatUnsignedLongAccumTy; 12037 case BuiltinType::ShortFract: 12038 return SatShortFractTy; 12039 case BuiltinType::Fract: 12040 return SatFractTy; 12041 case BuiltinType::LongFract: 12042 return SatLongFractTy; 12043 case BuiltinType::UShortFract: 12044 return SatUnsignedShortFractTy; 12045 case BuiltinType::UFract: 12046 return SatUnsignedFractTy; 12047 case BuiltinType::ULongFract: 12048 return SatUnsignedLongFractTy; 12049 } 12050 } 12051 12052 LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const { 12053 if (LangOpts.OpenCL) 12054 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS); 12055 12056 if (LangOpts.CUDA) 12057 return getTargetInfo().getCUDABuiltinAddressSpace(AS); 12058 12059 return getLangASFromTargetAS(AS); 12060 } 12061 12062 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that 12063 // doesn't include ASTContext.h 12064 template 12065 clang::LazyGenerationalUpdatePtr< 12066 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType 12067 clang::LazyGenerationalUpdatePtr< 12068 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue( 12069 const clang::ASTContext &Ctx, Decl *Value); 12070 12071 unsigned char ASTContext::getFixedPointScale(QualType Ty) const { 12072 assert(Ty->isFixedPointType()); 12073 12074 const TargetInfo &Target = getTargetInfo(); 12075 switch (Ty->castAs<BuiltinType>()->getKind()) { 12076 default: 12077 llvm_unreachable("Not a fixed point type!"); 12078 case BuiltinType::ShortAccum: 12079 case BuiltinType::SatShortAccum: 12080 return Target.getShortAccumScale(); 12081 case BuiltinType::Accum: 12082 case BuiltinType::SatAccum: 12083 return Target.getAccumScale(); 12084 case BuiltinType::LongAccum: 12085 case BuiltinType::SatLongAccum: 12086 return Target.getLongAccumScale(); 12087 case BuiltinType::UShortAccum: 12088 case BuiltinType::SatUShortAccum: 12089 return Target.getUnsignedShortAccumScale(); 12090 case BuiltinType::UAccum: 12091 case BuiltinType::SatUAccum: 12092 return Target.getUnsignedAccumScale(); 12093 case BuiltinType::ULongAccum: 12094 case BuiltinType::SatULongAccum: 12095 return Target.getUnsignedLongAccumScale(); 12096 case BuiltinType::ShortFract: 12097 case BuiltinType::SatShortFract: 12098 return Target.getShortFractScale(); 12099 case BuiltinType::Fract: 12100 case BuiltinType::SatFract: 12101 return Target.getFractScale(); 12102 case BuiltinType::LongFract: 12103 case BuiltinType::SatLongFract: 12104 return Target.getLongFractScale(); 12105 case BuiltinType::UShortFract: 12106 case BuiltinType::SatUShortFract: 12107 return Target.getUnsignedShortFractScale(); 12108 case BuiltinType::UFract: 12109 case BuiltinType::SatUFract: 12110 return Target.getUnsignedFractScale(); 12111 case BuiltinType::ULongFract: 12112 case BuiltinType::SatULongFract: 12113 return Target.getUnsignedLongFractScale(); 12114 } 12115 } 12116 12117 unsigned char ASTContext::getFixedPointIBits(QualType Ty) const { 12118 assert(Ty->isFixedPointType()); 12119 12120 const TargetInfo &Target = getTargetInfo(); 12121 switch (Ty->castAs<BuiltinType>()->getKind()) { 12122 default: 12123 llvm_unreachable("Not a fixed point type!"); 12124 case BuiltinType::ShortAccum: 12125 case BuiltinType::SatShortAccum: 12126 return Target.getShortAccumIBits(); 12127 case BuiltinType::Accum: 12128 case BuiltinType::SatAccum: 12129 return Target.getAccumIBits(); 12130 case BuiltinType::LongAccum: 12131 case BuiltinType::SatLongAccum: 12132 return Target.getLongAccumIBits(); 12133 case BuiltinType::UShortAccum: 12134 case BuiltinType::SatUShortAccum: 12135 return Target.getUnsignedShortAccumIBits(); 12136 case BuiltinType::UAccum: 12137 case BuiltinType::SatUAccum: 12138 return Target.getUnsignedAccumIBits(); 12139 case BuiltinType::ULongAccum: 12140 case BuiltinType::SatULongAccum: 12141 return Target.getUnsignedLongAccumIBits(); 12142 case BuiltinType::ShortFract: 12143 case BuiltinType::SatShortFract: 12144 case BuiltinType::Fract: 12145 case BuiltinType::SatFract: 12146 case BuiltinType::LongFract: 12147 case BuiltinType::SatLongFract: 12148 case BuiltinType::UShortFract: 12149 case BuiltinType::SatUShortFract: 12150 case BuiltinType::UFract: 12151 case BuiltinType::SatUFract: 12152 case BuiltinType::ULongFract: 12153 case BuiltinType::SatULongFract: 12154 return 0; 12155 } 12156 } 12157 12158 llvm::FixedPointSemantics 12159 ASTContext::getFixedPointSemantics(QualType Ty) const { 12160 assert((Ty->isFixedPointType() || Ty->isIntegerType()) && 12161 "Can only get the fixed point semantics for a " 12162 "fixed point or integer type."); 12163 if (Ty->isIntegerType()) 12164 return llvm::FixedPointSemantics::GetIntegerSemantics( 12165 getIntWidth(Ty), Ty->isSignedIntegerType()); 12166 12167 bool isSigned = Ty->isSignedFixedPointType(); 12168 return llvm::FixedPointSemantics( 12169 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned, 12170 Ty->isSaturatedFixedPointType(), 12171 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding()); 12172 } 12173 12174 llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const { 12175 assert(Ty->isFixedPointType()); 12176 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty)); 12177 } 12178 12179 llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const { 12180 assert(Ty->isFixedPointType()); 12181 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty)); 12182 } 12183 12184 QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const { 12185 assert(Ty->isUnsignedFixedPointType() && 12186 "Expected unsigned fixed point type"); 12187 12188 switch (Ty->castAs<BuiltinType>()->getKind()) { 12189 case BuiltinType::UShortAccum: 12190 return ShortAccumTy; 12191 case BuiltinType::UAccum: 12192 return AccumTy; 12193 case BuiltinType::ULongAccum: 12194 return LongAccumTy; 12195 case BuiltinType::SatUShortAccum: 12196 return SatShortAccumTy; 12197 case BuiltinType::SatUAccum: 12198 return SatAccumTy; 12199 case BuiltinType::SatULongAccum: 12200 return SatLongAccumTy; 12201 case BuiltinType::UShortFract: 12202 return ShortFractTy; 12203 case BuiltinType::UFract: 12204 return FractTy; 12205 case BuiltinType::ULongFract: 12206 return LongFractTy; 12207 case BuiltinType::SatUShortFract: 12208 return SatShortFractTy; 12209 case BuiltinType::SatUFract: 12210 return SatFractTy; 12211 case BuiltinType::SatULongFract: 12212 return SatLongFractTy; 12213 default: 12214 llvm_unreachable("Unexpected unsigned fixed point type"); 12215 } 12216 } 12217 12218 ParsedTargetAttr 12219 ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const { 12220 assert(TD != nullptr); 12221 ParsedTargetAttr ParsedAttr = TD->parse(); 12222 12223 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) { 12224 return !Target->isValidFeatureName(StringRef{Feat}.substr(1)); 12225 }); 12226 return ParsedAttr; 12227 } 12228 12229 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 12230 const FunctionDecl *FD) const { 12231 if (FD) 12232 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD)); 12233 else 12234 Target->initFeatureMap(FeatureMap, getDiagnostics(), 12235 Target->getTargetOpts().CPU, 12236 Target->getTargetOpts().Features); 12237 } 12238 12239 // Fills in the supplied string map with the set of target features for the 12240 // passed in function. 12241 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 12242 GlobalDecl GD) const { 12243 StringRef TargetCPU = Target->getTargetOpts().CPU; 12244 const FunctionDecl *FD = GD.getDecl()->getAsFunction(); 12245 if (const auto *TD = FD->getAttr<TargetAttr>()) { 12246 ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD); 12247 12248 // Make a copy of the features as passed on the command line into the 12249 // beginning of the additional features from the function to override. 12250 ParsedAttr.Features.insert( 12251 ParsedAttr.Features.begin(), 12252 Target->getTargetOpts().FeaturesAsWritten.begin(), 12253 Target->getTargetOpts().FeaturesAsWritten.end()); 12254 12255 if (ParsedAttr.Architecture != "" && 12256 Target->isValidCPUName(ParsedAttr.Architecture)) 12257 TargetCPU = ParsedAttr.Architecture; 12258 12259 // Now populate the feature map, first with the TargetCPU which is either 12260 // the default or a new one from the target attribute string. Then we'll use 12261 // the passed in features (FeaturesAsWritten) along with the new ones from 12262 // the attribute. 12263 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, 12264 ParsedAttr.Features); 12265 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) { 12266 llvm::SmallVector<StringRef, 32> FeaturesTmp; 12267 Target->getCPUSpecificCPUDispatchFeatures( 12268 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp); 12269 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end()); 12270 Features.insert(Features.begin(), 12271 Target->getTargetOpts().FeaturesAsWritten.begin(), 12272 Target->getTargetOpts().FeaturesAsWritten.end()); 12273 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features); 12274 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) { 12275 std::vector<std::string> Features; 12276 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex()); 12277 if (VersionStr.startswith("arch=")) 12278 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1); 12279 else if (VersionStr != "default") 12280 Features.push_back((StringRef{"+"} + VersionStr).str()); 12281 12282 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features); 12283 } else { 12284 FeatureMap = Target->getTargetOpts().FeatureMap; 12285 } 12286 } 12287 12288 OMPTraitInfo &ASTContext::getNewOMPTraitInfo() { 12289 OMPTraitInfoVector.emplace_back(new OMPTraitInfo()); 12290 return *OMPTraitInfoVector.back(); 12291 } 12292 12293 const StreamingDiagnostic &clang:: 12294 operator<<(const StreamingDiagnostic &DB, 12295 const ASTContext::SectionInfo &Section) { 12296 if (Section.Decl) 12297 return DB << Section.Decl; 12298 return DB << "a prior #pragma section"; 12299 } 12300 12301 bool ASTContext::mayExternalize(const Decl *D) const { 12302 bool IsStaticVar = 12303 isa<VarDecl>(D) && cast<VarDecl>(D)->getStorageClass() == SC_Static; 12304 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() && 12305 !D->getAttr<CUDADeviceAttr>()->isImplicit()) || 12306 (D->hasAttr<CUDAConstantAttr>() && 12307 !D->getAttr<CUDAConstantAttr>()->isImplicit()); 12308 // CUDA/HIP: static managed variables need to be externalized since it is 12309 // a declaration in IR, therefore cannot have internal linkage. Kernels in 12310 // anonymous name space needs to be externalized to avoid duplicate symbols. 12311 return (IsStaticVar && 12312 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) || 12313 (D->hasAttr<CUDAGlobalAttr>() && 12314 basicGVALinkageForFunction(*this, cast<FunctionDecl>(D)) == 12315 GVA_Internal); 12316 } 12317 12318 bool ASTContext::shouldExternalize(const Decl *D) const { 12319 return mayExternalize(D) && 12320 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() || 12321 CUDADeviceVarODRUsedByHost.count(cast<VarDecl>(D))); 12322 } 12323 12324 StringRef ASTContext::getCUIDHash() const { 12325 if (!CUIDHash.empty()) 12326 return CUIDHash; 12327 if (LangOpts.CUID.empty()) 12328 return StringRef(); 12329 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true); 12330 return CUIDHash; 12331 } 12332