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 for (auto &Arg : OldConverted.front().pack_elements().drop_front(1)) 743 NewConverted.push_back(Arg); 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 for (auto &Arg : OldConverted.drop_front(1)) 756 NewConverted.push_back(Arg); 757 } 758 Expr *NewIDC = ConceptSpecializationExpr::Create( 759 C, CSE->getNamedConcept(), NewConverted, nullptr, 760 CSE->isInstantiationDependent(), CSE->containsUnexpandedParameterPack()); 761 762 if (auto *OrigFold = dyn_cast<CXXFoldExpr>(IDC)) 763 NewIDC = new (C) CXXFoldExpr( 764 OrigFold->getType(), /*Callee*/nullptr, SourceLocation(), NewIDC, 765 BinaryOperatorKind::BO_LAnd, SourceLocation(), /*RHS=*/nullptr, 766 SourceLocation(), /*NumExpansions=*/None); 767 return NewIDC; 768 } 769 770 TemplateTemplateParmDecl * 771 ASTContext::getCanonicalTemplateTemplateParmDecl( 772 TemplateTemplateParmDecl *TTP) const { 773 // Check if we already have a canonical template template parameter. 774 llvm::FoldingSetNodeID ID; 775 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP); 776 void *InsertPos = nullptr; 777 CanonicalTemplateTemplateParm *Canonical 778 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 779 if (Canonical) 780 return Canonical->getParam(); 781 782 // Build a canonical template parameter list. 783 TemplateParameterList *Params = TTP->getTemplateParameters(); 784 SmallVector<NamedDecl *, 4> CanonParams; 785 CanonParams.reserve(Params->size()); 786 for (TemplateParameterList::const_iterator P = Params->begin(), 787 PEnd = Params->end(); 788 P != PEnd; ++P) { 789 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { 790 TemplateTypeParmDecl *NewTTP = TemplateTypeParmDecl::Create(*this, 791 getTranslationUnitDecl(), SourceLocation(), SourceLocation(), 792 TTP->getDepth(), TTP->getIndex(), nullptr, false, 793 TTP->isParameterPack(), TTP->hasTypeConstraint(), 794 TTP->isExpandedParameterPack() ? 795 llvm::Optional<unsigned>(TTP->getNumExpansionParameters()) : None); 796 if (const auto *TC = TTP->getTypeConstraint()) { 797 QualType ParamAsArgument(NewTTP->getTypeForDecl(), 0); 798 Expr *NewIDC = canonicalizeImmediatelyDeclaredConstraint( 799 *this, TC->getImmediatelyDeclaredConstraint(), 800 ParamAsArgument); 801 TemplateArgumentListInfo CanonArgsAsWritten; 802 if (auto *Args = TC->getTemplateArgsAsWritten()) 803 for (const auto &ArgLoc : Args->arguments()) 804 CanonArgsAsWritten.addArgument( 805 TemplateArgumentLoc(ArgLoc.getArgument(), 806 TemplateArgumentLocInfo())); 807 NewTTP->setTypeConstraint( 808 NestedNameSpecifierLoc(), 809 DeclarationNameInfo(TC->getNamedConcept()->getDeclName(), 810 SourceLocation()), /*FoundDecl=*/nullptr, 811 // Actually canonicalizing a TemplateArgumentLoc is difficult so we 812 // simply omit the ArgsAsWritten 813 TC->getNamedConcept(), /*ArgsAsWritten=*/nullptr, NewIDC); 814 } 815 CanonParams.push_back(NewTTP); 816 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 817 QualType T = getCanonicalType(NTTP->getType()); 818 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); 819 NonTypeTemplateParmDecl *Param; 820 if (NTTP->isExpandedParameterPack()) { 821 SmallVector<QualType, 2> ExpandedTypes; 822 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos; 823 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { 824 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I))); 825 ExpandedTInfos.push_back( 826 getTrivialTypeSourceInfo(ExpandedTypes.back())); 827 } 828 829 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 830 SourceLocation(), 831 SourceLocation(), 832 NTTP->getDepth(), 833 NTTP->getPosition(), nullptr, 834 T, 835 TInfo, 836 ExpandedTypes, 837 ExpandedTInfos); 838 } else { 839 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 840 SourceLocation(), 841 SourceLocation(), 842 NTTP->getDepth(), 843 NTTP->getPosition(), nullptr, 844 T, 845 NTTP->isParameterPack(), 846 TInfo); 847 } 848 if (AutoType *AT = T->getContainedAutoType()) { 849 if (AT->isConstrained()) { 850 Param->setPlaceholderTypeConstraint( 851 canonicalizeImmediatelyDeclaredConstraint( 852 *this, NTTP->getPlaceholderTypeConstraint(), T)); 853 } 854 } 855 CanonParams.push_back(Param); 856 857 } else 858 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl( 859 cast<TemplateTemplateParmDecl>(*P))); 860 } 861 862 Expr *CanonRequiresClause = nullptr; 863 if (Expr *RequiresClause = TTP->getTemplateParameters()->getRequiresClause()) 864 CanonRequiresClause = RequiresClause; 865 866 TemplateTemplateParmDecl *CanonTTP 867 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 868 SourceLocation(), TTP->getDepth(), 869 TTP->getPosition(), 870 TTP->isParameterPack(), 871 nullptr, 872 TemplateParameterList::Create(*this, SourceLocation(), 873 SourceLocation(), 874 CanonParams, 875 SourceLocation(), 876 CanonRequiresClause)); 877 878 // Get the new insert position for the node we care about. 879 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 880 assert(!Canonical && "Shouldn't be in the map!"); 881 (void)Canonical; 882 883 // Create the canonical template template parameter entry. 884 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP); 885 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos); 886 return CanonTTP; 887 } 888 889 TargetCXXABI::Kind ASTContext::getCXXABIKind() const { 890 auto Kind = getTargetInfo().getCXXABI().getKind(); 891 return getLangOpts().CXXABI.getValueOr(Kind); 892 } 893 894 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) { 895 if (!LangOpts.CPlusPlus) return nullptr; 896 897 switch (getCXXABIKind()) { 898 case TargetCXXABI::AppleARM64: 899 case TargetCXXABI::Fuchsia: 900 case TargetCXXABI::GenericARM: // Same as Itanium at this level 901 case TargetCXXABI::iOS: 902 case TargetCXXABI::WatchOS: 903 case TargetCXXABI::GenericAArch64: 904 case TargetCXXABI::GenericMIPS: 905 case TargetCXXABI::GenericItanium: 906 case TargetCXXABI::WebAssembly: 907 case TargetCXXABI::XL: 908 return CreateItaniumCXXABI(*this); 909 case TargetCXXABI::Microsoft: 910 return CreateMicrosoftCXXABI(*this); 911 } 912 llvm_unreachable("Invalid CXXABI type!"); 913 } 914 915 interp::Context &ASTContext::getInterpContext() { 916 if (!InterpContext) { 917 InterpContext.reset(new interp::Context(*this)); 918 } 919 return *InterpContext.get(); 920 } 921 922 ParentMapContext &ASTContext::getParentMapContext() { 923 if (!ParentMapCtx) 924 ParentMapCtx.reset(new ParentMapContext(*this)); 925 return *ParentMapCtx.get(); 926 } 927 928 static const LangASMap *getAddressSpaceMap(const TargetInfo &T, 929 const LangOptions &LOpts) { 930 if (LOpts.FakeAddressSpaceMap) { 931 // The fake address space map must have a distinct entry for each 932 // language-specific address space. 933 static const unsigned FakeAddrSpaceMap[] = { 934 0, // Default 935 1, // opencl_global 936 3, // opencl_local 937 2, // opencl_constant 938 0, // opencl_private 939 4, // opencl_generic 940 5, // opencl_global_device 941 6, // opencl_global_host 942 7, // cuda_device 943 8, // cuda_constant 944 9, // cuda_shared 945 1, // sycl_global 946 5, // sycl_global_device 947 6, // sycl_global_host 948 3, // sycl_local 949 0, // sycl_private 950 10, // ptr32_sptr 951 11, // ptr32_uptr 952 12 // ptr64 953 }; 954 return &FakeAddrSpaceMap; 955 } else { 956 return &T.getAddressSpaceMap(); 957 } 958 } 959 960 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI, 961 const LangOptions &LangOpts) { 962 switch (LangOpts.getAddressSpaceMapMangling()) { 963 case LangOptions::ASMM_Target: 964 return TI.useAddressSpaceMapMangling(); 965 case LangOptions::ASMM_On: 966 return true; 967 case LangOptions::ASMM_Off: 968 return false; 969 } 970 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything."); 971 } 972 973 ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM, 974 IdentifierTable &idents, SelectorTable &sels, 975 Builtin::Context &builtins, TranslationUnitKind TUKind) 976 : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize), 977 FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize), 978 TemplateSpecializationTypes(this_()), 979 DependentTemplateSpecializationTypes(this_()), AutoTypes(this_()), 980 SubstTemplateTemplateParmPacks(this_()), 981 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts), 982 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)), 983 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles, 984 LangOpts.XRayNeverInstrumentFiles, 985 LangOpts.XRayAttrListFiles, SM)), 986 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)), 987 PrintingPolicy(LOpts), Idents(idents), Selectors(sels), 988 BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this), 989 Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), 990 CompCategories(this_()), LastSDM(nullptr, 0) { 991 addTranslationUnitDecl(); 992 } 993 994 void ASTContext::cleanup() { 995 // Release the DenseMaps associated with DeclContext objects. 996 // FIXME: Is this the ideal solution? 997 ReleaseDeclContextMaps(); 998 999 // Call all of the deallocation functions on all of their targets. 1000 for (auto &Pair : Deallocations) 1001 (Pair.first)(Pair.second); 1002 Deallocations.clear(); 1003 1004 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed 1005 // because they can contain DenseMaps. 1006 for (llvm::DenseMap<const ObjCContainerDecl*, 1007 const ASTRecordLayout*>::iterator 1008 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) 1009 // Increment in loop to prevent using deallocated memory. 1010 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second)) 1011 R->Destroy(*this); 1012 ObjCLayouts.clear(); 1013 1014 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator 1015 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) { 1016 // Increment in loop to prevent using deallocated memory. 1017 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second)) 1018 R->Destroy(*this); 1019 } 1020 ASTRecordLayouts.clear(); 1021 1022 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(), 1023 AEnd = DeclAttrs.end(); 1024 A != AEnd; ++A) 1025 A->second->~AttrVec(); 1026 DeclAttrs.clear(); 1027 1028 for (const auto &Value : ModuleInitializers) 1029 Value.second->~PerModuleInitializers(); 1030 ModuleInitializers.clear(); 1031 } 1032 1033 ASTContext::~ASTContext() { cleanup(); } 1034 1035 void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) { 1036 TraversalScope = TopLevelDecls; 1037 getParentMapContext().clear(); 1038 } 1039 1040 void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const { 1041 Deallocations.push_back({Callback, Data}); 1042 } 1043 1044 void 1045 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) { 1046 ExternalSource = std::move(Source); 1047 } 1048 1049 void ASTContext::PrintStats() const { 1050 llvm::errs() << "\n*** AST Context Stats:\n"; 1051 llvm::errs() << " " << Types.size() << " types total.\n"; 1052 1053 unsigned counts[] = { 1054 #define TYPE(Name, Parent) 0, 1055 #define ABSTRACT_TYPE(Name, Parent) 1056 #include "clang/AST/TypeNodes.inc" 1057 0 // Extra 1058 }; 1059 1060 for (unsigned i = 0, e = Types.size(); i != e; ++i) { 1061 Type *T = Types[i]; 1062 counts[(unsigned)T->getTypeClass()]++; 1063 } 1064 1065 unsigned Idx = 0; 1066 unsigned TotalBytes = 0; 1067 #define TYPE(Name, Parent) \ 1068 if (counts[Idx]) \ 1069 llvm::errs() << " " << counts[Idx] << " " << #Name \ 1070 << " types, " << sizeof(Name##Type) << " each " \ 1071 << "(" << counts[Idx] * sizeof(Name##Type) \ 1072 << " bytes)\n"; \ 1073 TotalBytes += counts[Idx] * sizeof(Name##Type); \ 1074 ++Idx; 1075 #define ABSTRACT_TYPE(Name, Parent) 1076 #include "clang/AST/TypeNodes.inc" 1077 1078 llvm::errs() << "Total bytes = " << TotalBytes << "\n"; 1079 1080 // Implicit special member functions. 1081 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/" 1082 << NumImplicitDefaultConstructors 1083 << " implicit default constructors created\n"; 1084 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/" 1085 << NumImplicitCopyConstructors 1086 << " implicit copy constructors created\n"; 1087 if (getLangOpts().CPlusPlus) 1088 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/" 1089 << NumImplicitMoveConstructors 1090 << " implicit move constructors created\n"; 1091 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/" 1092 << NumImplicitCopyAssignmentOperators 1093 << " implicit copy assignment operators created\n"; 1094 if (getLangOpts().CPlusPlus) 1095 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/" 1096 << NumImplicitMoveAssignmentOperators 1097 << " implicit move assignment operators created\n"; 1098 llvm::errs() << NumImplicitDestructorsDeclared << "/" 1099 << NumImplicitDestructors 1100 << " implicit destructors created\n"; 1101 1102 if (ExternalSource) { 1103 llvm::errs() << "\n"; 1104 ExternalSource->PrintStats(); 1105 } 1106 1107 BumpAlloc.PrintStats(); 1108 } 1109 1110 void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M, 1111 bool NotifyListeners) { 1112 if (NotifyListeners) 1113 if (auto *Listener = getASTMutationListener()) 1114 Listener->RedefinedHiddenDefinition(ND, M); 1115 1116 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M); 1117 } 1118 1119 void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) { 1120 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl())); 1121 if (It == MergedDefModules.end()) 1122 return; 1123 1124 auto &Merged = It->second; 1125 llvm::DenseSet<Module*> Found; 1126 for (Module *&M : Merged) 1127 if (!Found.insert(M).second) 1128 M = nullptr; 1129 llvm::erase_value(Merged, nullptr); 1130 } 1131 1132 ArrayRef<Module *> 1133 ASTContext::getModulesWithMergedDefinition(const NamedDecl *Def) { 1134 auto MergedIt = 1135 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl())); 1136 if (MergedIt == MergedDefModules.end()) 1137 return None; 1138 return MergedIt->second; 1139 } 1140 1141 void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) { 1142 if (LazyInitializers.empty()) 1143 return; 1144 1145 auto *Source = Ctx.getExternalSource(); 1146 assert(Source && "lazy initializers but no external source"); 1147 1148 auto LazyInits = std::move(LazyInitializers); 1149 LazyInitializers.clear(); 1150 1151 for (auto ID : LazyInits) 1152 Initializers.push_back(Source->GetExternalDecl(ID)); 1153 1154 assert(LazyInitializers.empty() && 1155 "GetExternalDecl for lazy module initializer added more inits"); 1156 } 1157 1158 void ASTContext::addModuleInitializer(Module *M, Decl *D) { 1159 // One special case: if we add a module initializer that imports another 1160 // module, and that module's only initializer is an ImportDecl, simplify. 1161 if (const auto *ID = dyn_cast<ImportDecl>(D)) { 1162 auto It = ModuleInitializers.find(ID->getImportedModule()); 1163 1164 // Maybe the ImportDecl does nothing at all. (Common case.) 1165 if (It == ModuleInitializers.end()) 1166 return; 1167 1168 // Maybe the ImportDecl only imports another ImportDecl. 1169 auto &Imported = *It->second; 1170 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) { 1171 Imported.resolve(*this); 1172 auto *OnlyDecl = Imported.Initializers.front(); 1173 if (isa<ImportDecl>(OnlyDecl)) 1174 D = OnlyDecl; 1175 } 1176 } 1177 1178 auto *&Inits = ModuleInitializers[M]; 1179 if (!Inits) 1180 Inits = new (*this) PerModuleInitializers; 1181 Inits->Initializers.push_back(D); 1182 } 1183 1184 void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) { 1185 auto *&Inits = ModuleInitializers[M]; 1186 if (!Inits) 1187 Inits = new (*this) PerModuleInitializers; 1188 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(), 1189 IDs.begin(), IDs.end()); 1190 } 1191 1192 ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) { 1193 auto It = ModuleInitializers.find(M); 1194 if (It == ModuleInitializers.end()) 1195 return None; 1196 1197 auto *Inits = It->second; 1198 Inits->resolve(*this); 1199 return Inits->Initializers; 1200 } 1201 1202 ExternCContextDecl *ASTContext::getExternCContextDecl() const { 1203 if (!ExternCContext) 1204 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl()); 1205 1206 return ExternCContext; 1207 } 1208 1209 BuiltinTemplateDecl * 1210 ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK, 1211 const IdentifierInfo *II) const { 1212 auto *BuiltinTemplate = 1213 BuiltinTemplateDecl::Create(*this, getTranslationUnitDecl(), II, BTK); 1214 BuiltinTemplate->setImplicit(); 1215 getTranslationUnitDecl()->addDecl(BuiltinTemplate); 1216 1217 return BuiltinTemplate; 1218 } 1219 1220 BuiltinTemplateDecl * 1221 ASTContext::getMakeIntegerSeqDecl() const { 1222 if (!MakeIntegerSeqDecl) 1223 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq, 1224 getMakeIntegerSeqName()); 1225 return MakeIntegerSeqDecl; 1226 } 1227 1228 BuiltinTemplateDecl * 1229 ASTContext::getTypePackElementDecl() const { 1230 if (!TypePackElementDecl) 1231 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element, 1232 getTypePackElementName()); 1233 return TypePackElementDecl; 1234 } 1235 1236 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name, 1237 RecordDecl::TagKind TK) const { 1238 SourceLocation Loc; 1239 RecordDecl *NewDecl; 1240 if (getLangOpts().CPlusPlus) 1241 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, 1242 Loc, &Idents.get(Name)); 1243 else 1244 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc, 1245 &Idents.get(Name)); 1246 NewDecl->setImplicit(); 1247 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit( 1248 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default)); 1249 return NewDecl; 1250 } 1251 1252 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T, 1253 StringRef Name) const { 1254 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); 1255 TypedefDecl *NewDecl = TypedefDecl::Create( 1256 const_cast<ASTContext &>(*this), getTranslationUnitDecl(), 1257 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo); 1258 NewDecl->setImplicit(); 1259 return NewDecl; 1260 } 1261 1262 TypedefDecl *ASTContext::getInt128Decl() const { 1263 if (!Int128Decl) 1264 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t"); 1265 return Int128Decl; 1266 } 1267 1268 TypedefDecl *ASTContext::getUInt128Decl() const { 1269 if (!UInt128Decl) 1270 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t"); 1271 return UInt128Decl; 1272 } 1273 1274 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) { 1275 auto *Ty = new (*this, TypeAlignment) BuiltinType(K); 1276 R = CanQualType::CreateUnsafe(QualType(Ty, 0)); 1277 Types.push_back(Ty); 1278 } 1279 1280 void ASTContext::InitBuiltinTypes(const TargetInfo &Target, 1281 const TargetInfo *AuxTarget) { 1282 assert((!this->Target || this->Target == &Target) && 1283 "Incorrect target reinitialization"); 1284 assert(VoidTy.isNull() && "Context reinitialized?"); 1285 1286 this->Target = &Target; 1287 this->AuxTarget = AuxTarget; 1288 1289 ABI.reset(createCXXABI(Target)); 1290 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts); 1291 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts); 1292 1293 // C99 6.2.5p19. 1294 InitBuiltinType(VoidTy, BuiltinType::Void); 1295 1296 // C99 6.2.5p2. 1297 InitBuiltinType(BoolTy, BuiltinType::Bool); 1298 // C99 6.2.5p3. 1299 if (LangOpts.CharIsSigned) 1300 InitBuiltinType(CharTy, BuiltinType::Char_S); 1301 else 1302 InitBuiltinType(CharTy, BuiltinType::Char_U); 1303 // C99 6.2.5p4. 1304 InitBuiltinType(SignedCharTy, BuiltinType::SChar); 1305 InitBuiltinType(ShortTy, BuiltinType::Short); 1306 InitBuiltinType(IntTy, BuiltinType::Int); 1307 InitBuiltinType(LongTy, BuiltinType::Long); 1308 InitBuiltinType(LongLongTy, BuiltinType::LongLong); 1309 1310 // C99 6.2.5p6. 1311 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar); 1312 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort); 1313 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt); 1314 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong); 1315 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong); 1316 1317 // C99 6.2.5p10. 1318 InitBuiltinType(FloatTy, BuiltinType::Float); 1319 InitBuiltinType(DoubleTy, BuiltinType::Double); 1320 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble); 1321 1322 // GNU extension, __float128 for IEEE quadruple precision 1323 InitBuiltinType(Float128Ty, BuiltinType::Float128); 1324 1325 // __ibm128 for IBM extended precision 1326 InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128); 1327 1328 // C11 extension ISO/IEC TS 18661-3 1329 InitBuiltinType(Float16Ty, BuiltinType::Float16); 1330 1331 // ISO/IEC JTC1 SC22 WG14 N1169 Extension 1332 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum); 1333 InitBuiltinType(AccumTy, BuiltinType::Accum); 1334 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum); 1335 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum); 1336 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum); 1337 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum); 1338 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract); 1339 InitBuiltinType(FractTy, BuiltinType::Fract); 1340 InitBuiltinType(LongFractTy, BuiltinType::LongFract); 1341 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract); 1342 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract); 1343 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract); 1344 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum); 1345 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum); 1346 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum); 1347 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum); 1348 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum); 1349 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum); 1350 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract); 1351 InitBuiltinType(SatFractTy, BuiltinType::SatFract); 1352 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract); 1353 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract); 1354 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract); 1355 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract); 1356 1357 // GNU extension, 128-bit integers. 1358 InitBuiltinType(Int128Ty, BuiltinType::Int128); 1359 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128); 1360 1361 // C++ 3.9.1p5 1362 if (TargetInfo::isTypeSigned(Target.getWCharType())) 1363 InitBuiltinType(WCharTy, BuiltinType::WChar_S); 1364 else // -fshort-wchar makes wchar_t be unsigned. 1365 InitBuiltinType(WCharTy, BuiltinType::WChar_U); 1366 if (LangOpts.CPlusPlus && LangOpts.WChar) 1367 WideCharTy = WCharTy; 1368 else { 1369 // C99 (or C++ using -fno-wchar). 1370 WideCharTy = getFromTargetType(Target.getWCharType()); 1371 } 1372 1373 WIntTy = getFromTargetType(Target.getWIntType()); 1374 1375 // C++20 (proposed) 1376 InitBuiltinType(Char8Ty, BuiltinType::Char8); 1377 1378 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 1379 InitBuiltinType(Char16Ty, BuiltinType::Char16); 1380 else // C99 1381 Char16Ty = getFromTargetType(Target.getChar16Type()); 1382 1383 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 1384 InitBuiltinType(Char32Ty, BuiltinType::Char32); 1385 else // C99 1386 Char32Ty = getFromTargetType(Target.getChar32Type()); 1387 1388 // Placeholder type for type-dependent expressions whose type is 1389 // completely unknown. No code should ever check a type against 1390 // DependentTy and users should never see it; however, it is here to 1391 // help diagnose failures to properly check for type-dependent 1392 // expressions. 1393 InitBuiltinType(DependentTy, BuiltinType::Dependent); 1394 1395 // Placeholder type for functions. 1396 InitBuiltinType(OverloadTy, BuiltinType::Overload); 1397 1398 // Placeholder type for bound members. 1399 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember); 1400 1401 // Placeholder type for pseudo-objects. 1402 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject); 1403 1404 // "any" type; useful for debugger-like clients. 1405 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny); 1406 1407 // Placeholder type for unbridged ARC casts. 1408 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast); 1409 1410 // Placeholder type for builtin functions. 1411 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn); 1412 1413 // Placeholder type for OMP array sections. 1414 if (LangOpts.OpenMP) { 1415 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection); 1416 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping); 1417 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator); 1418 } 1419 if (LangOpts.MatrixTypes) 1420 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx); 1421 1422 // Builtin types for 'id', 'Class', and 'SEL'. 1423 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId); 1424 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass); 1425 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel); 1426 1427 if (LangOpts.OpenCL) { 1428 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 1429 InitBuiltinType(SingletonId, BuiltinType::Id); 1430 #include "clang/Basic/OpenCLImageTypes.def" 1431 1432 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler); 1433 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent); 1434 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent); 1435 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue); 1436 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID); 1437 1438 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 1439 InitBuiltinType(Id##Ty, BuiltinType::Id); 1440 #include "clang/Basic/OpenCLExtensionTypes.def" 1441 } 1442 1443 if (Target.hasAArch64SVETypes()) { 1444 #define SVE_TYPE(Name, Id, SingletonId) \ 1445 InitBuiltinType(SingletonId, BuiltinType::Id); 1446 #include "clang/Basic/AArch64SVEACLETypes.def" 1447 } 1448 1449 if (Target.getTriple().isPPC64()) { 1450 #define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \ 1451 InitBuiltinType(Id##Ty, BuiltinType::Id); 1452 #include "clang/Basic/PPCTypes.def" 1453 #define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \ 1454 InitBuiltinType(Id##Ty, BuiltinType::Id); 1455 #include "clang/Basic/PPCTypes.def" 1456 } 1457 1458 if (Target.hasRISCVVTypes()) { 1459 #define RVV_TYPE(Name, Id, SingletonId) \ 1460 InitBuiltinType(SingletonId, BuiltinType::Id); 1461 #include "clang/Basic/RISCVVTypes.def" 1462 } 1463 1464 // Builtin type for __objc_yes and __objc_no 1465 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ? 1466 SignedCharTy : BoolTy); 1467 1468 ObjCConstantStringType = QualType(); 1469 1470 ObjCSuperType = QualType(); 1471 1472 // void * type 1473 if (LangOpts.OpenCLGenericAddressSpace) { 1474 auto Q = VoidTy.getQualifiers(); 1475 Q.setAddressSpace(LangAS::opencl_generic); 1476 VoidPtrTy = getPointerType(getCanonicalType( 1477 getQualifiedType(VoidTy.getUnqualifiedType(), Q))); 1478 } else { 1479 VoidPtrTy = getPointerType(VoidTy); 1480 } 1481 1482 // nullptr type (C++0x 2.14.7) 1483 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr); 1484 1485 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16 1486 InitBuiltinType(HalfTy, BuiltinType::Half); 1487 1488 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16); 1489 1490 // Builtin type used to help define __builtin_va_list. 1491 VaListTagDecl = nullptr; 1492 1493 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls. 1494 if (LangOpts.MicrosoftExt || LangOpts.Borland) { 1495 MSGuidTagDecl = buildImplicitRecord("_GUID"); 1496 getTranslationUnitDecl()->addDecl(MSGuidTagDecl); 1497 } 1498 } 1499 1500 DiagnosticsEngine &ASTContext::getDiagnostics() const { 1501 return SourceMgr.getDiagnostics(); 1502 } 1503 1504 AttrVec& ASTContext::getDeclAttrs(const Decl *D) { 1505 AttrVec *&Result = DeclAttrs[D]; 1506 if (!Result) { 1507 void *Mem = Allocate(sizeof(AttrVec)); 1508 Result = new (Mem) AttrVec; 1509 } 1510 1511 return *Result; 1512 } 1513 1514 /// Erase the attributes corresponding to the given declaration. 1515 void ASTContext::eraseDeclAttrs(const Decl *D) { 1516 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D); 1517 if (Pos != DeclAttrs.end()) { 1518 Pos->second->~AttrVec(); 1519 DeclAttrs.erase(Pos); 1520 } 1521 } 1522 1523 // FIXME: Remove ? 1524 MemberSpecializationInfo * 1525 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) { 1526 assert(Var->isStaticDataMember() && "Not a static data member"); 1527 return getTemplateOrSpecializationInfo(Var) 1528 .dyn_cast<MemberSpecializationInfo *>(); 1529 } 1530 1531 ASTContext::TemplateOrSpecializationInfo 1532 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) { 1533 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos = 1534 TemplateOrInstantiation.find(Var); 1535 if (Pos == TemplateOrInstantiation.end()) 1536 return {}; 1537 1538 return Pos->second; 1539 } 1540 1541 void 1542 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, 1543 TemplateSpecializationKind TSK, 1544 SourceLocation PointOfInstantiation) { 1545 assert(Inst->isStaticDataMember() && "Not a static data member"); 1546 assert(Tmpl->isStaticDataMember() && "Not a static data member"); 1547 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo( 1548 Tmpl, TSK, PointOfInstantiation)); 1549 } 1550 1551 void 1552 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst, 1553 TemplateOrSpecializationInfo TSI) { 1554 assert(!TemplateOrInstantiation[Inst] && 1555 "Already noted what the variable was instantiated from"); 1556 TemplateOrInstantiation[Inst] = TSI; 1557 } 1558 1559 NamedDecl * 1560 ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) { 1561 auto Pos = InstantiatedFromUsingDecl.find(UUD); 1562 if (Pos == InstantiatedFromUsingDecl.end()) 1563 return nullptr; 1564 1565 return Pos->second; 1566 } 1567 1568 void 1569 ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) { 1570 assert((isa<UsingDecl>(Pattern) || 1571 isa<UnresolvedUsingValueDecl>(Pattern) || 1572 isa<UnresolvedUsingTypenameDecl>(Pattern)) && 1573 "pattern decl is not a using decl"); 1574 assert((isa<UsingDecl>(Inst) || 1575 isa<UnresolvedUsingValueDecl>(Inst) || 1576 isa<UnresolvedUsingTypenameDecl>(Inst)) && 1577 "instantiation did not produce a using decl"); 1578 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists"); 1579 InstantiatedFromUsingDecl[Inst] = Pattern; 1580 } 1581 1582 UsingEnumDecl * 1583 ASTContext::getInstantiatedFromUsingEnumDecl(UsingEnumDecl *UUD) { 1584 auto Pos = InstantiatedFromUsingEnumDecl.find(UUD); 1585 if (Pos == InstantiatedFromUsingEnumDecl.end()) 1586 return nullptr; 1587 1588 return Pos->second; 1589 } 1590 1591 void ASTContext::setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst, 1592 UsingEnumDecl *Pattern) { 1593 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists"); 1594 InstantiatedFromUsingEnumDecl[Inst] = Pattern; 1595 } 1596 1597 UsingShadowDecl * 1598 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) { 1599 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos 1600 = InstantiatedFromUsingShadowDecl.find(Inst); 1601 if (Pos == InstantiatedFromUsingShadowDecl.end()) 1602 return nullptr; 1603 1604 return Pos->second; 1605 } 1606 1607 void 1608 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, 1609 UsingShadowDecl *Pattern) { 1610 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists"); 1611 InstantiatedFromUsingShadowDecl[Inst] = Pattern; 1612 } 1613 1614 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) { 1615 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos 1616 = InstantiatedFromUnnamedFieldDecl.find(Field); 1617 if (Pos == InstantiatedFromUnnamedFieldDecl.end()) 1618 return nullptr; 1619 1620 return Pos->second; 1621 } 1622 1623 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, 1624 FieldDecl *Tmpl) { 1625 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed"); 1626 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed"); 1627 assert(!InstantiatedFromUnnamedFieldDecl[Inst] && 1628 "Already noted what unnamed field was instantiated from"); 1629 1630 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl; 1631 } 1632 1633 ASTContext::overridden_cxx_method_iterator 1634 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const { 1635 return overridden_methods(Method).begin(); 1636 } 1637 1638 ASTContext::overridden_cxx_method_iterator 1639 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const { 1640 return overridden_methods(Method).end(); 1641 } 1642 1643 unsigned 1644 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const { 1645 auto Range = overridden_methods(Method); 1646 return Range.end() - Range.begin(); 1647 } 1648 1649 ASTContext::overridden_method_range 1650 ASTContext::overridden_methods(const CXXMethodDecl *Method) const { 1651 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos = 1652 OverriddenMethods.find(Method->getCanonicalDecl()); 1653 if (Pos == OverriddenMethods.end()) 1654 return overridden_method_range(nullptr, nullptr); 1655 return overridden_method_range(Pos->second.begin(), Pos->second.end()); 1656 } 1657 1658 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method, 1659 const CXXMethodDecl *Overridden) { 1660 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl()); 1661 OverriddenMethods[Method].push_back(Overridden); 1662 } 1663 1664 void ASTContext::getOverriddenMethods( 1665 const NamedDecl *D, 1666 SmallVectorImpl<const NamedDecl *> &Overridden) const { 1667 assert(D); 1668 1669 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) { 1670 Overridden.append(overridden_methods_begin(CXXMethod), 1671 overridden_methods_end(CXXMethod)); 1672 return; 1673 } 1674 1675 const auto *Method = dyn_cast<ObjCMethodDecl>(D); 1676 if (!Method) 1677 return; 1678 1679 SmallVector<const ObjCMethodDecl *, 8> OverDecls; 1680 Method->getOverriddenMethods(OverDecls); 1681 Overridden.append(OverDecls.begin(), OverDecls.end()); 1682 } 1683 1684 void ASTContext::addedLocalImportDecl(ImportDecl *Import) { 1685 assert(!Import->getNextLocalImport() && 1686 "Import declaration already in the chain"); 1687 assert(!Import->isFromASTFile() && "Non-local import declaration"); 1688 if (!FirstLocalImport) { 1689 FirstLocalImport = Import; 1690 LastLocalImport = Import; 1691 return; 1692 } 1693 1694 LastLocalImport->setNextLocalImport(Import); 1695 LastLocalImport = Import; 1696 } 1697 1698 //===----------------------------------------------------------------------===// 1699 // Type Sizing and Analysis 1700 //===----------------------------------------------------------------------===// 1701 1702 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified 1703 /// scalar floating point type. 1704 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const { 1705 switch (T->castAs<BuiltinType>()->getKind()) { 1706 default: 1707 llvm_unreachable("Not a floating point type!"); 1708 case BuiltinType::BFloat16: 1709 return Target->getBFloat16Format(); 1710 case BuiltinType::Float16: 1711 case BuiltinType::Half: 1712 return Target->getHalfFormat(); 1713 case BuiltinType::Float: return Target->getFloatFormat(); 1714 case BuiltinType::Double: return Target->getDoubleFormat(); 1715 case BuiltinType::Ibm128: 1716 return Target->getIbm128Format(); 1717 case BuiltinType::LongDouble: 1718 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) 1719 return AuxTarget->getLongDoubleFormat(); 1720 return Target->getLongDoubleFormat(); 1721 case BuiltinType::Float128: 1722 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) 1723 return AuxTarget->getFloat128Format(); 1724 return Target->getFloat128Format(); 1725 } 1726 } 1727 1728 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const { 1729 unsigned Align = Target->getCharWidth(); 1730 1731 bool UseAlignAttrOnly = false; 1732 if (unsigned AlignFromAttr = D->getMaxAlignment()) { 1733 Align = AlignFromAttr; 1734 1735 // __attribute__((aligned)) can increase or decrease alignment 1736 // *except* on a struct or struct member, where it only increases 1737 // alignment unless 'packed' is also specified. 1738 // 1739 // It is an error for alignas to decrease alignment, so we can 1740 // ignore that possibility; Sema should diagnose it. 1741 if (isa<FieldDecl>(D)) { 1742 UseAlignAttrOnly = D->hasAttr<PackedAttr>() || 1743 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 1744 } else { 1745 UseAlignAttrOnly = true; 1746 } 1747 } 1748 else if (isa<FieldDecl>(D)) 1749 UseAlignAttrOnly = 1750 D->hasAttr<PackedAttr>() || 1751 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 1752 1753 // If we're using the align attribute only, just ignore everything 1754 // else about the declaration and its type. 1755 if (UseAlignAttrOnly) { 1756 // do nothing 1757 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) { 1758 QualType T = VD->getType(); 1759 if (const auto *RT = T->getAs<ReferenceType>()) { 1760 if (ForAlignof) 1761 T = RT->getPointeeType(); 1762 else 1763 T = getPointerType(RT->getPointeeType()); 1764 } 1765 QualType BaseT = getBaseElementType(T); 1766 if (T->isFunctionType()) 1767 Align = getTypeInfoImpl(T.getTypePtr()).Align; 1768 else if (!BaseT->isIncompleteType()) { 1769 // Adjust alignments of declarations with array type by the 1770 // large-array alignment on the target. 1771 if (const ArrayType *arrayType = getAsArrayType(T)) { 1772 unsigned MinWidth = Target->getLargeArrayMinWidth(); 1773 if (!ForAlignof && MinWidth) { 1774 if (isa<VariableArrayType>(arrayType)) 1775 Align = std::max(Align, Target->getLargeArrayAlign()); 1776 else if (isa<ConstantArrayType>(arrayType) && 1777 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType))) 1778 Align = std::max(Align, Target->getLargeArrayAlign()); 1779 } 1780 } 1781 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr())); 1782 if (BaseT.getQualifiers().hasUnaligned()) 1783 Align = Target->getCharWidth(); 1784 if (const auto *VD = dyn_cast<VarDecl>(D)) { 1785 if (VD->hasGlobalStorage() && !ForAlignof) { 1786 uint64_t TypeSize = getTypeSize(T.getTypePtr()); 1787 Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize)); 1788 } 1789 } 1790 } 1791 1792 // Fields can be subject to extra alignment constraints, like if 1793 // the field is packed, the struct is packed, or the struct has a 1794 // a max-field-alignment constraint (#pragma pack). So calculate 1795 // the actual alignment of the field within the struct, and then 1796 // (as we're expected to) constrain that by the alignment of the type. 1797 if (const auto *Field = dyn_cast<FieldDecl>(VD)) { 1798 const RecordDecl *Parent = Field->getParent(); 1799 // We can only produce a sensible answer if the record is valid. 1800 if (!Parent->isInvalidDecl()) { 1801 const ASTRecordLayout &Layout = getASTRecordLayout(Parent); 1802 1803 // Start with the record's overall alignment. 1804 unsigned FieldAlign = toBits(Layout.getAlignment()); 1805 1806 // Use the GCD of that and the offset within the record. 1807 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex()); 1808 if (Offset > 0) { 1809 // Alignment is always a power of 2, so the GCD will be a power of 2, 1810 // which means we get to do this crazy thing instead of Euclid's. 1811 uint64_t LowBitOfOffset = Offset & (~Offset + 1); 1812 if (LowBitOfOffset < FieldAlign) 1813 FieldAlign = static_cast<unsigned>(LowBitOfOffset); 1814 } 1815 1816 Align = std::min(Align, FieldAlign); 1817 } 1818 } 1819 } 1820 1821 // Some targets have hard limitation on the maximum requestable alignment in 1822 // aligned attribute for static variables. 1823 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute(); 1824 const auto *VD = dyn_cast<VarDecl>(D); 1825 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static) 1826 Align = std::min(Align, MaxAlignedAttr); 1827 1828 return toCharUnitsFromBits(Align); 1829 } 1830 1831 CharUnits ASTContext::getExnObjectAlignment() const { 1832 return toCharUnitsFromBits(Target->getExnObjectAlignment()); 1833 } 1834 1835 // getTypeInfoDataSizeInChars - Return the size of a type, in 1836 // chars. If the type is a record, its data size is returned. This is 1837 // the size of the memcpy that's performed when assigning this type 1838 // using a trivial copy/move assignment operator. 1839 TypeInfoChars ASTContext::getTypeInfoDataSizeInChars(QualType T) const { 1840 TypeInfoChars Info = getTypeInfoInChars(T); 1841 1842 // In C++, objects can sometimes be allocated into the tail padding 1843 // of a base-class subobject. We decide whether that's possible 1844 // during class layout, so here we can just trust the layout results. 1845 if (getLangOpts().CPlusPlus) { 1846 if (const auto *RT = T->getAs<RecordType>()) { 1847 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl()); 1848 Info.Width = layout.getDataSize(); 1849 } 1850 } 1851 1852 return Info; 1853 } 1854 1855 /// getConstantArrayInfoInChars - Performing the computation in CharUnits 1856 /// instead of in bits prevents overflowing the uint64_t for some large arrays. 1857 TypeInfoChars 1858 static getConstantArrayInfoInChars(const ASTContext &Context, 1859 const ConstantArrayType *CAT) { 1860 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType()); 1861 uint64_t Size = CAT->getSize().getZExtValue(); 1862 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <= 1863 (uint64_t)(-1)/Size) && 1864 "Overflow in array type char size evaluation"); 1865 uint64_t Width = EltInfo.Width.getQuantity() * Size; 1866 unsigned Align = EltInfo.Align.getQuantity(); 1867 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() || 1868 Context.getTargetInfo().getPointerWidth(0) == 64) 1869 Width = llvm::alignTo(Width, Align); 1870 return TypeInfoChars(CharUnits::fromQuantity(Width), 1871 CharUnits::fromQuantity(Align), 1872 EltInfo.AlignRequirement); 1873 } 1874 1875 TypeInfoChars ASTContext::getTypeInfoInChars(const Type *T) const { 1876 if (const auto *CAT = dyn_cast<ConstantArrayType>(T)) 1877 return getConstantArrayInfoInChars(*this, CAT); 1878 TypeInfo Info = getTypeInfo(T); 1879 return TypeInfoChars(toCharUnitsFromBits(Info.Width), 1880 toCharUnitsFromBits(Info.Align), Info.AlignRequirement); 1881 } 1882 1883 TypeInfoChars ASTContext::getTypeInfoInChars(QualType T) const { 1884 return getTypeInfoInChars(T.getTypePtr()); 1885 } 1886 1887 bool ASTContext::isAlignmentRequired(const Type *T) const { 1888 return getTypeInfo(T).AlignRequirement != AlignRequirementKind::None; 1889 } 1890 1891 bool ASTContext::isAlignmentRequired(QualType T) const { 1892 return isAlignmentRequired(T.getTypePtr()); 1893 } 1894 1895 unsigned ASTContext::getTypeAlignIfKnown(QualType T, 1896 bool NeedsPreferredAlignment) const { 1897 // An alignment on a typedef overrides anything else. 1898 if (const auto *TT = T->getAs<TypedefType>()) 1899 if (unsigned Align = TT->getDecl()->getMaxAlignment()) 1900 return Align; 1901 1902 // If we have an (array of) complete type, we're done. 1903 T = getBaseElementType(T); 1904 if (!T->isIncompleteType()) 1905 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T); 1906 1907 // If we had an array type, its element type might be a typedef 1908 // type with an alignment attribute. 1909 if (const auto *TT = T->getAs<TypedefType>()) 1910 if (unsigned Align = TT->getDecl()->getMaxAlignment()) 1911 return Align; 1912 1913 // Otherwise, see if the declaration of the type had an attribute. 1914 if (const auto *TT = T->getAs<TagType>()) 1915 return TT->getDecl()->getMaxAlignment(); 1916 1917 return 0; 1918 } 1919 1920 TypeInfo ASTContext::getTypeInfo(const Type *T) const { 1921 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T); 1922 if (I != MemoizedTypeInfo.end()) 1923 return I->second; 1924 1925 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup. 1926 TypeInfo TI = getTypeInfoImpl(T); 1927 MemoizedTypeInfo[T] = TI; 1928 return TI; 1929 } 1930 1931 /// getTypeInfoImpl - Return the size of the specified type, in bits. This 1932 /// method does not work on incomplete types. 1933 /// 1934 /// FIXME: Pointers into different addr spaces could have different sizes and 1935 /// alignment requirements: getPointerInfo should take an AddrSpace, this 1936 /// should take a QualType, &c. 1937 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const { 1938 uint64_t Width = 0; 1939 unsigned Align = 8; 1940 AlignRequirementKind AlignRequirement = AlignRequirementKind::None; 1941 unsigned AS = 0; 1942 switch (T->getTypeClass()) { 1943 #define TYPE(Class, Base) 1944 #define ABSTRACT_TYPE(Class, Base) 1945 #define NON_CANONICAL_TYPE(Class, Base) 1946 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 1947 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \ 1948 case Type::Class: \ 1949 assert(!T->isDependentType() && "should not see dependent types here"); \ 1950 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr()); 1951 #include "clang/AST/TypeNodes.inc" 1952 llvm_unreachable("Should not see dependent types"); 1953 1954 case Type::FunctionNoProto: 1955 case Type::FunctionProto: 1956 // GCC extension: alignof(function) = 32 bits 1957 Width = 0; 1958 Align = 32; 1959 break; 1960 1961 case Type::IncompleteArray: 1962 case Type::VariableArray: 1963 case Type::ConstantArray: { 1964 // Model non-constant sized arrays as size zero, but track the alignment. 1965 uint64_t Size = 0; 1966 if (const auto *CAT = dyn_cast<ConstantArrayType>(T)) 1967 Size = CAT->getSize().getZExtValue(); 1968 1969 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType()); 1970 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) && 1971 "Overflow in array type bit size evaluation"); 1972 Width = EltInfo.Width * Size; 1973 Align = EltInfo.Align; 1974 AlignRequirement = EltInfo.AlignRequirement; 1975 if (!getTargetInfo().getCXXABI().isMicrosoft() || 1976 getTargetInfo().getPointerWidth(0) == 64) 1977 Width = llvm::alignTo(Width, Align); 1978 break; 1979 } 1980 1981 case Type::ExtVector: 1982 case Type::Vector: { 1983 const auto *VT = cast<VectorType>(T); 1984 TypeInfo EltInfo = getTypeInfo(VT->getElementType()); 1985 Width = EltInfo.Width * VT->getNumElements(); 1986 Align = Width; 1987 // If the alignment is not a power of 2, round up to the next power of 2. 1988 // This happens for non-power-of-2 length vectors. 1989 if (Align & (Align-1)) { 1990 Align = llvm::NextPowerOf2(Align); 1991 Width = llvm::alignTo(Width, Align); 1992 } 1993 // Adjust the alignment based on the target max. 1994 uint64_t TargetVectorAlign = Target->getMaxVectorAlign(); 1995 if (TargetVectorAlign && TargetVectorAlign < Align) 1996 Align = TargetVectorAlign; 1997 if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) 1998 // Adjust the alignment for fixed-length SVE vectors. This is important 1999 // for non-power-of-2 vector lengths. 2000 Align = 128; 2001 else if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 2002 // Adjust the alignment for fixed-length SVE predicates. 2003 Align = 16; 2004 break; 2005 } 2006 2007 case Type::ConstantMatrix: { 2008 const auto *MT = cast<ConstantMatrixType>(T); 2009 TypeInfo ElementInfo = getTypeInfo(MT->getElementType()); 2010 // The internal layout of a matrix value is implementation defined. 2011 // Initially be ABI compatible with arrays with respect to alignment and 2012 // size. 2013 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns(); 2014 Align = ElementInfo.Align; 2015 break; 2016 } 2017 2018 case Type::Builtin: 2019 switch (cast<BuiltinType>(T)->getKind()) { 2020 default: llvm_unreachable("Unknown builtin type!"); 2021 case BuiltinType::Void: 2022 // GCC extension: alignof(void) = 8 bits. 2023 Width = 0; 2024 Align = 8; 2025 break; 2026 case BuiltinType::Bool: 2027 Width = Target->getBoolWidth(); 2028 Align = Target->getBoolAlign(); 2029 break; 2030 case BuiltinType::Char_S: 2031 case BuiltinType::Char_U: 2032 case BuiltinType::UChar: 2033 case BuiltinType::SChar: 2034 case BuiltinType::Char8: 2035 Width = Target->getCharWidth(); 2036 Align = Target->getCharAlign(); 2037 break; 2038 case BuiltinType::WChar_S: 2039 case BuiltinType::WChar_U: 2040 Width = Target->getWCharWidth(); 2041 Align = Target->getWCharAlign(); 2042 break; 2043 case BuiltinType::Char16: 2044 Width = Target->getChar16Width(); 2045 Align = Target->getChar16Align(); 2046 break; 2047 case BuiltinType::Char32: 2048 Width = Target->getChar32Width(); 2049 Align = Target->getChar32Align(); 2050 break; 2051 case BuiltinType::UShort: 2052 case BuiltinType::Short: 2053 Width = Target->getShortWidth(); 2054 Align = Target->getShortAlign(); 2055 break; 2056 case BuiltinType::UInt: 2057 case BuiltinType::Int: 2058 Width = Target->getIntWidth(); 2059 Align = Target->getIntAlign(); 2060 break; 2061 case BuiltinType::ULong: 2062 case BuiltinType::Long: 2063 Width = Target->getLongWidth(); 2064 Align = Target->getLongAlign(); 2065 break; 2066 case BuiltinType::ULongLong: 2067 case BuiltinType::LongLong: 2068 Width = Target->getLongLongWidth(); 2069 Align = Target->getLongLongAlign(); 2070 break; 2071 case BuiltinType::Int128: 2072 case BuiltinType::UInt128: 2073 Width = 128; 2074 Align = 128; // int128_t is 128-bit aligned on all targets. 2075 break; 2076 case BuiltinType::ShortAccum: 2077 case BuiltinType::UShortAccum: 2078 case BuiltinType::SatShortAccum: 2079 case BuiltinType::SatUShortAccum: 2080 Width = Target->getShortAccumWidth(); 2081 Align = Target->getShortAccumAlign(); 2082 break; 2083 case BuiltinType::Accum: 2084 case BuiltinType::UAccum: 2085 case BuiltinType::SatAccum: 2086 case BuiltinType::SatUAccum: 2087 Width = Target->getAccumWidth(); 2088 Align = Target->getAccumAlign(); 2089 break; 2090 case BuiltinType::LongAccum: 2091 case BuiltinType::ULongAccum: 2092 case BuiltinType::SatLongAccum: 2093 case BuiltinType::SatULongAccum: 2094 Width = Target->getLongAccumWidth(); 2095 Align = Target->getLongAccumAlign(); 2096 break; 2097 case BuiltinType::ShortFract: 2098 case BuiltinType::UShortFract: 2099 case BuiltinType::SatShortFract: 2100 case BuiltinType::SatUShortFract: 2101 Width = Target->getShortFractWidth(); 2102 Align = Target->getShortFractAlign(); 2103 break; 2104 case BuiltinType::Fract: 2105 case BuiltinType::UFract: 2106 case BuiltinType::SatFract: 2107 case BuiltinType::SatUFract: 2108 Width = Target->getFractWidth(); 2109 Align = Target->getFractAlign(); 2110 break; 2111 case BuiltinType::LongFract: 2112 case BuiltinType::ULongFract: 2113 case BuiltinType::SatLongFract: 2114 case BuiltinType::SatULongFract: 2115 Width = Target->getLongFractWidth(); 2116 Align = Target->getLongFractAlign(); 2117 break; 2118 case BuiltinType::BFloat16: 2119 Width = Target->getBFloat16Width(); 2120 Align = Target->getBFloat16Align(); 2121 break; 2122 case BuiltinType::Float16: 2123 case BuiltinType::Half: 2124 if (Target->hasFloat16Type() || !getLangOpts().OpenMP || 2125 !getLangOpts().OpenMPIsDevice) { 2126 Width = Target->getHalfWidth(); 2127 Align = Target->getHalfAlign(); 2128 } else { 2129 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 2130 "Expected OpenMP device compilation."); 2131 Width = AuxTarget->getHalfWidth(); 2132 Align = AuxTarget->getHalfAlign(); 2133 } 2134 break; 2135 case BuiltinType::Float: 2136 Width = Target->getFloatWidth(); 2137 Align = Target->getFloatAlign(); 2138 break; 2139 case BuiltinType::Double: 2140 Width = Target->getDoubleWidth(); 2141 Align = Target->getDoubleAlign(); 2142 break; 2143 case BuiltinType::Ibm128: 2144 Width = Target->getIbm128Width(); 2145 Align = Target->getIbm128Align(); 2146 break; 2147 case BuiltinType::LongDouble: 2148 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 2149 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() || 2150 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) { 2151 Width = AuxTarget->getLongDoubleWidth(); 2152 Align = AuxTarget->getLongDoubleAlign(); 2153 } else { 2154 Width = Target->getLongDoubleWidth(); 2155 Align = Target->getLongDoubleAlign(); 2156 } 2157 break; 2158 case BuiltinType::Float128: 2159 if (Target->hasFloat128Type() || !getLangOpts().OpenMP || 2160 !getLangOpts().OpenMPIsDevice) { 2161 Width = Target->getFloat128Width(); 2162 Align = Target->getFloat128Align(); 2163 } else { 2164 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 2165 "Expected OpenMP device compilation."); 2166 Width = AuxTarget->getFloat128Width(); 2167 Align = AuxTarget->getFloat128Align(); 2168 } 2169 break; 2170 case BuiltinType::NullPtr: 2171 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t) 2172 Align = Target->getPointerAlign(0); // == sizeof(void*) 2173 break; 2174 case BuiltinType::ObjCId: 2175 case BuiltinType::ObjCClass: 2176 case BuiltinType::ObjCSel: 2177 Width = Target->getPointerWidth(0); 2178 Align = Target->getPointerAlign(0); 2179 break; 2180 case BuiltinType::OCLSampler: 2181 case BuiltinType::OCLEvent: 2182 case BuiltinType::OCLClkEvent: 2183 case BuiltinType::OCLQueue: 2184 case BuiltinType::OCLReserveID: 2185 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 2186 case BuiltinType::Id: 2187 #include "clang/Basic/OpenCLImageTypes.def" 2188 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 2189 case BuiltinType::Id: 2190 #include "clang/Basic/OpenCLExtensionTypes.def" 2191 AS = getTargetAddressSpace( 2192 Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T))); 2193 Width = Target->getPointerWidth(AS); 2194 Align = Target->getPointerAlign(AS); 2195 break; 2196 // The SVE types are effectively target-specific. The length of an 2197 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple 2198 // of 128 bits. There is one predicate bit for each vector byte, so the 2199 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits. 2200 // 2201 // Because the length is only known at runtime, we use a dummy value 2202 // of 0 for the static length. The alignment values are those defined 2203 // by the Procedure Call Standard for the Arm Architecture. 2204 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \ 2205 IsSigned, IsFP, IsBF) \ 2206 case BuiltinType::Id: \ 2207 Width = 0; \ 2208 Align = 128; \ 2209 break; 2210 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \ 2211 case BuiltinType::Id: \ 2212 Width = 0; \ 2213 Align = 16; \ 2214 break; 2215 #include "clang/Basic/AArch64SVEACLETypes.def" 2216 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 2217 case BuiltinType::Id: \ 2218 Width = Size; \ 2219 Align = Size; \ 2220 break; 2221 #include "clang/Basic/PPCTypes.def" 2222 #define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \ 2223 IsFP) \ 2224 case BuiltinType::Id: \ 2225 Width = 0; \ 2226 Align = ElBits; \ 2227 break; 2228 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \ 2229 case BuiltinType::Id: \ 2230 Width = 0; \ 2231 Align = 8; \ 2232 break; 2233 #include "clang/Basic/RISCVVTypes.def" 2234 } 2235 break; 2236 case Type::ObjCObjectPointer: 2237 Width = Target->getPointerWidth(0); 2238 Align = Target->getPointerAlign(0); 2239 break; 2240 case Type::BlockPointer: 2241 AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType()); 2242 Width = Target->getPointerWidth(AS); 2243 Align = Target->getPointerAlign(AS); 2244 break; 2245 case Type::LValueReference: 2246 case Type::RValueReference: 2247 // alignof and sizeof should never enter this code path here, so we go 2248 // the pointer route. 2249 AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType()); 2250 Width = Target->getPointerWidth(AS); 2251 Align = Target->getPointerAlign(AS); 2252 break; 2253 case Type::Pointer: 2254 AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType()); 2255 Width = Target->getPointerWidth(AS); 2256 Align = Target->getPointerAlign(AS); 2257 break; 2258 case Type::MemberPointer: { 2259 const auto *MPT = cast<MemberPointerType>(T); 2260 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT); 2261 Width = MPI.Width; 2262 Align = MPI.Align; 2263 break; 2264 } 2265 case Type::Complex: { 2266 // Complex types have the same alignment as their elements, but twice the 2267 // size. 2268 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType()); 2269 Width = EltInfo.Width * 2; 2270 Align = EltInfo.Align; 2271 break; 2272 } 2273 case Type::ObjCObject: 2274 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr()); 2275 case Type::Adjusted: 2276 case Type::Decayed: 2277 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr()); 2278 case Type::ObjCInterface: { 2279 const auto *ObjCI = cast<ObjCInterfaceType>(T); 2280 if (ObjCI->getDecl()->isInvalidDecl()) { 2281 Width = 8; 2282 Align = 8; 2283 break; 2284 } 2285 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 2286 Width = toBits(Layout.getSize()); 2287 Align = toBits(Layout.getAlignment()); 2288 break; 2289 } 2290 case Type::BitInt: { 2291 const auto *EIT = cast<BitIntType>(T); 2292 Align = 2293 std::min(static_cast<unsigned>(std::max( 2294 getCharWidth(), llvm::PowerOf2Ceil(EIT->getNumBits()))), 2295 Target->getLongLongAlign()); 2296 Width = llvm::alignTo(EIT->getNumBits(), Align); 2297 break; 2298 } 2299 case Type::Record: 2300 case Type::Enum: { 2301 const auto *TT = cast<TagType>(T); 2302 2303 if (TT->getDecl()->isInvalidDecl()) { 2304 Width = 8; 2305 Align = 8; 2306 break; 2307 } 2308 2309 if (const auto *ET = dyn_cast<EnumType>(TT)) { 2310 const EnumDecl *ED = ET->getDecl(); 2311 TypeInfo Info = 2312 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType()); 2313 if (unsigned AttrAlign = ED->getMaxAlignment()) { 2314 Info.Align = AttrAlign; 2315 Info.AlignRequirement = AlignRequirementKind::RequiredByEnum; 2316 } 2317 return Info; 2318 } 2319 2320 const auto *RT = cast<RecordType>(TT); 2321 const RecordDecl *RD = RT->getDecl(); 2322 const ASTRecordLayout &Layout = getASTRecordLayout(RD); 2323 Width = toBits(Layout.getSize()); 2324 Align = toBits(Layout.getAlignment()); 2325 AlignRequirement = RD->hasAttr<AlignedAttr>() 2326 ? AlignRequirementKind::RequiredByRecord 2327 : AlignRequirementKind::None; 2328 break; 2329 } 2330 2331 case Type::SubstTemplateTypeParm: 2332 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)-> 2333 getReplacementType().getTypePtr()); 2334 2335 case Type::Auto: 2336 case Type::DeducedTemplateSpecialization: { 2337 const auto *A = cast<DeducedType>(T); 2338 assert(!A->getDeducedType().isNull() && 2339 "cannot request the size of an undeduced or dependent auto type"); 2340 return getTypeInfo(A->getDeducedType().getTypePtr()); 2341 } 2342 2343 case Type::Paren: 2344 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr()); 2345 2346 case Type::MacroQualified: 2347 return getTypeInfo( 2348 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr()); 2349 2350 case Type::ObjCTypeParam: 2351 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr()); 2352 2353 case Type::Using: 2354 return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr()); 2355 2356 case Type::Typedef: { 2357 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl(); 2358 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr()); 2359 // If the typedef has an aligned attribute on it, it overrides any computed 2360 // alignment we have. This violates the GCC documentation (which says that 2361 // attribute(aligned) can only round up) but matches its implementation. 2362 if (unsigned AttrAlign = Typedef->getMaxAlignment()) { 2363 Align = AttrAlign; 2364 AlignRequirement = AlignRequirementKind::RequiredByTypedef; 2365 } else { 2366 Align = Info.Align; 2367 AlignRequirement = Info.AlignRequirement; 2368 } 2369 Width = Info.Width; 2370 break; 2371 } 2372 2373 case Type::Elaborated: 2374 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr()); 2375 2376 case Type::Attributed: 2377 return getTypeInfo( 2378 cast<AttributedType>(T)->getEquivalentType().getTypePtr()); 2379 2380 case Type::Atomic: { 2381 // Start with the base type information. 2382 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType()); 2383 Width = Info.Width; 2384 Align = Info.Align; 2385 2386 if (!Width) { 2387 // An otherwise zero-sized type should still generate an 2388 // atomic operation. 2389 Width = Target->getCharWidth(); 2390 assert(Align); 2391 } else if (Width <= Target->getMaxAtomicPromoteWidth()) { 2392 // If the size of the type doesn't exceed the platform's max 2393 // atomic promotion width, make the size and alignment more 2394 // favorable to atomic operations: 2395 2396 // Round the size up to a power of 2. 2397 if (!llvm::isPowerOf2_64(Width)) 2398 Width = llvm::NextPowerOf2(Width); 2399 2400 // Set the alignment equal to the size. 2401 Align = static_cast<unsigned>(Width); 2402 } 2403 } 2404 break; 2405 2406 case Type::Pipe: 2407 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global)); 2408 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global)); 2409 break; 2410 } 2411 2412 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2"); 2413 return TypeInfo(Width, Align, AlignRequirement); 2414 } 2415 2416 unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const { 2417 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T); 2418 if (I != MemoizedUnadjustedAlign.end()) 2419 return I->second; 2420 2421 unsigned UnadjustedAlign; 2422 if (const auto *RT = T->getAs<RecordType>()) { 2423 const RecordDecl *RD = RT->getDecl(); 2424 const ASTRecordLayout &Layout = getASTRecordLayout(RD); 2425 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment()); 2426 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) { 2427 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 2428 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment()); 2429 } else { 2430 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType()); 2431 } 2432 2433 MemoizedUnadjustedAlign[T] = UnadjustedAlign; 2434 return UnadjustedAlign; 2435 } 2436 2437 unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const { 2438 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign(); 2439 return SimdAlign; 2440 } 2441 2442 /// toCharUnitsFromBits - Convert a size in bits to a size in characters. 2443 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const { 2444 return CharUnits::fromQuantity(BitSize / getCharWidth()); 2445 } 2446 2447 /// toBits - Convert a size in characters to a size in characters. 2448 int64_t ASTContext::toBits(CharUnits CharSize) const { 2449 return CharSize.getQuantity() * getCharWidth(); 2450 } 2451 2452 /// getTypeSizeInChars - Return the size of the specified type, in characters. 2453 /// This method does not work on incomplete types. 2454 CharUnits ASTContext::getTypeSizeInChars(QualType T) const { 2455 return getTypeInfoInChars(T).Width; 2456 } 2457 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const { 2458 return getTypeInfoInChars(T).Width; 2459 } 2460 2461 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in 2462 /// characters. This method does not work on incomplete types. 2463 CharUnits ASTContext::getTypeAlignInChars(QualType T) const { 2464 return toCharUnitsFromBits(getTypeAlign(T)); 2465 } 2466 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const { 2467 return toCharUnitsFromBits(getTypeAlign(T)); 2468 } 2469 2470 /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a 2471 /// type, in characters, before alignment adustments. This method does 2472 /// not work on incomplete types. 2473 CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const { 2474 return toCharUnitsFromBits(getTypeUnadjustedAlign(T)); 2475 } 2476 CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const { 2477 return toCharUnitsFromBits(getTypeUnadjustedAlign(T)); 2478 } 2479 2480 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified 2481 /// type for the current target in bits. This can be different than the ABI 2482 /// alignment in cases where it is beneficial for performance or backwards 2483 /// compatibility preserving to overalign a data type. (Note: despite the name, 2484 /// the preferred alignment is ABI-impacting, and not an optimization.) 2485 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const { 2486 TypeInfo TI = getTypeInfo(T); 2487 unsigned ABIAlign = TI.Align; 2488 2489 T = T->getBaseElementTypeUnsafe(); 2490 2491 // The preferred alignment of member pointers is that of a pointer. 2492 if (T->isMemberPointerType()) 2493 return getPreferredTypeAlign(getPointerDiffType().getTypePtr()); 2494 2495 if (!Target->allowsLargerPreferedTypeAlignment()) 2496 return ABIAlign; 2497 2498 if (const auto *RT = T->getAs<RecordType>()) { 2499 const RecordDecl *RD = RT->getDecl(); 2500 2501 // When used as part of a typedef, or together with a 'packed' attribute, 2502 // the 'aligned' attribute can be used to decrease alignment. Note that the 2503 // 'packed' case is already taken into consideration when computing the 2504 // alignment, we only need to handle the typedef case here. 2505 if (TI.AlignRequirement == AlignRequirementKind::RequiredByTypedef || 2506 RD->isInvalidDecl()) 2507 return ABIAlign; 2508 2509 unsigned PreferredAlign = static_cast<unsigned>( 2510 toBits(getASTRecordLayout(RD).PreferredAlignment)); 2511 assert(PreferredAlign >= ABIAlign && 2512 "PreferredAlign should be at least as large as ABIAlign."); 2513 return PreferredAlign; 2514 } 2515 2516 // Double (and, for targets supporting AIX `power` alignment, long double) and 2517 // long long should be naturally aligned (despite requiring less alignment) if 2518 // possible. 2519 if (const auto *CT = T->getAs<ComplexType>()) 2520 T = CT->getElementType().getTypePtr(); 2521 if (const auto *ET = T->getAs<EnumType>()) 2522 T = ET->getDecl()->getIntegerType().getTypePtr(); 2523 if (T->isSpecificBuiltinType(BuiltinType::Double) || 2524 T->isSpecificBuiltinType(BuiltinType::LongLong) || 2525 T->isSpecificBuiltinType(BuiltinType::ULongLong) || 2526 (T->isSpecificBuiltinType(BuiltinType::LongDouble) && 2527 Target->defaultsToAIXPowerAlignment())) 2528 // Don't increase the alignment if an alignment attribute was specified on a 2529 // typedef declaration. 2530 if (!TI.isAlignRequired()) 2531 return std::max(ABIAlign, (unsigned)getTypeSize(T)); 2532 2533 return ABIAlign; 2534 } 2535 2536 /// getTargetDefaultAlignForAttributeAligned - Return the default alignment 2537 /// for __attribute__((aligned)) on this target, to be used if no alignment 2538 /// value is specified. 2539 unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const { 2540 return getTargetInfo().getDefaultAlignForAttributeAligned(); 2541 } 2542 2543 /// getAlignOfGlobalVar - Return the alignment in bits that should be given 2544 /// to a global variable of the specified type. 2545 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const { 2546 uint64_t TypeSize = getTypeSize(T.getTypePtr()); 2547 return std::max(getPreferredTypeAlign(T), 2548 getTargetInfo().getMinGlobalAlign(TypeSize)); 2549 } 2550 2551 /// getAlignOfGlobalVarInChars - Return the alignment in characters that 2552 /// should be given to a global variable of the specified type. 2553 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const { 2554 return toCharUnitsFromBits(getAlignOfGlobalVar(T)); 2555 } 2556 2557 CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const { 2558 CharUnits Offset = CharUnits::Zero(); 2559 const ASTRecordLayout *Layout = &getASTRecordLayout(RD); 2560 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) { 2561 Offset += Layout->getBaseClassOffset(Base); 2562 Layout = &getASTRecordLayout(Base); 2563 } 2564 return Offset; 2565 } 2566 2567 CharUnits ASTContext::getMemberPointerPathAdjustment(const APValue &MP) const { 2568 const ValueDecl *MPD = MP.getMemberPointerDecl(); 2569 CharUnits ThisAdjustment = CharUnits::Zero(); 2570 ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath(); 2571 bool DerivedMember = MP.isMemberPointerToDerivedMember(); 2572 const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext()); 2573 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 2574 const CXXRecordDecl *Base = RD; 2575 const CXXRecordDecl *Derived = Path[I]; 2576 if (DerivedMember) 2577 std::swap(Base, Derived); 2578 ThisAdjustment += getASTRecordLayout(Derived).getBaseClassOffset(Base); 2579 RD = Path[I]; 2580 } 2581 if (DerivedMember) 2582 ThisAdjustment = -ThisAdjustment; 2583 return ThisAdjustment; 2584 } 2585 2586 /// DeepCollectObjCIvars - 2587 /// This routine first collects all declared, but not synthesized, ivars in 2588 /// super class and then collects all ivars, including those synthesized for 2589 /// current class. This routine is used for implementation of current class 2590 /// when all ivars, declared and synthesized are known. 2591 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, 2592 bool leafClass, 2593 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const { 2594 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass()) 2595 DeepCollectObjCIvars(SuperClass, false, Ivars); 2596 if (!leafClass) { 2597 for (const auto *I : OI->ivars()) 2598 Ivars.push_back(I); 2599 } else { 2600 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI); 2601 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv; 2602 Iv= Iv->getNextIvar()) 2603 Ivars.push_back(Iv); 2604 } 2605 } 2606 2607 /// CollectInheritedProtocols - Collect all protocols in current class and 2608 /// those inherited by it. 2609 void ASTContext::CollectInheritedProtocols(const Decl *CDecl, 2610 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) { 2611 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) { 2612 // We can use protocol_iterator here instead of 2613 // all_referenced_protocol_iterator since we are walking all categories. 2614 for (auto *Proto : OI->all_referenced_protocols()) { 2615 CollectInheritedProtocols(Proto, Protocols); 2616 } 2617 2618 // Categories of this Interface. 2619 for (const auto *Cat : OI->visible_categories()) 2620 CollectInheritedProtocols(Cat, Protocols); 2621 2622 if (ObjCInterfaceDecl *SD = OI->getSuperClass()) 2623 while (SD) { 2624 CollectInheritedProtocols(SD, Protocols); 2625 SD = SD->getSuperClass(); 2626 } 2627 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) { 2628 for (auto *Proto : OC->protocols()) { 2629 CollectInheritedProtocols(Proto, Protocols); 2630 } 2631 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) { 2632 // Insert the protocol. 2633 if (!Protocols.insert( 2634 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second) 2635 return; 2636 2637 for (auto *Proto : OP->protocols()) 2638 CollectInheritedProtocols(Proto, Protocols); 2639 } 2640 } 2641 2642 static bool unionHasUniqueObjectRepresentations(const ASTContext &Context, 2643 const RecordDecl *RD) { 2644 assert(RD->isUnion() && "Must be union type"); 2645 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl()); 2646 2647 for (const auto *Field : RD->fields()) { 2648 if (!Context.hasUniqueObjectRepresentations(Field->getType())) 2649 return false; 2650 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType()); 2651 if (FieldSize != UnionSize) 2652 return false; 2653 } 2654 return !RD->field_empty(); 2655 } 2656 2657 static int64_t getSubobjectOffset(const FieldDecl *Field, 2658 const ASTContext &Context, 2659 const clang::ASTRecordLayout & /*Layout*/) { 2660 return Context.getFieldOffset(Field); 2661 } 2662 2663 static int64_t getSubobjectOffset(const CXXRecordDecl *RD, 2664 const ASTContext &Context, 2665 const clang::ASTRecordLayout &Layout) { 2666 return Context.toBits(Layout.getBaseClassOffset(RD)); 2667 } 2668 2669 static llvm::Optional<int64_t> 2670 structHasUniqueObjectRepresentations(const ASTContext &Context, 2671 const RecordDecl *RD); 2672 2673 static llvm::Optional<int64_t> 2674 getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context) { 2675 if (Field->getType()->isRecordType()) { 2676 const RecordDecl *RD = Field->getType()->getAsRecordDecl(); 2677 if (!RD->isUnion()) 2678 return structHasUniqueObjectRepresentations(Context, RD); 2679 } 2680 if (!Field->getType()->isReferenceType() && 2681 !Context.hasUniqueObjectRepresentations(Field->getType())) 2682 return llvm::None; 2683 2684 int64_t FieldSizeInBits = 2685 Context.toBits(Context.getTypeSizeInChars(Field->getType())); 2686 if (Field->isBitField()) { 2687 int64_t BitfieldSize = Field->getBitWidthValue(Context); 2688 if (BitfieldSize > FieldSizeInBits) 2689 return llvm::None; 2690 FieldSizeInBits = BitfieldSize; 2691 } 2692 return FieldSizeInBits; 2693 } 2694 2695 static llvm::Optional<int64_t> 2696 getSubobjectSizeInBits(const CXXRecordDecl *RD, const ASTContext &Context) { 2697 return structHasUniqueObjectRepresentations(Context, RD); 2698 } 2699 2700 template <typename RangeT> 2701 static llvm::Optional<int64_t> structSubobjectsHaveUniqueObjectRepresentations( 2702 const RangeT &Subobjects, int64_t CurOffsetInBits, 2703 const ASTContext &Context, const clang::ASTRecordLayout &Layout) { 2704 for (const auto *Subobject : Subobjects) { 2705 llvm::Optional<int64_t> SizeInBits = 2706 getSubobjectSizeInBits(Subobject, Context); 2707 if (!SizeInBits) 2708 return llvm::None; 2709 if (*SizeInBits != 0) { 2710 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout); 2711 if (Offset != CurOffsetInBits) 2712 return llvm::None; 2713 CurOffsetInBits += *SizeInBits; 2714 } 2715 } 2716 return CurOffsetInBits; 2717 } 2718 2719 static llvm::Optional<int64_t> 2720 structHasUniqueObjectRepresentations(const ASTContext &Context, 2721 const RecordDecl *RD) { 2722 assert(!RD->isUnion() && "Must be struct/class type"); 2723 const auto &Layout = Context.getASTRecordLayout(RD); 2724 2725 int64_t CurOffsetInBits = 0; 2726 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) { 2727 if (ClassDecl->isDynamicClass()) 2728 return llvm::None; 2729 2730 SmallVector<CXXRecordDecl *, 4> Bases; 2731 for (const auto &Base : ClassDecl->bases()) { 2732 // Empty types can be inherited from, and non-empty types can potentially 2733 // have tail padding, so just make sure there isn't an error. 2734 Bases.emplace_back(Base.getType()->getAsCXXRecordDecl()); 2735 } 2736 2737 llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) { 2738 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R); 2739 }); 2740 2741 llvm::Optional<int64_t> OffsetAfterBases = 2742 structSubobjectsHaveUniqueObjectRepresentations(Bases, CurOffsetInBits, 2743 Context, Layout); 2744 if (!OffsetAfterBases) 2745 return llvm::None; 2746 CurOffsetInBits = *OffsetAfterBases; 2747 } 2748 2749 llvm::Optional<int64_t> OffsetAfterFields = 2750 structSubobjectsHaveUniqueObjectRepresentations( 2751 RD->fields(), CurOffsetInBits, Context, Layout); 2752 if (!OffsetAfterFields) 2753 return llvm::None; 2754 CurOffsetInBits = *OffsetAfterFields; 2755 2756 return CurOffsetInBits; 2757 } 2758 2759 bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const { 2760 // C++17 [meta.unary.prop]: 2761 // The predicate condition for a template specialization 2762 // has_unique_object_representations<T> shall be 2763 // satisfied if and only if: 2764 // (9.1) - T is trivially copyable, and 2765 // (9.2) - any two objects of type T with the same value have the same 2766 // object representation, where two objects 2767 // of array or non-union class type are considered to have the same value 2768 // if their respective sequences of 2769 // direct subobjects have the same values, and two objects of union type 2770 // are considered to have the same 2771 // value if they have the same active member and the corresponding members 2772 // have the same value. 2773 // The set of scalar types for which this condition holds is 2774 // implementation-defined. [ Note: If a type has padding 2775 // bits, the condition does not hold; otherwise, the condition holds true 2776 // for unsigned integral types. -- end note ] 2777 assert(!Ty.isNull() && "Null QualType sent to unique object rep check"); 2778 2779 // Arrays are unique only if their element type is unique. 2780 if (Ty->isArrayType()) 2781 return hasUniqueObjectRepresentations(getBaseElementType(Ty)); 2782 2783 // (9.1) - T is trivially copyable... 2784 if (!Ty.isTriviallyCopyableType(*this)) 2785 return false; 2786 2787 // All integrals and enums are unique. 2788 if (Ty->isIntegralOrEnumerationType()) 2789 return true; 2790 2791 // All other pointers are unique. 2792 if (Ty->isPointerType()) 2793 return true; 2794 2795 if (Ty->isMemberPointerType()) { 2796 const auto *MPT = Ty->getAs<MemberPointerType>(); 2797 return !ABI->getMemberPointerInfo(MPT).HasPadding; 2798 } 2799 2800 if (Ty->isRecordType()) { 2801 const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl(); 2802 2803 if (Record->isInvalidDecl()) 2804 return false; 2805 2806 if (Record->isUnion()) 2807 return unionHasUniqueObjectRepresentations(*this, Record); 2808 2809 Optional<int64_t> StructSize = 2810 structHasUniqueObjectRepresentations(*this, Record); 2811 2812 return StructSize && 2813 StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty)); 2814 } 2815 2816 // FIXME: More cases to handle here (list by rsmith): 2817 // vectors (careful about, eg, vector of 3 foo) 2818 // _Complex int and friends 2819 // _Atomic T 2820 // Obj-C block pointers 2821 // Obj-C object pointers 2822 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t, 2823 // clk_event_t, queue_t, reserve_id_t) 2824 // There're also Obj-C class types and the Obj-C selector type, but I think it 2825 // makes sense for those to return false here. 2826 2827 return false; 2828 } 2829 2830 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const { 2831 unsigned count = 0; 2832 // Count ivars declared in class extension. 2833 for (const auto *Ext : OI->known_extensions()) 2834 count += Ext->ivar_size(); 2835 2836 // Count ivar defined in this class's implementation. This 2837 // includes synthesized ivars. 2838 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) 2839 count += ImplDecl->ivar_size(); 2840 2841 return count; 2842 } 2843 2844 bool ASTContext::isSentinelNullExpr(const Expr *E) { 2845 if (!E) 2846 return false; 2847 2848 // nullptr_t is always treated as null. 2849 if (E->getType()->isNullPtrType()) return true; 2850 2851 if (E->getType()->isAnyPointerType() && 2852 E->IgnoreParenCasts()->isNullPointerConstant(*this, 2853 Expr::NPC_ValueDependentIsNull)) 2854 return true; 2855 2856 // Unfortunately, __null has type 'int'. 2857 if (isa<GNUNullExpr>(E)) return true; 2858 2859 return false; 2860 } 2861 2862 /// Get the implementation of ObjCInterfaceDecl, or nullptr if none 2863 /// exists. 2864 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) { 2865 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 2866 I = ObjCImpls.find(D); 2867 if (I != ObjCImpls.end()) 2868 return cast<ObjCImplementationDecl>(I->second); 2869 return nullptr; 2870 } 2871 2872 /// Get the implementation of ObjCCategoryDecl, or nullptr if none 2873 /// exists. 2874 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) { 2875 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 2876 I = ObjCImpls.find(D); 2877 if (I != ObjCImpls.end()) 2878 return cast<ObjCCategoryImplDecl>(I->second); 2879 return nullptr; 2880 } 2881 2882 /// Set the implementation of ObjCInterfaceDecl. 2883 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD, 2884 ObjCImplementationDecl *ImplD) { 2885 assert(IFaceD && ImplD && "Passed null params"); 2886 ObjCImpls[IFaceD] = ImplD; 2887 } 2888 2889 /// Set the implementation of ObjCCategoryDecl. 2890 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD, 2891 ObjCCategoryImplDecl *ImplD) { 2892 assert(CatD && ImplD && "Passed null params"); 2893 ObjCImpls[CatD] = ImplD; 2894 } 2895 2896 const ObjCMethodDecl * 2897 ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const { 2898 return ObjCMethodRedecls.lookup(MD); 2899 } 2900 2901 void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD, 2902 const ObjCMethodDecl *Redecl) { 2903 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration"); 2904 ObjCMethodRedecls[MD] = Redecl; 2905 } 2906 2907 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface( 2908 const NamedDecl *ND) const { 2909 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext())) 2910 return ID; 2911 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext())) 2912 return CD->getClassInterface(); 2913 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext())) 2914 return IMD->getClassInterface(); 2915 2916 return nullptr; 2917 } 2918 2919 /// Get the copy initialization expression of VarDecl, or nullptr if 2920 /// none exists. 2921 BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const { 2922 assert(VD && "Passed null params"); 2923 assert(VD->hasAttr<BlocksAttr>() && 2924 "getBlockVarCopyInits - not __block var"); 2925 auto I = BlockVarCopyInits.find(VD); 2926 if (I != BlockVarCopyInits.end()) 2927 return I->second; 2928 return {nullptr, false}; 2929 } 2930 2931 /// Set the copy initialization expression of a block var decl. 2932 void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr, 2933 bool CanThrow) { 2934 assert(VD && CopyExpr && "Passed null params"); 2935 assert(VD->hasAttr<BlocksAttr>() && 2936 "setBlockVarCopyInits - not __block var"); 2937 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow); 2938 } 2939 2940 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T, 2941 unsigned DataSize) const { 2942 if (!DataSize) 2943 DataSize = TypeLoc::getFullDataSizeForType(T); 2944 else 2945 assert(DataSize == TypeLoc::getFullDataSizeForType(T) && 2946 "incorrect data size provided to CreateTypeSourceInfo!"); 2947 2948 auto *TInfo = 2949 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8); 2950 new (TInfo) TypeSourceInfo(T); 2951 return TInfo; 2952 } 2953 2954 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T, 2955 SourceLocation L) const { 2956 TypeSourceInfo *DI = CreateTypeSourceInfo(T); 2957 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L); 2958 return DI; 2959 } 2960 2961 const ASTRecordLayout & 2962 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const { 2963 return getObjCLayout(D, nullptr); 2964 } 2965 2966 const ASTRecordLayout & 2967 ASTContext::getASTObjCImplementationLayout( 2968 const ObjCImplementationDecl *D) const { 2969 return getObjCLayout(D->getClassInterface(), D); 2970 } 2971 2972 //===----------------------------------------------------------------------===// 2973 // Type creation/memoization methods 2974 //===----------------------------------------------------------------------===// 2975 2976 QualType 2977 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const { 2978 unsigned fastQuals = quals.getFastQualifiers(); 2979 quals.removeFastQualifiers(); 2980 2981 // Check if we've already instantiated this type. 2982 llvm::FoldingSetNodeID ID; 2983 ExtQuals::Profile(ID, baseType, quals); 2984 void *insertPos = nullptr; 2985 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) { 2986 assert(eq->getQualifiers() == quals); 2987 return QualType(eq, fastQuals); 2988 } 2989 2990 // If the base type is not canonical, make the appropriate canonical type. 2991 QualType canon; 2992 if (!baseType->isCanonicalUnqualified()) { 2993 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split(); 2994 canonSplit.Quals.addConsistentQualifiers(quals); 2995 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals); 2996 2997 // Re-find the insert position. 2998 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos); 2999 } 3000 3001 auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals); 3002 ExtQualNodes.InsertNode(eq, insertPos); 3003 return QualType(eq, fastQuals); 3004 } 3005 3006 QualType ASTContext::getAddrSpaceQualType(QualType T, 3007 LangAS AddressSpace) const { 3008 QualType CanT = getCanonicalType(T); 3009 if (CanT.getAddressSpace() == AddressSpace) 3010 return T; 3011 3012 // If we are composing extended qualifiers together, merge together 3013 // into one ExtQuals node. 3014 QualifierCollector Quals; 3015 const Type *TypeNode = Quals.strip(T); 3016 3017 // If this type already has an address space specified, it cannot get 3018 // another one. 3019 assert(!Quals.hasAddressSpace() && 3020 "Type cannot be in multiple addr spaces!"); 3021 Quals.addAddressSpace(AddressSpace); 3022 3023 return getExtQualType(TypeNode, Quals); 3024 } 3025 3026 QualType ASTContext::removeAddrSpaceQualType(QualType T) const { 3027 // If the type is not qualified with an address space, just return it 3028 // immediately. 3029 if (!T.hasAddressSpace()) 3030 return T; 3031 3032 // If we are composing extended qualifiers together, merge together 3033 // into one ExtQuals node. 3034 QualifierCollector Quals; 3035 const Type *TypeNode; 3036 3037 while (T.hasAddressSpace()) { 3038 TypeNode = Quals.strip(T); 3039 3040 // If the type no longer has an address space after stripping qualifiers, 3041 // jump out. 3042 if (!QualType(TypeNode, 0).hasAddressSpace()) 3043 break; 3044 3045 // There might be sugar in the way. Strip it and try again. 3046 T = T.getSingleStepDesugaredType(*this); 3047 } 3048 3049 Quals.removeAddressSpace(); 3050 3051 // Removal of the address space can mean there are no longer any 3052 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts) 3053 // or required. 3054 if (Quals.hasNonFastQualifiers()) 3055 return getExtQualType(TypeNode, Quals); 3056 else 3057 return QualType(TypeNode, Quals.getFastQualifiers()); 3058 } 3059 3060 QualType ASTContext::getObjCGCQualType(QualType T, 3061 Qualifiers::GC GCAttr) const { 3062 QualType CanT = getCanonicalType(T); 3063 if (CanT.getObjCGCAttr() == GCAttr) 3064 return T; 3065 3066 if (const auto *ptr = T->getAs<PointerType>()) { 3067 QualType Pointee = ptr->getPointeeType(); 3068 if (Pointee->isAnyPointerType()) { 3069 QualType ResultType = getObjCGCQualType(Pointee, GCAttr); 3070 return getPointerType(ResultType); 3071 } 3072 } 3073 3074 // If we are composing extended qualifiers together, merge together 3075 // into one ExtQuals node. 3076 QualifierCollector Quals; 3077 const Type *TypeNode = Quals.strip(T); 3078 3079 // If this type already has an ObjCGC specified, it cannot get 3080 // another one. 3081 assert(!Quals.hasObjCGCAttr() && 3082 "Type cannot have multiple ObjCGCs!"); 3083 Quals.addObjCGCAttr(GCAttr); 3084 3085 return getExtQualType(TypeNode, Quals); 3086 } 3087 3088 QualType ASTContext::removePtrSizeAddrSpace(QualType T) const { 3089 if (const PointerType *Ptr = T->getAs<PointerType>()) { 3090 QualType Pointee = Ptr->getPointeeType(); 3091 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) { 3092 return getPointerType(removeAddrSpaceQualType(Pointee)); 3093 } 3094 } 3095 return T; 3096 } 3097 3098 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T, 3099 FunctionType::ExtInfo Info) { 3100 if (T->getExtInfo() == Info) 3101 return T; 3102 3103 QualType Result; 3104 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) { 3105 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info); 3106 } else { 3107 const auto *FPT = cast<FunctionProtoType>(T); 3108 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 3109 EPI.ExtInfo = Info; 3110 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI); 3111 } 3112 3113 return cast<FunctionType>(Result.getTypePtr()); 3114 } 3115 3116 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD, 3117 QualType ResultType) { 3118 FD = FD->getMostRecentDecl(); 3119 while (true) { 3120 const auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 3121 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 3122 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI)); 3123 if (FunctionDecl *Next = FD->getPreviousDecl()) 3124 FD = Next; 3125 else 3126 break; 3127 } 3128 if (ASTMutationListener *L = getASTMutationListener()) 3129 L->DeducedReturnType(FD, ResultType); 3130 } 3131 3132 /// Get a function type and produce the equivalent function type with the 3133 /// specified exception specification. Type sugar that can be present on a 3134 /// declaration of a function with an exception specification is permitted 3135 /// and preserved. Other type sugar (for instance, typedefs) is not. 3136 QualType ASTContext::getFunctionTypeWithExceptionSpec( 3137 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) { 3138 // Might have some parens. 3139 if (const auto *PT = dyn_cast<ParenType>(Orig)) 3140 return getParenType( 3141 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI)); 3142 3143 // Might be wrapped in a macro qualified type. 3144 if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig)) 3145 return getMacroQualifiedType( 3146 getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI), 3147 MQT->getMacroIdentifier()); 3148 3149 // Might have a calling-convention attribute. 3150 if (const auto *AT = dyn_cast<AttributedType>(Orig)) 3151 return getAttributedType( 3152 AT->getAttrKind(), 3153 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI), 3154 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI)); 3155 3156 // Anything else must be a function type. Rebuild it with the new exception 3157 // specification. 3158 const auto *Proto = Orig->castAs<FunctionProtoType>(); 3159 return getFunctionType( 3160 Proto->getReturnType(), Proto->getParamTypes(), 3161 Proto->getExtProtoInfo().withExceptionSpec(ESI)); 3162 } 3163 3164 bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T, 3165 QualType U) { 3166 return hasSameType(T, U) || 3167 (getLangOpts().CPlusPlus17 && 3168 hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None), 3169 getFunctionTypeWithExceptionSpec(U, EST_None))); 3170 } 3171 3172 QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) { 3173 if (const auto *Proto = T->getAs<FunctionProtoType>()) { 3174 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType()); 3175 SmallVector<QualType, 16> Args(Proto->param_types()); 3176 for (unsigned i = 0, n = Args.size(); i != n; ++i) 3177 Args[i] = removePtrSizeAddrSpace(Args[i]); 3178 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo()); 3179 } 3180 3181 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) { 3182 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType()); 3183 return getFunctionNoProtoType(RetTy, Proto->getExtInfo()); 3184 } 3185 3186 return T; 3187 } 3188 3189 bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) { 3190 return hasSameType(T, U) || 3191 hasSameType(getFunctionTypeWithoutPtrSizes(T), 3192 getFunctionTypeWithoutPtrSizes(U)); 3193 } 3194 3195 void ASTContext::adjustExceptionSpec( 3196 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, 3197 bool AsWritten) { 3198 // Update the type. 3199 QualType Updated = 3200 getFunctionTypeWithExceptionSpec(FD->getType(), ESI); 3201 FD->setType(Updated); 3202 3203 if (!AsWritten) 3204 return; 3205 3206 // Update the type in the type source information too. 3207 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) { 3208 // If the type and the type-as-written differ, we may need to update 3209 // the type-as-written too. 3210 if (TSInfo->getType() != FD->getType()) 3211 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI); 3212 3213 // FIXME: When we get proper type location information for exceptions, 3214 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch 3215 // up the TypeSourceInfo; 3216 assert(TypeLoc::getFullDataSizeForType(Updated) == 3217 TypeLoc::getFullDataSizeForType(TSInfo->getType()) && 3218 "TypeLoc size mismatch from updating exception specification"); 3219 TSInfo->overrideType(Updated); 3220 } 3221 } 3222 3223 /// getComplexType - Return the uniqued reference to the type for a complex 3224 /// number with the specified element type. 3225 QualType ASTContext::getComplexType(QualType T) const { 3226 // Unique pointers, to guarantee there is only one pointer of a particular 3227 // structure. 3228 llvm::FoldingSetNodeID ID; 3229 ComplexType::Profile(ID, T); 3230 3231 void *InsertPos = nullptr; 3232 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos)) 3233 return QualType(CT, 0); 3234 3235 // If the pointee type isn't canonical, this won't be a canonical type either, 3236 // so fill in the canonical type field. 3237 QualType Canonical; 3238 if (!T.isCanonical()) { 3239 Canonical = getComplexType(getCanonicalType(T)); 3240 3241 // Get the new insert position for the node we care about. 3242 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos); 3243 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3244 } 3245 auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical); 3246 Types.push_back(New); 3247 ComplexTypes.InsertNode(New, InsertPos); 3248 return QualType(New, 0); 3249 } 3250 3251 /// getPointerType - Return the uniqued reference to the type for a pointer to 3252 /// the specified type. 3253 QualType ASTContext::getPointerType(QualType T) const { 3254 // Unique pointers, to guarantee there is only one pointer of a particular 3255 // structure. 3256 llvm::FoldingSetNodeID ID; 3257 PointerType::Profile(ID, T); 3258 3259 void *InsertPos = nullptr; 3260 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3261 return QualType(PT, 0); 3262 3263 // If the pointee type isn't canonical, this won't be a canonical type either, 3264 // so fill in the canonical type field. 3265 QualType Canonical; 3266 if (!T.isCanonical()) { 3267 Canonical = getPointerType(getCanonicalType(T)); 3268 3269 // Get the new insert position for the node we care about. 3270 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3271 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3272 } 3273 auto *New = new (*this, TypeAlignment) PointerType(T, Canonical); 3274 Types.push_back(New); 3275 PointerTypes.InsertNode(New, InsertPos); 3276 return QualType(New, 0); 3277 } 3278 3279 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const { 3280 llvm::FoldingSetNodeID ID; 3281 AdjustedType::Profile(ID, Orig, New); 3282 void *InsertPos = nullptr; 3283 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3284 if (AT) 3285 return QualType(AT, 0); 3286 3287 QualType Canonical = getCanonicalType(New); 3288 3289 // Get the new insert position for the node we care about. 3290 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3291 assert(!AT && "Shouldn't be in the map!"); 3292 3293 AT = new (*this, TypeAlignment) 3294 AdjustedType(Type::Adjusted, Orig, New, Canonical); 3295 Types.push_back(AT); 3296 AdjustedTypes.InsertNode(AT, InsertPos); 3297 return QualType(AT, 0); 3298 } 3299 3300 QualType ASTContext::getDecayedType(QualType T) const { 3301 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay"); 3302 3303 QualType Decayed; 3304 3305 // C99 6.7.5.3p7: 3306 // A declaration of a parameter as "array of type" shall be 3307 // adjusted to "qualified pointer to type", where the type 3308 // qualifiers (if any) are those specified within the [ and ] of 3309 // the array type derivation. 3310 if (T->isArrayType()) 3311 Decayed = getArrayDecayedType(T); 3312 3313 // C99 6.7.5.3p8: 3314 // A declaration of a parameter as "function returning type" 3315 // shall be adjusted to "pointer to function returning type", as 3316 // in 6.3.2.1. 3317 if (T->isFunctionType()) 3318 Decayed = getPointerType(T); 3319 3320 llvm::FoldingSetNodeID ID; 3321 AdjustedType::Profile(ID, T, Decayed); 3322 void *InsertPos = nullptr; 3323 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3324 if (AT) 3325 return QualType(AT, 0); 3326 3327 QualType Canonical = getCanonicalType(Decayed); 3328 3329 // Get the new insert position for the node we care about. 3330 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3331 assert(!AT && "Shouldn't be in the map!"); 3332 3333 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical); 3334 Types.push_back(AT); 3335 AdjustedTypes.InsertNode(AT, InsertPos); 3336 return QualType(AT, 0); 3337 } 3338 3339 /// getBlockPointerType - Return the uniqued reference to the type for 3340 /// a pointer to the specified block. 3341 QualType ASTContext::getBlockPointerType(QualType T) const { 3342 assert(T->isFunctionType() && "block of function types only"); 3343 // Unique pointers, to guarantee there is only one block of a particular 3344 // structure. 3345 llvm::FoldingSetNodeID ID; 3346 BlockPointerType::Profile(ID, T); 3347 3348 void *InsertPos = nullptr; 3349 if (BlockPointerType *PT = 3350 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3351 return QualType(PT, 0); 3352 3353 // If the block pointee type isn't canonical, this won't be a canonical 3354 // type either so fill in the canonical type field. 3355 QualType Canonical; 3356 if (!T.isCanonical()) { 3357 Canonical = getBlockPointerType(getCanonicalType(T)); 3358 3359 // Get the new insert position for the node we care about. 3360 BlockPointerType *NewIP = 3361 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3362 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3363 } 3364 auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical); 3365 Types.push_back(New); 3366 BlockPointerTypes.InsertNode(New, InsertPos); 3367 return QualType(New, 0); 3368 } 3369 3370 /// getLValueReferenceType - Return the uniqued reference to the type for an 3371 /// lvalue reference to the specified type. 3372 QualType 3373 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const { 3374 assert((!T->isPlaceholderType() || 3375 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) && 3376 "Unresolved placeholder type"); 3377 3378 // Unique pointers, to guarantee there is only one pointer of a particular 3379 // structure. 3380 llvm::FoldingSetNodeID ID; 3381 ReferenceType::Profile(ID, T, SpelledAsLValue); 3382 3383 void *InsertPos = nullptr; 3384 if (LValueReferenceType *RT = 3385 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 3386 return QualType(RT, 0); 3387 3388 const auto *InnerRef = T->getAs<ReferenceType>(); 3389 3390 // If the referencee type isn't canonical, this won't be a canonical type 3391 // either, so fill in the canonical type field. 3392 QualType Canonical; 3393 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) { 3394 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 3395 Canonical = getLValueReferenceType(getCanonicalType(PointeeType)); 3396 3397 // Get the new insert position for the node we care about. 3398 LValueReferenceType *NewIP = 3399 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 3400 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3401 } 3402 3403 auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical, 3404 SpelledAsLValue); 3405 Types.push_back(New); 3406 LValueReferenceTypes.InsertNode(New, InsertPos); 3407 3408 return QualType(New, 0); 3409 } 3410 3411 /// getRValueReferenceType - Return the uniqued reference to the type for an 3412 /// rvalue reference to the specified type. 3413 QualType ASTContext::getRValueReferenceType(QualType T) const { 3414 assert((!T->isPlaceholderType() || 3415 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) && 3416 "Unresolved placeholder type"); 3417 3418 // Unique pointers, to guarantee there is only one pointer of a particular 3419 // structure. 3420 llvm::FoldingSetNodeID ID; 3421 ReferenceType::Profile(ID, T, false); 3422 3423 void *InsertPos = nullptr; 3424 if (RValueReferenceType *RT = 3425 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 3426 return QualType(RT, 0); 3427 3428 const auto *InnerRef = T->getAs<ReferenceType>(); 3429 3430 // If the referencee type isn't canonical, this won't be a canonical type 3431 // either, so fill in the canonical type field. 3432 QualType Canonical; 3433 if (InnerRef || !T.isCanonical()) { 3434 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 3435 Canonical = getRValueReferenceType(getCanonicalType(PointeeType)); 3436 3437 // Get the new insert position for the node we care about. 3438 RValueReferenceType *NewIP = 3439 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 3440 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3441 } 3442 3443 auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical); 3444 Types.push_back(New); 3445 RValueReferenceTypes.InsertNode(New, InsertPos); 3446 return QualType(New, 0); 3447 } 3448 3449 /// getMemberPointerType - Return the uniqued reference to the type for a 3450 /// member pointer to the specified type, in the specified class. 3451 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const { 3452 // Unique pointers, to guarantee there is only one pointer of a particular 3453 // structure. 3454 llvm::FoldingSetNodeID ID; 3455 MemberPointerType::Profile(ID, T, Cls); 3456 3457 void *InsertPos = nullptr; 3458 if (MemberPointerType *PT = 3459 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3460 return QualType(PT, 0); 3461 3462 // If the pointee or class type isn't canonical, this won't be a canonical 3463 // type either, so fill in the canonical type field. 3464 QualType Canonical; 3465 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) { 3466 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls)); 3467 3468 // Get the new insert position for the node we care about. 3469 MemberPointerType *NewIP = 3470 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3471 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3472 } 3473 auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical); 3474 Types.push_back(New); 3475 MemberPointerTypes.InsertNode(New, InsertPos); 3476 return QualType(New, 0); 3477 } 3478 3479 /// getConstantArrayType - Return the unique reference to the type for an 3480 /// array of the specified element type. 3481 QualType ASTContext::getConstantArrayType(QualType EltTy, 3482 const llvm::APInt &ArySizeIn, 3483 const Expr *SizeExpr, 3484 ArrayType::ArraySizeModifier ASM, 3485 unsigned IndexTypeQuals) const { 3486 assert((EltTy->isDependentType() || 3487 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) && 3488 "Constant array of VLAs is illegal!"); 3489 3490 // We only need the size as part of the type if it's instantiation-dependent. 3491 if (SizeExpr && !SizeExpr->isInstantiationDependent()) 3492 SizeExpr = nullptr; 3493 3494 // Convert the array size into a canonical width matching the pointer size for 3495 // the target. 3496 llvm::APInt ArySize(ArySizeIn); 3497 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth()); 3498 3499 llvm::FoldingSetNodeID ID; 3500 ConstantArrayType::Profile(ID, *this, EltTy, ArySize, SizeExpr, ASM, 3501 IndexTypeQuals); 3502 3503 void *InsertPos = nullptr; 3504 if (ConstantArrayType *ATP = 3505 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 3506 return QualType(ATP, 0); 3507 3508 // If the element type isn't canonical or has qualifiers, or the array bound 3509 // is instantiation-dependent, this won't be a canonical type either, so fill 3510 // in the canonical type field. 3511 QualType Canon; 3512 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) { 3513 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 3514 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr, 3515 ASM, IndexTypeQuals); 3516 Canon = getQualifiedType(Canon, canonSplit.Quals); 3517 3518 // Get the new insert position for the node we care about. 3519 ConstantArrayType *NewIP = 3520 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 3521 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3522 } 3523 3524 void *Mem = Allocate( 3525 ConstantArrayType::totalSizeToAlloc<const Expr *>(SizeExpr ? 1 : 0), 3526 TypeAlignment); 3527 auto *New = new (Mem) 3528 ConstantArrayType(EltTy, Canon, ArySize, SizeExpr, ASM, IndexTypeQuals); 3529 ConstantArrayTypes.InsertNode(New, InsertPos); 3530 Types.push_back(New); 3531 return QualType(New, 0); 3532 } 3533 3534 /// getVariableArrayDecayedType - Turns the given type, which may be 3535 /// variably-modified, into the corresponding type with all the known 3536 /// sizes replaced with [*]. 3537 QualType ASTContext::getVariableArrayDecayedType(QualType type) const { 3538 // Vastly most common case. 3539 if (!type->isVariablyModifiedType()) return type; 3540 3541 QualType result; 3542 3543 SplitQualType split = type.getSplitDesugaredType(); 3544 const Type *ty = split.Ty; 3545 switch (ty->getTypeClass()) { 3546 #define TYPE(Class, Base) 3547 #define ABSTRACT_TYPE(Class, Base) 3548 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 3549 #include "clang/AST/TypeNodes.inc" 3550 llvm_unreachable("didn't desugar past all non-canonical types?"); 3551 3552 // These types should never be variably-modified. 3553 case Type::Builtin: 3554 case Type::Complex: 3555 case Type::Vector: 3556 case Type::DependentVector: 3557 case Type::ExtVector: 3558 case Type::DependentSizedExtVector: 3559 case Type::ConstantMatrix: 3560 case Type::DependentSizedMatrix: 3561 case Type::DependentAddressSpace: 3562 case Type::ObjCObject: 3563 case Type::ObjCInterface: 3564 case Type::ObjCObjectPointer: 3565 case Type::Record: 3566 case Type::Enum: 3567 case Type::UnresolvedUsing: 3568 case Type::TypeOfExpr: 3569 case Type::TypeOf: 3570 case Type::Decltype: 3571 case Type::UnaryTransform: 3572 case Type::DependentName: 3573 case Type::InjectedClassName: 3574 case Type::TemplateSpecialization: 3575 case Type::DependentTemplateSpecialization: 3576 case Type::TemplateTypeParm: 3577 case Type::SubstTemplateTypeParmPack: 3578 case Type::Auto: 3579 case Type::DeducedTemplateSpecialization: 3580 case Type::PackExpansion: 3581 case Type::BitInt: 3582 case Type::DependentBitInt: 3583 llvm_unreachable("type should never be variably-modified"); 3584 3585 // These types can be variably-modified but should never need to 3586 // further decay. 3587 case Type::FunctionNoProto: 3588 case Type::FunctionProto: 3589 case Type::BlockPointer: 3590 case Type::MemberPointer: 3591 case Type::Pipe: 3592 return type; 3593 3594 // These types can be variably-modified. All these modifications 3595 // preserve structure except as noted by comments. 3596 // TODO: if we ever care about optimizing VLAs, there are no-op 3597 // optimizations available here. 3598 case Type::Pointer: 3599 result = getPointerType(getVariableArrayDecayedType( 3600 cast<PointerType>(ty)->getPointeeType())); 3601 break; 3602 3603 case Type::LValueReference: { 3604 const auto *lv = cast<LValueReferenceType>(ty); 3605 result = getLValueReferenceType( 3606 getVariableArrayDecayedType(lv->getPointeeType()), 3607 lv->isSpelledAsLValue()); 3608 break; 3609 } 3610 3611 case Type::RValueReference: { 3612 const auto *lv = cast<RValueReferenceType>(ty); 3613 result = getRValueReferenceType( 3614 getVariableArrayDecayedType(lv->getPointeeType())); 3615 break; 3616 } 3617 3618 case Type::Atomic: { 3619 const auto *at = cast<AtomicType>(ty); 3620 result = getAtomicType(getVariableArrayDecayedType(at->getValueType())); 3621 break; 3622 } 3623 3624 case Type::ConstantArray: { 3625 const auto *cat = cast<ConstantArrayType>(ty); 3626 result = getConstantArrayType( 3627 getVariableArrayDecayedType(cat->getElementType()), 3628 cat->getSize(), 3629 cat->getSizeExpr(), 3630 cat->getSizeModifier(), 3631 cat->getIndexTypeCVRQualifiers()); 3632 break; 3633 } 3634 3635 case Type::DependentSizedArray: { 3636 const auto *dat = cast<DependentSizedArrayType>(ty); 3637 result = getDependentSizedArrayType( 3638 getVariableArrayDecayedType(dat->getElementType()), 3639 dat->getSizeExpr(), 3640 dat->getSizeModifier(), 3641 dat->getIndexTypeCVRQualifiers(), 3642 dat->getBracketsRange()); 3643 break; 3644 } 3645 3646 // Turn incomplete types into [*] types. 3647 case Type::IncompleteArray: { 3648 const auto *iat = cast<IncompleteArrayType>(ty); 3649 result = getVariableArrayType( 3650 getVariableArrayDecayedType(iat->getElementType()), 3651 /*size*/ nullptr, 3652 ArrayType::Normal, 3653 iat->getIndexTypeCVRQualifiers(), 3654 SourceRange()); 3655 break; 3656 } 3657 3658 // Turn VLA types into [*] types. 3659 case Type::VariableArray: { 3660 const auto *vat = cast<VariableArrayType>(ty); 3661 result = getVariableArrayType( 3662 getVariableArrayDecayedType(vat->getElementType()), 3663 /*size*/ nullptr, 3664 ArrayType::Star, 3665 vat->getIndexTypeCVRQualifiers(), 3666 vat->getBracketsRange()); 3667 break; 3668 } 3669 } 3670 3671 // Apply the top-level qualifiers from the original. 3672 return getQualifiedType(result, split.Quals); 3673 } 3674 3675 /// getVariableArrayType - Returns a non-unique reference to the type for a 3676 /// variable array of the specified element type. 3677 QualType ASTContext::getVariableArrayType(QualType EltTy, 3678 Expr *NumElts, 3679 ArrayType::ArraySizeModifier ASM, 3680 unsigned IndexTypeQuals, 3681 SourceRange Brackets) const { 3682 // Since we don't unique expressions, it isn't possible to unique VLA's 3683 // that have an expression provided for their size. 3684 QualType Canon; 3685 3686 // Be sure to pull qualifiers off the element type. 3687 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) { 3688 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 3689 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM, 3690 IndexTypeQuals, Brackets); 3691 Canon = getQualifiedType(Canon, canonSplit.Quals); 3692 } 3693 3694 auto *New = new (*this, TypeAlignment) 3695 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets); 3696 3697 VariableArrayTypes.push_back(New); 3698 Types.push_back(New); 3699 return QualType(New, 0); 3700 } 3701 3702 /// getDependentSizedArrayType - Returns a non-unique reference to 3703 /// the type for a dependently-sized array of the specified element 3704 /// type. 3705 QualType ASTContext::getDependentSizedArrayType(QualType elementType, 3706 Expr *numElements, 3707 ArrayType::ArraySizeModifier ASM, 3708 unsigned elementTypeQuals, 3709 SourceRange brackets) const { 3710 assert((!numElements || numElements->isTypeDependent() || 3711 numElements->isValueDependent()) && 3712 "Size must be type- or value-dependent!"); 3713 3714 // Dependently-sized array types that do not have a specified number 3715 // of elements will have their sizes deduced from a dependent 3716 // initializer. We do no canonicalization here at all, which is okay 3717 // because they can't be used in most locations. 3718 if (!numElements) { 3719 auto *newType 3720 = new (*this, TypeAlignment) 3721 DependentSizedArrayType(*this, elementType, QualType(), 3722 numElements, ASM, elementTypeQuals, 3723 brackets); 3724 Types.push_back(newType); 3725 return QualType(newType, 0); 3726 } 3727 3728 // Otherwise, we actually build a new type every time, but we 3729 // also build a canonical type. 3730 3731 SplitQualType canonElementType = getCanonicalType(elementType).split(); 3732 3733 void *insertPos = nullptr; 3734 llvm::FoldingSetNodeID ID; 3735 DependentSizedArrayType::Profile(ID, *this, 3736 QualType(canonElementType.Ty, 0), 3737 ASM, elementTypeQuals, numElements); 3738 3739 // Look for an existing type with these properties. 3740 DependentSizedArrayType *canonTy = 3741 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos); 3742 3743 // If we don't have one, build one. 3744 if (!canonTy) { 3745 canonTy = new (*this, TypeAlignment) 3746 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0), 3747 QualType(), numElements, ASM, elementTypeQuals, 3748 brackets); 3749 DependentSizedArrayTypes.InsertNode(canonTy, insertPos); 3750 Types.push_back(canonTy); 3751 } 3752 3753 // Apply qualifiers from the element type to the array. 3754 QualType canon = getQualifiedType(QualType(canonTy,0), 3755 canonElementType.Quals); 3756 3757 // If we didn't need extra canonicalization for the element type or the size 3758 // expression, then just use that as our result. 3759 if (QualType(canonElementType.Ty, 0) == elementType && 3760 canonTy->getSizeExpr() == numElements) 3761 return canon; 3762 3763 // Otherwise, we need to build a type which follows the spelling 3764 // of the element type. 3765 auto *sugaredType 3766 = new (*this, TypeAlignment) 3767 DependentSizedArrayType(*this, elementType, canon, numElements, 3768 ASM, elementTypeQuals, brackets); 3769 Types.push_back(sugaredType); 3770 return QualType(sugaredType, 0); 3771 } 3772 3773 QualType ASTContext::getIncompleteArrayType(QualType elementType, 3774 ArrayType::ArraySizeModifier ASM, 3775 unsigned elementTypeQuals) const { 3776 llvm::FoldingSetNodeID ID; 3777 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals); 3778 3779 void *insertPos = nullptr; 3780 if (IncompleteArrayType *iat = 3781 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos)) 3782 return QualType(iat, 0); 3783 3784 // If the element type isn't canonical, this won't be a canonical type 3785 // either, so fill in the canonical type field. We also have to pull 3786 // qualifiers off the element type. 3787 QualType canon; 3788 3789 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) { 3790 SplitQualType canonSplit = getCanonicalType(elementType).split(); 3791 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0), 3792 ASM, elementTypeQuals); 3793 canon = getQualifiedType(canon, canonSplit.Quals); 3794 3795 // Get the new insert position for the node we care about. 3796 IncompleteArrayType *existing = 3797 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos); 3798 assert(!existing && "Shouldn't be in the map!"); (void) existing; 3799 } 3800 3801 auto *newType = new (*this, TypeAlignment) 3802 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals); 3803 3804 IncompleteArrayTypes.InsertNode(newType, insertPos); 3805 Types.push_back(newType); 3806 return QualType(newType, 0); 3807 } 3808 3809 ASTContext::BuiltinVectorTypeInfo 3810 ASTContext::getBuiltinVectorTypeInfo(const BuiltinType *Ty) const { 3811 #define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \ 3812 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \ 3813 NUMVECTORS}; 3814 3815 #define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \ 3816 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS}; 3817 3818 switch (Ty->getKind()) { 3819 default: 3820 llvm_unreachable("Unsupported builtin vector type"); 3821 case BuiltinType::SveInt8: 3822 return SVE_INT_ELTTY(8, 16, true, 1); 3823 case BuiltinType::SveUint8: 3824 return SVE_INT_ELTTY(8, 16, false, 1); 3825 case BuiltinType::SveInt8x2: 3826 return SVE_INT_ELTTY(8, 16, true, 2); 3827 case BuiltinType::SveUint8x2: 3828 return SVE_INT_ELTTY(8, 16, false, 2); 3829 case BuiltinType::SveInt8x3: 3830 return SVE_INT_ELTTY(8, 16, true, 3); 3831 case BuiltinType::SveUint8x3: 3832 return SVE_INT_ELTTY(8, 16, false, 3); 3833 case BuiltinType::SveInt8x4: 3834 return SVE_INT_ELTTY(8, 16, true, 4); 3835 case BuiltinType::SveUint8x4: 3836 return SVE_INT_ELTTY(8, 16, false, 4); 3837 case BuiltinType::SveInt16: 3838 return SVE_INT_ELTTY(16, 8, true, 1); 3839 case BuiltinType::SveUint16: 3840 return SVE_INT_ELTTY(16, 8, false, 1); 3841 case BuiltinType::SveInt16x2: 3842 return SVE_INT_ELTTY(16, 8, true, 2); 3843 case BuiltinType::SveUint16x2: 3844 return SVE_INT_ELTTY(16, 8, false, 2); 3845 case BuiltinType::SveInt16x3: 3846 return SVE_INT_ELTTY(16, 8, true, 3); 3847 case BuiltinType::SveUint16x3: 3848 return SVE_INT_ELTTY(16, 8, false, 3); 3849 case BuiltinType::SveInt16x4: 3850 return SVE_INT_ELTTY(16, 8, true, 4); 3851 case BuiltinType::SveUint16x4: 3852 return SVE_INT_ELTTY(16, 8, false, 4); 3853 case BuiltinType::SveInt32: 3854 return SVE_INT_ELTTY(32, 4, true, 1); 3855 case BuiltinType::SveUint32: 3856 return SVE_INT_ELTTY(32, 4, false, 1); 3857 case BuiltinType::SveInt32x2: 3858 return SVE_INT_ELTTY(32, 4, true, 2); 3859 case BuiltinType::SveUint32x2: 3860 return SVE_INT_ELTTY(32, 4, false, 2); 3861 case BuiltinType::SveInt32x3: 3862 return SVE_INT_ELTTY(32, 4, true, 3); 3863 case BuiltinType::SveUint32x3: 3864 return SVE_INT_ELTTY(32, 4, false, 3); 3865 case BuiltinType::SveInt32x4: 3866 return SVE_INT_ELTTY(32, 4, true, 4); 3867 case BuiltinType::SveUint32x4: 3868 return SVE_INT_ELTTY(32, 4, false, 4); 3869 case BuiltinType::SveInt64: 3870 return SVE_INT_ELTTY(64, 2, true, 1); 3871 case BuiltinType::SveUint64: 3872 return SVE_INT_ELTTY(64, 2, false, 1); 3873 case BuiltinType::SveInt64x2: 3874 return SVE_INT_ELTTY(64, 2, true, 2); 3875 case BuiltinType::SveUint64x2: 3876 return SVE_INT_ELTTY(64, 2, false, 2); 3877 case BuiltinType::SveInt64x3: 3878 return SVE_INT_ELTTY(64, 2, true, 3); 3879 case BuiltinType::SveUint64x3: 3880 return SVE_INT_ELTTY(64, 2, false, 3); 3881 case BuiltinType::SveInt64x4: 3882 return SVE_INT_ELTTY(64, 2, true, 4); 3883 case BuiltinType::SveUint64x4: 3884 return SVE_INT_ELTTY(64, 2, false, 4); 3885 case BuiltinType::SveBool: 3886 return SVE_ELTTY(BoolTy, 16, 1); 3887 case BuiltinType::SveFloat16: 3888 return SVE_ELTTY(HalfTy, 8, 1); 3889 case BuiltinType::SveFloat16x2: 3890 return SVE_ELTTY(HalfTy, 8, 2); 3891 case BuiltinType::SveFloat16x3: 3892 return SVE_ELTTY(HalfTy, 8, 3); 3893 case BuiltinType::SveFloat16x4: 3894 return SVE_ELTTY(HalfTy, 8, 4); 3895 case BuiltinType::SveFloat32: 3896 return SVE_ELTTY(FloatTy, 4, 1); 3897 case BuiltinType::SveFloat32x2: 3898 return SVE_ELTTY(FloatTy, 4, 2); 3899 case BuiltinType::SveFloat32x3: 3900 return SVE_ELTTY(FloatTy, 4, 3); 3901 case BuiltinType::SveFloat32x4: 3902 return SVE_ELTTY(FloatTy, 4, 4); 3903 case BuiltinType::SveFloat64: 3904 return SVE_ELTTY(DoubleTy, 2, 1); 3905 case BuiltinType::SveFloat64x2: 3906 return SVE_ELTTY(DoubleTy, 2, 2); 3907 case BuiltinType::SveFloat64x3: 3908 return SVE_ELTTY(DoubleTy, 2, 3); 3909 case BuiltinType::SveFloat64x4: 3910 return SVE_ELTTY(DoubleTy, 2, 4); 3911 case BuiltinType::SveBFloat16: 3912 return SVE_ELTTY(BFloat16Ty, 8, 1); 3913 case BuiltinType::SveBFloat16x2: 3914 return SVE_ELTTY(BFloat16Ty, 8, 2); 3915 case BuiltinType::SveBFloat16x3: 3916 return SVE_ELTTY(BFloat16Ty, 8, 3); 3917 case BuiltinType::SveBFloat16x4: 3918 return SVE_ELTTY(BFloat16Ty, 8, 4); 3919 #define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \ 3920 IsSigned) \ 3921 case BuiltinType::Id: \ 3922 return {getIntTypeForBitwidth(ElBits, IsSigned), \ 3923 llvm::ElementCount::getScalable(NumEls), NF}; 3924 #define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \ 3925 case BuiltinType::Id: \ 3926 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \ 3927 llvm::ElementCount::getScalable(NumEls), NF}; 3928 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \ 3929 case BuiltinType::Id: \ 3930 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1}; 3931 #include "clang/Basic/RISCVVTypes.def" 3932 } 3933 } 3934 3935 /// getScalableVectorType - Return the unique reference to a scalable vector 3936 /// type of the specified element type and size. VectorType must be a built-in 3937 /// type. 3938 QualType ASTContext::getScalableVectorType(QualType EltTy, 3939 unsigned NumElts) const { 3940 if (Target->hasAArch64SVETypes()) { 3941 uint64_t EltTySize = getTypeSize(EltTy); 3942 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \ 3943 IsSigned, IsFP, IsBF) \ 3944 if (!EltTy->isBooleanType() && \ 3945 ((EltTy->hasIntegerRepresentation() && \ 3946 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \ 3947 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \ 3948 IsFP && !IsBF) || \ 3949 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \ 3950 IsBF && !IsFP)) && \ 3951 EltTySize == ElBits && NumElts == NumEls) { \ 3952 return SingletonId; \ 3953 } 3954 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \ 3955 if (EltTy->isBooleanType() && NumElts == NumEls) \ 3956 return SingletonId; 3957 #include "clang/Basic/AArch64SVEACLETypes.def" 3958 } else if (Target->hasRISCVVTypes()) { 3959 uint64_t EltTySize = getTypeSize(EltTy); 3960 #define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \ 3961 IsFP) \ 3962 if (!EltTy->isBooleanType() && \ 3963 ((EltTy->hasIntegerRepresentation() && \ 3964 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \ 3965 (EltTy->hasFloatingRepresentation() && IsFP)) && \ 3966 EltTySize == ElBits && NumElts == NumEls) \ 3967 return SingletonId; 3968 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \ 3969 if (EltTy->isBooleanType() && NumElts == NumEls) \ 3970 return SingletonId; 3971 #include "clang/Basic/RISCVVTypes.def" 3972 } 3973 return QualType(); 3974 } 3975 3976 /// getVectorType - Return the unique reference to a vector type of 3977 /// the specified element type and size. VectorType must be a built-in type. 3978 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts, 3979 VectorType::VectorKind VecKind) const { 3980 assert(vecType->isBuiltinType()); 3981 3982 // Check if we've already instantiated a vector of this type. 3983 llvm::FoldingSetNodeID ID; 3984 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind); 3985 3986 void *InsertPos = nullptr; 3987 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 3988 return QualType(VTP, 0); 3989 3990 // If the element type isn't canonical, this won't be a canonical type either, 3991 // so fill in the canonical type field. 3992 QualType Canonical; 3993 if (!vecType.isCanonical()) { 3994 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind); 3995 3996 // Get the new insert position for the node we care about. 3997 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3998 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3999 } 4000 auto *New = new (*this, TypeAlignment) 4001 VectorType(vecType, NumElts, Canonical, VecKind); 4002 VectorTypes.InsertNode(New, InsertPos); 4003 Types.push_back(New); 4004 return QualType(New, 0); 4005 } 4006 4007 QualType 4008 ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr, 4009 SourceLocation AttrLoc, 4010 VectorType::VectorKind VecKind) const { 4011 llvm::FoldingSetNodeID ID; 4012 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr, 4013 VecKind); 4014 void *InsertPos = nullptr; 4015 DependentVectorType *Canon = 4016 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4017 DependentVectorType *New; 4018 4019 if (Canon) { 4020 New = new (*this, TypeAlignment) DependentVectorType( 4021 *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind); 4022 } else { 4023 QualType CanonVecTy = getCanonicalType(VecType); 4024 if (CanonVecTy == VecType) { 4025 New = new (*this, TypeAlignment) DependentVectorType( 4026 *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind); 4027 4028 DependentVectorType *CanonCheck = 4029 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4030 assert(!CanonCheck && 4031 "Dependent-sized vector_size canonical type broken"); 4032 (void)CanonCheck; 4033 DependentVectorTypes.InsertNode(New, InsertPos); 4034 } else { 4035 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr, 4036 SourceLocation(), VecKind); 4037 New = new (*this, TypeAlignment) DependentVectorType( 4038 *this, VecType, CanonTy, SizeExpr, AttrLoc, VecKind); 4039 } 4040 } 4041 4042 Types.push_back(New); 4043 return QualType(New, 0); 4044 } 4045 4046 /// getExtVectorType - Return the unique reference to an extended vector type of 4047 /// the specified element type and size. VectorType must be a built-in type. 4048 QualType 4049 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const { 4050 assert(vecType->isBuiltinType() || vecType->isDependentType()); 4051 4052 // Check if we've already instantiated a vector of this type. 4053 llvm::FoldingSetNodeID ID; 4054 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, 4055 VectorType::GenericVector); 4056 void *InsertPos = nullptr; 4057 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 4058 return QualType(VTP, 0); 4059 4060 // If the element type isn't canonical, this won't be a canonical type either, 4061 // so fill in the canonical type field. 4062 QualType Canonical; 4063 if (!vecType.isCanonical()) { 4064 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts); 4065 4066 // Get the new insert position for the node we care about. 4067 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4068 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4069 } 4070 auto *New = new (*this, TypeAlignment) 4071 ExtVectorType(vecType, NumElts, Canonical); 4072 VectorTypes.InsertNode(New, InsertPos); 4073 Types.push_back(New); 4074 return QualType(New, 0); 4075 } 4076 4077 QualType 4078 ASTContext::getDependentSizedExtVectorType(QualType vecType, 4079 Expr *SizeExpr, 4080 SourceLocation AttrLoc) const { 4081 llvm::FoldingSetNodeID ID; 4082 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType), 4083 SizeExpr); 4084 4085 void *InsertPos = nullptr; 4086 DependentSizedExtVectorType *Canon 4087 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4088 DependentSizedExtVectorType *New; 4089 if (Canon) { 4090 // We already have a canonical version of this array type; use it as 4091 // the canonical type for a newly-built type. 4092 New = new (*this, TypeAlignment) 4093 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0), 4094 SizeExpr, AttrLoc); 4095 } else { 4096 QualType CanonVecTy = getCanonicalType(vecType); 4097 if (CanonVecTy == vecType) { 4098 New = new (*this, TypeAlignment) 4099 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr, 4100 AttrLoc); 4101 4102 DependentSizedExtVectorType *CanonCheck 4103 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4104 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken"); 4105 (void)CanonCheck; 4106 DependentSizedExtVectorTypes.InsertNode(New, InsertPos); 4107 } else { 4108 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr, 4109 SourceLocation()); 4110 New = new (*this, TypeAlignment) DependentSizedExtVectorType( 4111 *this, vecType, CanonExtTy, SizeExpr, AttrLoc); 4112 } 4113 } 4114 4115 Types.push_back(New); 4116 return QualType(New, 0); 4117 } 4118 4119 QualType ASTContext::getConstantMatrixType(QualType ElementTy, unsigned NumRows, 4120 unsigned NumColumns) const { 4121 llvm::FoldingSetNodeID ID; 4122 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns, 4123 Type::ConstantMatrix); 4124 4125 assert(MatrixType::isValidElementType(ElementTy) && 4126 "need a valid element type"); 4127 assert(ConstantMatrixType::isDimensionValid(NumRows) && 4128 ConstantMatrixType::isDimensionValid(NumColumns) && 4129 "need valid matrix dimensions"); 4130 void *InsertPos = nullptr; 4131 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos)) 4132 return QualType(MTP, 0); 4133 4134 QualType Canonical; 4135 if (!ElementTy.isCanonical()) { 4136 Canonical = 4137 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns); 4138 4139 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos); 4140 assert(!NewIP && "Matrix type shouldn't already exist in the map"); 4141 (void)NewIP; 4142 } 4143 4144 auto *New = new (*this, TypeAlignment) 4145 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical); 4146 MatrixTypes.InsertNode(New, InsertPos); 4147 Types.push_back(New); 4148 return QualType(New, 0); 4149 } 4150 4151 QualType ASTContext::getDependentSizedMatrixType(QualType ElementTy, 4152 Expr *RowExpr, 4153 Expr *ColumnExpr, 4154 SourceLocation AttrLoc) const { 4155 QualType CanonElementTy = getCanonicalType(ElementTy); 4156 llvm::FoldingSetNodeID ID; 4157 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr, 4158 ColumnExpr); 4159 4160 void *InsertPos = nullptr; 4161 DependentSizedMatrixType *Canon = 4162 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos); 4163 4164 if (!Canon) { 4165 Canon = new (*this, TypeAlignment) DependentSizedMatrixType( 4166 *this, CanonElementTy, QualType(), RowExpr, ColumnExpr, AttrLoc); 4167 #ifndef NDEBUG 4168 DependentSizedMatrixType *CanonCheck = 4169 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos); 4170 assert(!CanonCheck && "Dependent-sized matrix canonical type broken"); 4171 #endif 4172 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos); 4173 Types.push_back(Canon); 4174 } 4175 4176 // Already have a canonical version of the matrix type 4177 // 4178 // If it exactly matches the requested type, use it directly. 4179 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr && 4180 Canon->getRowExpr() == ColumnExpr) 4181 return QualType(Canon, 0); 4182 4183 // Use Canon as the canonical type for newly-built type. 4184 DependentSizedMatrixType *New = new (*this, TypeAlignment) 4185 DependentSizedMatrixType(*this, ElementTy, QualType(Canon, 0), RowExpr, 4186 ColumnExpr, AttrLoc); 4187 Types.push_back(New); 4188 return QualType(New, 0); 4189 } 4190 4191 QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType, 4192 Expr *AddrSpaceExpr, 4193 SourceLocation AttrLoc) const { 4194 assert(AddrSpaceExpr->isInstantiationDependent()); 4195 4196 QualType canonPointeeType = getCanonicalType(PointeeType); 4197 4198 void *insertPos = nullptr; 4199 llvm::FoldingSetNodeID ID; 4200 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType, 4201 AddrSpaceExpr); 4202 4203 DependentAddressSpaceType *canonTy = 4204 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos); 4205 4206 if (!canonTy) { 4207 canonTy = new (*this, TypeAlignment) 4208 DependentAddressSpaceType(*this, canonPointeeType, 4209 QualType(), AddrSpaceExpr, AttrLoc); 4210 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos); 4211 Types.push_back(canonTy); 4212 } 4213 4214 if (canonPointeeType == PointeeType && 4215 canonTy->getAddrSpaceExpr() == AddrSpaceExpr) 4216 return QualType(canonTy, 0); 4217 4218 auto *sugaredType 4219 = new (*this, TypeAlignment) 4220 DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0), 4221 AddrSpaceExpr, AttrLoc); 4222 Types.push_back(sugaredType); 4223 return QualType(sugaredType, 0); 4224 } 4225 4226 /// Determine whether \p T is canonical as the result type of a function. 4227 static bool isCanonicalResultType(QualType T) { 4228 return T.isCanonical() && 4229 (T.getObjCLifetime() == Qualifiers::OCL_None || 4230 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone); 4231 } 4232 4233 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'. 4234 QualType 4235 ASTContext::getFunctionNoProtoType(QualType ResultTy, 4236 const FunctionType::ExtInfo &Info) const { 4237 // Unique functions, to guarantee there is only one function of a particular 4238 // structure. 4239 llvm::FoldingSetNodeID ID; 4240 FunctionNoProtoType::Profile(ID, ResultTy, Info); 4241 4242 void *InsertPos = nullptr; 4243 if (FunctionNoProtoType *FT = 4244 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 4245 return QualType(FT, 0); 4246 4247 QualType Canonical; 4248 if (!isCanonicalResultType(ResultTy)) { 4249 Canonical = 4250 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info); 4251 4252 // Get the new insert position for the node we care about. 4253 FunctionNoProtoType *NewIP = 4254 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 4255 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4256 } 4257 4258 auto *New = new (*this, TypeAlignment) 4259 FunctionNoProtoType(ResultTy, Canonical, Info); 4260 Types.push_back(New); 4261 FunctionNoProtoTypes.InsertNode(New, InsertPos); 4262 return QualType(New, 0); 4263 } 4264 4265 CanQualType 4266 ASTContext::getCanonicalFunctionResultType(QualType ResultType) const { 4267 CanQualType CanResultType = getCanonicalType(ResultType); 4268 4269 // Canonical result types do not have ARC lifetime qualifiers. 4270 if (CanResultType.getQualifiers().hasObjCLifetime()) { 4271 Qualifiers Qs = CanResultType.getQualifiers(); 4272 Qs.removeObjCLifetime(); 4273 return CanQualType::CreateUnsafe( 4274 getQualifiedType(CanResultType.getUnqualifiedType(), Qs)); 4275 } 4276 4277 return CanResultType; 4278 } 4279 4280 static bool isCanonicalExceptionSpecification( 4281 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) { 4282 if (ESI.Type == EST_None) 4283 return true; 4284 if (!NoexceptInType) 4285 return false; 4286 4287 // C++17 onwards: exception specification is part of the type, as a simple 4288 // boolean "can this function type throw". 4289 if (ESI.Type == EST_BasicNoexcept) 4290 return true; 4291 4292 // A noexcept(expr) specification is (possibly) canonical if expr is 4293 // value-dependent. 4294 if (ESI.Type == EST_DependentNoexcept) 4295 return true; 4296 4297 // A dynamic exception specification is canonical if it only contains pack 4298 // expansions (so we can't tell whether it's non-throwing) and all its 4299 // contained types are canonical. 4300 if (ESI.Type == EST_Dynamic) { 4301 bool AnyPackExpansions = false; 4302 for (QualType ET : ESI.Exceptions) { 4303 if (!ET.isCanonical()) 4304 return false; 4305 if (ET->getAs<PackExpansionType>()) 4306 AnyPackExpansions = true; 4307 } 4308 return AnyPackExpansions; 4309 } 4310 4311 return false; 4312 } 4313 4314 QualType ASTContext::getFunctionTypeInternal( 4315 QualType ResultTy, ArrayRef<QualType> ArgArray, 4316 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const { 4317 size_t NumArgs = ArgArray.size(); 4318 4319 // Unique functions, to guarantee there is only one function of a particular 4320 // structure. 4321 llvm::FoldingSetNodeID ID; 4322 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI, 4323 *this, true); 4324 4325 QualType Canonical; 4326 bool Unique = false; 4327 4328 void *InsertPos = nullptr; 4329 if (FunctionProtoType *FPT = 4330 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) { 4331 QualType Existing = QualType(FPT, 0); 4332 4333 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse 4334 // it so long as our exception specification doesn't contain a dependent 4335 // noexcept expression, or we're just looking for a canonical type. 4336 // Otherwise, we're going to need to create a type 4337 // sugar node to hold the concrete expression. 4338 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) || 4339 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr()) 4340 return Existing; 4341 4342 // We need a new type sugar node for this one, to hold the new noexcept 4343 // expression. We do no canonicalization here, but that's OK since we don't 4344 // expect to see the same noexcept expression much more than once. 4345 Canonical = getCanonicalType(Existing); 4346 Unique = true; 4347 } 4348 4349 bool NoexceptInType = getLangOpts().CPlusPlus17; 4350 bool IsCanonicalExceptionSpec = 4351 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType); 4352 4353 // Determine whether the type being created is already canonical or not. 4354 bool isCanonical = !Unique && IsCanonicalExceptionSpec && 4355 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn; 4356 for (unsigned i = 0; i != NumArgs && isCanonical; ++i) 4357 if (!ArgArray[i].isCanonicalAsParam()) 4358 isCanonical = false; 4359 4360 if (OnlyWantCanonical) 4361 assert(isCanonical && 4362 "given non-canonical parameters constructing canonical type"); 4363 4364 // If this type isn't canonical, get the canonical version of it if we don't 4365 // already have it. The exception spec is only partially part of the 4366 // canonical type, and only in C++17 onwards. 4367 if (!isCanonical && Canonical.isNull()) { 4368 SmallVector<QualType, 16> CanonicalArgs; 4369 CanonicalArgs.reserve(NumArgs); 4370 for (unsigned i = 0; i != NumArgs; ++i) 4371 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i])); 4372 4373 llvm::SmallVector<QualType, 8> ExceptionTypeStorage; 4374 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI; 4375 CanonicalEPI.HasTrailingReturn = false; 4376 4377 if (IsCanonicalExceptionSpec) { 4378 // Exception spec is already OK. 4379 } else if (NoexceptInType) { 4380 switch (EPI.ExceptionSpec.Type) { 4381 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated: 4382 // We don't know yet. It shouldn't matter what we pick here; no-one 4383 // should ever look at this. 4384 LLVM_FALLTHROUGH; 4385 case EST_None: case EST_MSAny: case EST_NoexceptFalse: 4386 CanonicalEPI.ExceptionSpec.Type = EST_None; 4387 break; 4388 4389 // A dynamic exception specification is almost always "not noexcept", 4390 // with the exception that a pack expansion might expand to no types. 4391 case EST_Dynamic: { 4392 bool AnyPacks = false; 4393 for (QualType ET : EPI.ExceptionSpec.Exceptions) { 4394 if (ET->getAs<PackExpansionType>()) 4395 AnyPacks = true; 4396 ExceptionTypeStorage.push_back(getCanonicalType(ET)); 4397 } 4398 if (!AnyPacks) 4399 CanonicalEPI.ExceptionSpec.Type = EST_None; 4400 else { 4401 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic; 4402 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage; 4403 } 4404 break; 4405 } 4406 4407 case EST_DynamicNone: 4408 case EST_BasicNoexcept: 4409 case EST_NoexceptTrue: 4410 case EST_NoThrow: 4411 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept; 4412 break; 4413 4414 case EST_DependentNoexcept: 4415 llvm_unreachable("dependent noexcept is already canonical"); 4416 } 4417 } else { 4418 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo(); 4419 } 4420 4421 // Adjust the canonical function result type. 4422 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy); 4423 Canonical = 4424 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true); 4425 4426 // Get the new insert position for the node we care about. 4427 FunctionProtoType *NewIP = 4428 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 4429 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4430 } 4431 4432 // Compute the needed size to hold this FunctionProtoType and the 4433 // various trailing objects. 4434 auto ESH = FunctionProtoType::getExceptionSpecSize( 4435 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size()); 4436 size_t Size = FunctionProtoType::totalSizeToAlloc< 4437 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields, 4438 FunctionType::ExceptionType, Expr *, FunctionDecl *, 4439 FunctionProtoType::ExtParameterInfo, Qualifiers>( 4440 NumArgs, EPI.Variadic, 4441 FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type), 4442 ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr, 4443 EPI.ExtParameterInfos ? NumArgs : 0, 4444 EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0); 4445 4446 auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment); 4447 FunctionProtoType::ExtProtoInfo newEPI = EPI; 4448 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI); 4449 Types.push_back(FTP); 4450 if (!Unique) 4451 FunctionProtoTypes.InsertNode(FTP, InsertPos); 4452 return QualType(FTP, 0); 4453 } 4454 4455 QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const { 4456 llvm::FoldingSetNodeID ID; 4457 PipeType::Profile(ID, T, ReadOnly); 4458 4459 void *InsertPos = nullptr; 4460 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos)) 4461 return QualType(PT, 0); 4462 4463 // If the pipe element type isn't canonical, this won't be a canonical type 4464 // either, so fill in the canonical type field. 4465 QualType Canonical; 4466 if (!T.isCanonical()) { 4467 Canonical = getPipeType(getCanonicalType(T), ReadOnly); 4468 4469 // Get the new insert position for the node we care about. 4470 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos); 4471 assert(!NewIP && "Shouldn't be in the map!"); 4472 (void)NewIP; 4473 } 4474 auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly); 4475 Types.push_back(New); 4476 PipeTypes.InsertNode(New, InsertPos); 4477 return QualType(New, 0); 4478 } 4479 4480 QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const { 4481 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 4482 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant) 4483 : Ty; 4484 } 4485 4486 QualType ASTContext::getReadPipeType(QualType T) const { 4487 return getPipeType(T, true); 4488 } 4489 4490 QualType ASTContext::getWritePipeType(QualType T) const { 4491 return getPipeType(T, false); 4492 } 4493 4494 QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const { 4495 llvm::FoldingSetNodeID ID; 4496 BitIntType::Profile(ID, IsUnsigned, NumBits); 4497 4498 void *InsertPos = nullptr; 4499 if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos)) 4500 return QualType(EIT, 0); 4501 4502 auto *New = new (*this, TypeAlignment) BitIntType(IsUnsigned, NumBits); 4503 BitIntTypes.InsertNode(New, InsertPos); 4504 Types.push_back(New); 4505 return QualType(New, 0); 4506 } 4507 4508 QualType ASTContext::getDependentBitIntType(bool IsUnsigned, 4509 Expr *NumBitsExpr) const { 4510 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent"); 4511 llvm::FoldingSetNodeID ID; 4512 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr); 4513 4514 void *InsertPos = nullptr; 4515 if (DependentBitIntType *Existing = 4516 DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos)) 4517 return QualType(Existing, 0); 4518 4519 auto *New = new (*this, TypeAlignment) 4520 DependentBitIntType(*this, IsUnsigned, NumBitsExpr); 4521 DependentBitIntTypes.InsertNode(New, InsertPos); 4522 4523 Types.push_back(New); 4524 return QualType(New, 0); 4525 } 4526 4527 #ifndef NDEBUG 4528 static bool NeedsInjectedClassNameType(const RecordDecl *D) { 4529 if (!isa<CXXRecordDecl>(D)) return false; 4530 const auto *RD = cast<CXXRecordDecl>(D); 4531 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) 4532 return true; 4533 if (RD->getDescribedClassTemplate() && 4534 !isa<ClassTemplateSpecializationDecl>(RD)) 4535 return true; 4536 return false; 4537 } 4538 #endif 4539 4540 /// getInjectedClassNameType - Return the unique reference to the 4541 /// injected class name type for the specified templated declaration. 4542 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl, 4543 QualType TST) const { 4544 assert(NeedsInjectedClassNameType(Decl)); 4545 if (Decl->TypeForDecl) { 4546 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 4547 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) { 4548 assert(PrevDecl->TypeForDecl && "previous declaration has no type"); 4549 Decl->TypeForDecl = PrevDecl->TypeForDecl; 4550 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 4551 } else { 4552 Type *newType = 4553 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST); 4554 Decl->TypeForDecl = newType; 4555 Types.push_back(newType); 4556 } 4557 return QualType(Decl->TypeForDecl, 0); 4558 } 4559 4560 /// getTypeDeclType - Return the unique reference to the type for the 4561 /// specified type declaration. 4562 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const { 4563 assert(Decl && "Passed null for Decl param"); 4564 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case"); 4565 4566 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl)) 4567 return getTypedefType(Typedef); 4568 4569 assert(!isa<TemplateTypeParmDecl>(Decl) && 4570 "Template type parameter types are always available."); 4571 4572 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) { 4573 assert(Record->isFirstDecl() && "struct/union has previous declaration"); 4574 assert(!NeedsInjectedClassNameType(Record)); 4575 return getRecordType(Record); 4576 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) { 4577 assert(Enum->isFirstDecl() && "enum has previous declaration"); 4578 return getEnumType(Enum); 4579 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) { 4580 return getUnresolvedUsingType(Using); 4581 } else 4582 llvm_unreachable("TypeDecl without a type?"); 4583 4584 return QualType(Decl->TypeForDecl, 0); 4585 } 4586 4587 /// getTypedefType - Return the unique reference to the type for the 4588 /// specified typedef name decl. 4589 QualType ASTContext::getTypedefType(const TypedefNameDecl *Decl, 4590 QualType Underlying) const { 4591 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 4592 4593 if (Underlying.isNull()) 4594 Underlying = Decl->getUnderlyingType(); 4595 QualType Canonical = getCanonicalType(Underlying); 4596 auto *newType = new (*this, TypeAlignment) 4597 TypedefType(Type::Typedef, Decl, Underlying, Canonical); 4598 Decl->TypeForDecl = newType; 4599 Types.push_back(newType); 4600 return QualType(newType, 0); 4601 } 4602 4603 QualType ASTContext::getUsingType(const UsingShadowDecl *Found, 4604 QualType Underlying) const { 4605 llvm::FoldingSetNodeID ID; 4606 UsingType::Profile(ID, Found); 4607 4608 void *InsertPos = nullptr; 4609 UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos); 4610 if (T) 4611 return QualType(T, 0); 4612 4613 assert(!Underlying.hasLocalQualifiers()); 4614 assert(Underlying == getTypeDeclType(cast<TypeDecl>(Found->getTargetDecl()))); 4615 QualType Canon = Underlying.getCanonicalType(); 4616 4617 UsingType *NewType = 4618 new (*this, TypeAlignment) UsingType(Found, Underlying, Canon); 4619 Types.push_back(NewType); 4620 UsingTypes.InsertNode(NewType, InsertPos); 4621 return QualType(NewType, 0); 4622 } 4623 4624 QualType ASTContext::getRecordType(const RecordDecl *Decl) const { 4625 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 4626 4627 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl()) 4628 if (PrevDecl->TypeForDecl) 4629 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 4630 4631 auto *newType = new (*this, TypeAlignment) RecordType(Decl); 4632 Decl->TypeForDecl = newType; 4633 Types.push_back(newType); 4634 return QualType(newType, 0); 4635 } 4636 4637 QualType ASTContext::getEnumType(const EnumDecl *Decl) const { 4638 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 4639 4640 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl()) 4641 if (PrevDecl->TypeForDecl) 4642 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 4643 4644 auto *newType = new (*this, TypeAlignment) EnumType(Decl); 4645 Decl->TypeForDecl = newType; 4646 Types.push_back(newType); 4647 return QualType(newType, 0); 4648 } 4649 4650 QualType ASTContext::getUnresolvedUsingType( 4651 const UnresolvedUsingTypenameDecl *Decl) const { 4652 if (Decl->TypeForDecl) 4653 return QualType(Decl->TypeForDecl, 0); 4654 4655 if (const UnresolvedUsingTypenameDecl *CanonicalDecl = 4656 Decl->getCanonicalDecl()) 4657 if (CanonicalDecl->TypeForDecl) 4658 return QualType(Decl->TypeForDecl = CanonicalDecl->TypeForDecl, 0); 4659 4660 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Decl); 4661 Decl->TypeForDecl = newType; 4662 Types.push_back(newType); 4663 return QualType(newType, 0); 4664 } 4665 4666 QualType ASTContext::getAttributedType(attr::Kind attrKind, 4667 QualType modifiedType, 4668 QualType equivalentType) { 4669 llvm::FoldingSetNodeID id; 4670 AttributedType::Profile(id, attrKind, modifiedType, equivalentType); 4671 4672 void *insertPos = nullptr; 4673 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos); 4674 if (type) return QualType(type, 0); 4675 4676 QualType canon = getCanonicalType(equivalentType); 4677 type = new (*this, TypeAlignment) 4678 AttributedType(canon, attrKind, modifiedType, equivalentType); 4679 4680 Types.push_back(type); 4681 AttributedTypes.InsertNode(type, insertPos); 4682 4683 return QualType(type, 0); 4684 } 4685 4686 /// Retrieve a substitution-result type. 4687 QualType 4688 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm, 4689 QualType Replacement) const { 4690 assert(Replacement.isCanonical() 4691 && "replacement types must always be canonical"); 4692 4693 llvm::FoldingSetNodeID ID; 4694 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement); 4695 void *InsertPos = nullptr; 4696 SubstTemplateTypeParmType *SubstParm 4697 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 4698 4699 if (!SubstParm) { 4700 SubstParm = new (*this, TypeAlignment) 4701 SubstTemplateTypeParmType(Parm, Replacement); 4702 Types.push_back(SubstParm); 4703 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos); 4704 } 4705 4706 return QualType(SubstParm, 0); 4707 } 4708 4709 /// Retrieve a 4710 QualType ASTContext::getSubstTemplateTypeParmPackType( 4711 const TemplateTypeParmType *Parm, 4712 const TemplateArgument &ArgPack) { 4713 #ifndef NDEBUG 4714 for (const auto &P : ArgPack.pack_elements()) { 4715 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type"); 4716 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type"); 4717 } 4718 #endif 4719 4720 llvm::FoldingSetNodeID ID; 4721 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack); 4722 void *InsertPos = nullptr; 4723 if (SubstTemplateTypeParmPackType *SubstParm 4724 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos)) 4725 return QualType(SubstParm, 0); 4726 4727 QualType Canon; 4728 if (!Parm->isCanonicalUnqualified()) { 4729 Canon = getCanonicalType(QualType(Parm, 0)); 4730 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon), 4731 ArgPack); 4732 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos); 4733 } 4734 4735 auto *SubstParm 4736 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon, 4737 ArgPack); 4738 Types.push_back(SubstParm); 4739 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos); 4740 return QualType(SubstParm, 0); 4741 } 4742 4743 /// Retrieve the template type parameter type for a template 4744 /// parameter or parameter pack with the given depth, index, and (optionally) 4745 /// name. 4746 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index, 4747 bool ParameterPack, 4748 TemplateTypeParmDecl *TTPDecl) const { 4749 llvm::FoldingSetNodeID ID; 4750 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl); 4751 void *InsertPos = nullptr; 4752 TemplateTypeParmType *TypeParm 4753 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 4754 4755 if (TypeParm) 4756 return QualType(TypeParm, 0); 4757 4758 if (TTPDecl) { 4759 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack); 4760 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon); 4761 4762 TemplateTypeParmType *TypeCheck 4763 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 4764 assert(!TypeCheck && "Template type parameter canonical type broken"); 4765 (void)TypeCheck; 4766 } else 4767 TypeParm = new (*this, TypeAlignment) 4768 TemplateTypeParmType(Depth, Index, ParameterPack); 4769 4770 Types.push_back(TypeParm); 4771 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos); 4772 4773 return QualType(TypeParm, 0); 4774 } 4775 4776 TypeSourceInfo * 4777 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name, 4778 SourceLocation NameLoc, 4779 const TemplateArgumentListInfo &Args, 4780 QualType Underlying) const { 4781 assert(!Name.getAsDependentTemplateName() && 4782 "No dependent template names here!"); 4783 QualType TST = getTemplateSpecializationType(Name, Args, Underlying); 4784 4785 TypeSourceInfo *DI = CreateTypeSourceInfo(TST); 4786 TemplateSpecializationTypeLoc TL = 4787 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>(); 4788 TL.setTemplateKeywordLoc(SourceLocation()); 4789 TL.setTemplateNameLoc(NameLoc); 4790 TL.setLAngleLoc(Args.getLAngleLoc()); 4791 TL.setRAngleLoc(Args.getRAngleLoc()); 4792 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 4793 TL.setArgLocInfo(i, Args[i].getLocInfo()); 4794 return DI; 4795 } 4796 4797 QualType 4798 ASTContext::getTemplateSpecializationType(TemplateName Template, 4799 const TemplateArgumentListInfo &Args, 4800 QualType Underlying) const { 4801 assert(!Template.getAsDependentTemplateName() && 4802 "No dependent template names here!"); 4803 4804 SmallVector<TemplateArgument, 4> ArgVec; 4805 ArgVec.reserve(Args.size()); 4806 for (const TemplateArgumentLoc &Arg : Args.arguments()) 4807 ArgVec.push_back(Arg.getArgument()); 4808 4809 return getTemplateSpecializationType(Template, ArgVec, Underlying); 4810 } 4811 4812 #ifndef NDEBUG 4813 static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) { 4814 for (const TemplateArgument &Arg : Args) 4815 if (Arg.isPackExpansion()) 4816 return true; 4817 4818 return true; 4819 } 4820 #endif 4821 4822 QualType 4823 ASTContext::getTemplateSpecializationType(TemplateName Template, 4824 ArrayRef<TemplateArgument> Args, 4825 QualType Underlying) const { 4826 assert(!Template.getAsDependentTemplateName() && 4827 "No dependent template names here!"); 4828 // Look through qualified template names. 4829 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 4830 Template = TemplateName(QTN->getTemplateDecl()); 4831 4832 bool IsTypeAlias = 4833 Template.getAsTemplateDecl() && 4834 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl()); 4835 QualType CanonType; 4836 if (!Underlying.isNull()) 4837 CanonType = getCanonicalType(Underlying); 4838 else { 4839 // We can get here with an alias template when the specialization contains 4840 // a pack expansion that does not match up with a parameter pack. 4841 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) && 4842 "Caller must compute aliased type"); 4843 IsTypeAlias = false; 4844 CanonType = getCanonicalTemplateSpecializationType(Template, Args); 4845 } 4846 4847 // Allocate the (non-canonical) template specialization type, but don't 4848 // try to unique it: these types typically have location information that 4849 // we don't unique and don't want to lose. 4850 void *Mem = Allocate(sizeof(TemplateSpecializationType) + 4851 sizeof(TemplateArgument) * Args.size() + 4852 (IsTypeAlias? sizeof(QualType) : 0), 4853 TypeAlignment); 4854 auto *Spec 4855 = new (Mem) TemplateSpecializationType(Template, Args, CanonType, 4856 IsTypeAlias ? Underlying : QualType()); 4857 4858 Types.push_back(Spec); 4859 return QualType(Spec, 0); 4860 } 4861 4862 static bool 4863 getCanonicalTemplateArguments(const ASTContext &C, 4864 ArrayRef<TemplateArgument> OrigArgs, 4865 SmallVectorImpl<TemplateArgument> &CanonArgs) { 4866 bool AnyNonCanonArgs = false; 4867 unsigned NumArgs = OrigArgs.size(); 4868 CanonArgs.resize(NumArgs); 4869 for (unsigned I = 0; I != NumArgs; ++I) { 4870 const TemplateArgument &OrigArg = OrigArgs[I]; 4871 TemplateArgument &CanonArg = CanonArgs[I]; 4872 CanonArg = C.getCanonicalTemplateArgument(OrigArg); 4873 if (!CanonArg.structurallyEquals(OrigArg)) 4874 AnyNonCanonArgs = true; 4875 } 4876 return AnyNonCanonArgs; 4877 } 4878 4879 QualType ASTContext::getCanonicalTemplateSpecializationType( 4880 TemplateName Template, ArrayRef<TemplateArgument> Args) const { 4881 assert(!Template.getAsDependentTemplateName() && 4882 "No dependent template names here!"); 4883 4884 // Look through qualified template names. 4885 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 4886 Template = TemplateName(QTN->getTemplateDecl()); 4887 4888 // Build the canonical template specialization type. 4889 TemplateName CanonTemplate = getCanonicalTemplateName(Template); 4890 SmallVector<TemplateArgument, 4> CanonArgs; 4891 ::getCanonicalTemplateArguments(*this, Args, CanonArgs); 4892 4893 // Determine whether this canonical template specialization type already 4894 // exists. 4895 llvm::FoldingSetNodeID ID; 4896 TemplateSpecializationType::Profile(ID, CanonTemplate, 4897 CanonArgs, *this); 4898 4899 void *InsertPos = nullptr; 4900 TemplateSpecializationType *Spec 4901 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 4902 4903 if (!Spec) { 4904 // Allocate a new canonical template specialization type. 4905 void *Mem = Allocate((sizeof(TemplateSpecializationType) + 4906 sizeof(TemplateArgument) * CanonArgs.size()), 4907 TypeAlignment); 4908 Spec = new (Mem) TemplateSpecializationType(CanonTemplate, 4909 CanonArgs, 4910 QualType(), QualType()); 4911 Types.push_back(Spec); 4912 TemplateSpecializationTypes.InsertNode(Spec, InsertPos); 4913 } 4914 4915 assert(Spec->isDependentType() && 4916 "Non-dependent template-id type must have a canonical type"); 4917 return QualType(Spec, 0); 4918 } 4919 4920 QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword, 4921 NestedNameSpecifier *NNS, 4922 QualType NamedType, 4923 TagDecl *OwnedTagDecl) const { 4924 llvm::FoldingSetNodeID ID; 4925 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl); 4926 4927 void *InsertPos = nullptr; 4928 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 4929 if (T) 4930 return QualType(T, 0); 4931 4932 QualType Canon = NamedType; 4933 if (!Canon.isCanonical()) { 4934 Canon = getCanonicalType(NamedType); 4935 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 4936 assert(!CheckT && "Elaborated canonical type broken"); 4937 (void)CheckT; 4938 } 4939 4940 void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl), 4941 TypeAlignment); 4942 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl); 4943 4944 Types.push_back(T); 4945 ElaboratedTypes.InsertNode(T, InsertPos); 4946 return QualType(T, 0); 4947 } 4948 4949 QualType 4950 ASTContext::getParenType(QualType InnerType) const { 4951 llvm::FoldingSetNodeID ID; 4952 ParenType::Profile(ID, InnerType); 4953 4954 void *InsertPos = nullptr; 4955 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 4956 if (T) 4957 return QualType(T, 0); 4958 4959 QualType Canon = InnerType; 4960 if (!Canon.isCanonical()) { 4961 Canon = getCanonicalType(InnerType); 4962 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 4963 assert(!CheckT && "Paren canonical type broken"); 4964 (void)CheckT; 4965 } 4966 4967 T = new (*this, TypeAlignment) ParenType(InnerType, Canon); 4968 Types.push_back(T); 4969 ParenTypes.InsertNode(T, InsertPos); 4970 return QualType(T, 0); 4971 } 4972 4973 QualType 4974 ASTContext::getMacroQualifiedType(QualType UnderlyingTy, 4975 const IdentifierInfo *MacroII) const { 4976 QualType Canon = UnderlyingTy; 4977 if (!Canon.isCanonical()) 4978 Canon = getCanonicalType(UnderlyingTy); 4979 4980 auto *newType = new (*this, TypeAlignment) 4981 MacroQualifiedType(UnderlyingTy, Canon, MacroII); 4982 Types.push_back(newType); 4983 return QualType(newType, 0); 4984 } 4985 4986 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword, 4987 NestedNameSpecifier *NNS, 4988 const IdentifierInfo *Name, 4989 QualType Canon) const { 4990 if (Canon.isNull()) { 4991 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 4992 if (CanonNNS != NNS) 4993 Canon = getDependentNameType(Keyword, CanonNNS, Name); 4994 } 4995 4996 llvm::FoldingSetNodeID ID; 4997 DependentNameType::Profile(ID, Keyword, NNS, Name); 4998 4999 void *InsertPos = nullptr; 5000 DependentNameType *T 5001 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos); 5002 if (T) 5003 return QualType(T, 0); 5004 5005 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon); 5006 Types.push_back(T); 5007 DependentNameTypes.InsertNode(T, InsertPos); 5008 return QualType(T, 0); 5009 } 5010 5011 QualType 5012 ASTContext::getDependentTemplateSpecializationType( 5013 ElaboratedTypeKeyword Keyword, 5014 NestedNameSpecifier *NNS, 5015 const IdentifierInfo *Name, 5016 const TemplateArgumentListInfo &Args) const { 5017 // TODO: avoid this copy 5018 SmallVector<TemplateArgument, 16> ArgCopy; 5019 for (unsigned I = 0, E = Args.size(); I != E; ++I) 5020 ArgCopy.push_back(Args[I].getArgument()); 5021 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy); 5022 } 5023 5024 QualType 5025 ASTContext::getDependentTemplateSpecializationType( 5026 ElaboratedTypeKeyword Keyword, 5027 NestedNameSpecifier *NNS, 5028 const IdentifierInfo *Name, 5029 ArrayRef<TemplateArgument> Args) const { 5030 assert((!NNS || NNS->isDependent()) && 5031 "nested-name-specifier must be dependent"); 5032 5033 llvm::FoldingSetNodeID ID; 5034 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS, 5035 Name, Args); 5036 5037 void *InsertPos = nullptr; 5038 DependentTemplateSpecializationType *T 5039 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 5040 if (T) 5041 return QualType(T, 0); 5042 5043 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 5044 5045 ElaboratedTypeKeyword CanonKeyword = Keyword; 5046 if (Keyword == ETK_None) CanonKeyword = ETK_Typename; 5047 5048 SmallVector<TemplateArgument, 16> CanonArgs; 5049 bool AnyNonCanonArgs = 5050 ::getCanonicalTemplateArguments(*this, Args, CanonArgs); 5051 5052 QualType Canon; 5053 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) { 5054 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS, 5055 Name, 5056 CanonArgs); 5057 5058 // Find the insert position again. 5059 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 5060 } 5061 5062 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) + 5063 sizeof(TemplateArgument) * Args.size()), 5064 TypeAlignment); 5065 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS, 5066 Name, Args, Canon); 5067 Types.push_back(T); 5068 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos); 5069 return QualType(T, 0); 5070 } 5071 5072 TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) { 5073 TemplateArgument Arg; 5074 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) { 5075 QualType ArgType = getTypeDeclType(TTP); 5076 if (TTP->isParameterPack()) 5077 ArgType = getPackExpansionType(ArgType, None); 5078 5079 Arg = TemplateArgument(ArgType); 5080 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 5081 QualType T = 5082 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this); 5083 // For class NTTPs, ensure we include the 'const' so the type matches that 5084 // of a real template argument. 5085 // FIXME: It would be more faithful to model this as something like an 5086 // lvalue-to-rvalue conversion applied to a const-qualified lvalue. 5087 if (T->isRecordType()) 5088 T.addConst(); 5089 Expr *E = new (*this) DeclRefExpr( 5090 *this, NTTP, /*enclosing*/ false, T, 5091 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation()); 5092 5093 if (NTTP->isParameterPack()) 5094 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(), 5095 None); 5096 Arg = TemplateArgument(E); 5097 } else { 5098 auto *TTP = cast<TemplateTemplateParmDecl>(Param); 5099 if (TTP->isParameterPack()) 5100 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>()); 5101 else 5102 Arg = TemplateArgument(TemplateName(TTP)); 5103 } 5104 5105 if (Param->isTemplateParameterPack()) 5106 Arg = TemplateArgument::CreatePackCopy(*this, Arg); 5107 5108 return Arg; 5109 } 5110 5111 void 5112 ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params, 5113 SmallVectorImpl<TemplateArgument> &Args) { 5114 Args.reserve(Args.size() + Params->size()); 5115 5116 for (NamedDecl *Param : *Params) 5117 Args.push_back(getInjectedTemplateArg(Param)); 5118 } 5119 5120 QualType ASTContext::getPackExpansionType(QualType Pattern, 5121 Optional<unsigned> NumExpansions, 5122 bool ExpectPackInType) { 5123 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) && 5124 "Pack expansions must expand one or more parameter packs"); 5125 5126 llvm::FoldingSetNodeID ID; 5127 PackExpansionType::Profile(ID, Pattern, NumExpansions); 5128 5129 void *InsertPos = nullptr; 5130 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 5131 if (T) 5132 return QualType(T, 0); 5133 5134 QualType Canon; 5135 if (!Pattern.isCanonical()) { 5136 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions, 5137 /*ExpectPackInType=*/false); 5138 5139 // Find the insert position again, in case we inserted an element into 5140 // PackExpansionTypes and invalidated our insert position. 5141 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 5142 } 5143 5144 T = new (*this, TypeAlignment) 5145 PackExpansionType(Pattern, Canon, NumExpansions); 5146 Types.push_back(T); 5147 PackExpansionTypes.InsertNode(T, InsertPos); 5148 return QualType(T, 0); 5149 } 5150 5151 /// CmpProtocolNames - Comparison predicate for sorting protocols 5152 /// alphabetically. 5153 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS, 5154 ObjCProtocolDecl *const *RHS) { 5155 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName()); 5156 } 5157 5158 static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) { 5159 if (Protocols.empty()) return true; 5160 5161 if (Protocols[0]->getCanonicalDecl() != Protocols[0]) 5162 return false; 5163 5164 for (unsigned i = 1; i != Protocols.size(); ++i) 5165 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 || 5166 Protocols[i]->getCanonicalDecl() != Protocols[i]) 5167 return false; 5168 return true; 5169 } 5170 5171 static void 5172 SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) { 5173 // Sort protocols, keyed by name. 5174 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames); 5175 5176 // Canonicalize. 5177 for (ObjCProtocolDecl *&P : Protocols) 5178 P = P->getCanonicalDecl(); 5179 5180 // Remove duplicates. 5181 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end()); 5182 Protocols.erase(ProtocolsEnd, Protocols.end()); 5183 } 5184 5185 QualType ASTContext::getObjCObjectType(QualType BaseType, 5186 ObjCProtocolDecl * const *Protocols, 5187 unsigned NumProtocols) const { 5188 return getObjCObjectType(BaseType, {}, 5189 llvm::makeArrayRef(Protocols, NumProtocols), 5190 /*isKindOf=*/false); 5191 } 5192 5193 QualType ASTContext::getObjCObjectType( 5194 QualType baseType, 5195 ArrayRef<QualType> typeArgs, 5196 ArrayRef<ObjCProtocolDecl *> protocols, 5197 bool isKindOf) const { 5198 // If the base type is an interface and there aren't any protocols or 5199 // type arguments to add, then the interface type will do just fine. 5200 if (typeArgs.empty() && protocols.empty() && !isKindOf && 5201 isa<ObjCInterfaceType>(baseType)) 5202 return baseType; 5203 5204 // Look in the folding set for an existing type. 5205 llvm::FoldingSetNodeID ID; 5206 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf); 5207 void *InsertPos = nullptr; 5208 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos)) 5209 return QualType(QT, 0); 5210 5211 // Determine the type arguments to be used for canonicalization, 5212 // which may be explicitly specified here or written on the base 5213 // type. 5214 ArrayRef<QualType> effectiveTypeArgs = typeArgs; 5215 if (effectiveTypeArgs.empty()) { 5216 if (const auto *baseObject = baseType->getAs<ObjCObjectType>()) 5217 effectiveTypeArgs = baseObject->getTypeArgs(); 5218 } 5219 5220 // Build the canonical type, which has the canonical base type and a 5221 // sorted-and-uniqued list of protocols and the type arguments 5222 // canonicalized. 5223 QualType canonical; 5224 bool typeArgsAreCanonical = llvm::all_of( 5225 effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); }); 5226 bool protocolsSorted = areSortedAndUniqued(protocols); 5227 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) { 5228 // Determine the canonical type arguments. 5229 ArrayRef<QualType> canonTypeArgs; 5230 SmallVector<QualType, 4> canonTypeArgsVec; 5231 if (!typeArgsAreCanonical) { 5232 canonTypeArgsVec.reserve(effectiveTypeArgs.size()); 5233 for (auto typeArg : effectiveTypeArgs) 5234 canonTypeArgsVec.push_back(getCanonicalType(typeArg)); 5235 canonTypeArgs = canonTypeArgsVec; 5236 } else { 5237 canonTypeArgs = effectiveTypeArgs; 5238 } 5239 5240 ArrayRef<ObjCProtocolDecl *> canonProtocols; 5241 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec; 5242 if (!protocolsSorted) { 5243 canonProtocolsVec.append(protocols.begin(), protocols.end()); 5244 SortAndUniqueProtocols(canonProtocolsVec); 5245 canonProtocols = canonProtocolsVec; 5246 } else { 5247 canonProtocols = protocols; 5248 } 5249 5250 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs, 5251 canonProtocols, isKindOf); 5252 5253 // Regenerate InsertPos. 5254 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos); 5255 } 5256 5257 unsigned size = sizeof(ObjCObjectTypeImpl); 5258 size += typeArgs.size() * sizeof(QualType); 5259 size += protocols.size() * sizeof(ObjCProtocolDecl *); 5260 void *mem = Allocate(size, TypeAlignment); 5261 auto *T = 5262 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols, 5263 isKindOf); 5264 5265 Types.push_back(T); 5266 ObjCObjectTypes.InsertNode(T, InsertPos); 5267 return QualType(T, 0); 5268 } 5269 5270 /// Apply Objective-C protocol qualifiers to the given type. 5271 /// If this is for the canonical type of a type parameter, we can apply 5272 /// protocol qualifiers on the ObjCObjectPointerType. 5273 QualType 5274 ASTContext::applyObjCProtocolQualifiers(QualType type, 5275 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError, 5276 bool allowOnPointerType) const { 5277 hasError = false; 5278 5279 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) { 5280 return getObjCTypeParamType(objT->getDecl(), protocols); 5281 } 5282 5283 // Apply protocol qualifiers to ObjCObjectPointerType. 5284 if (allowOnPointerType) { 5285 if (const auto *objPtr = 5286 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) { 5287 const ObjCObjectType *objT = objPtr->getObjectType(); 5288 // Merge protocol lists and construct ObjCObjectType. 5289 SmallVector<ObjCProtocolDecl*, 8> protocolsVec; 5290 protocolsVec.append(objT->qual_begin(), 5291 objT->qual_end()); 5292 protocolsVec.append(protocols.begin(), protocols.end()); 5293 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec; 5294 type = getObjCObjectType( 5295 objT->getBaseType(), 5296 objT->getTypeArgsAsWritten(), 5297 protocols, 5298 objT->isKindOfTypeAsWritten()); 5299 return getObjCObjectPointerType(type); 5300 } 5301 } 5302 5303 // Apply protocol qualifiers to ObjCObjectType. 5304 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){ 5305 // FIXME: Check for protocols to which the class type is already 5306 // known to conform. 5307 5308 return getObjCObjectType(objT->getBaseType(), 5309 objT->getTypeArgsAsWritten(), 5310 protocols, 5311 objT->isKindOfTypeAsWritten()); 5312 } 5313 5314 // If the canonical type is ObjCObjectType, ... 5315 if (type->isObjCObjectType()) { 5316 // Silently overwrite any existing protocol qualifiers. 5317 // TODO: determine whether that's the right thing to do. 5318 5319 // FIXME: Check for protocols to which the class type is already 5320 // known to conform. 5321 return getObjCObjectType(type, {}, protocols, false); 5322 } 5323 5324 // id<protocol-list> 5325 if (type->isObjCIdType()) { 5326 const auto *objPtr = type->castAs<ObjCObjectPointerType>(); 5327 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols, 5328 objPtr->isKindOfType()); 5329 return getObjCObjectPointerType(type); 5330 } 5331 5332 // Class<protocol-list> 5333 if (type->isObjCClassType()) { 5334 const auto *objPtr = type->castAs<ObjCObjectPointerType>(); 5335 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols, 5336 objPtr->isKindOfType()); 5337 return getObjCObjectPointerType(type); 5338 } 5339 5340 hasError = true; 5341 return type; 5342 } 5343 5344 QualType 5345 ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl, 5346 ArrayRef<ObjCProtocolDecl *> protocols) const { 5347 // Look in the folding set for an existing type. 5348 llvm::FoldingSetNodeID ID; 5349 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols); 5350 void *InsertPos = nullptr; 5351 if (ObjCTypeParamType *TypeParam = 5352 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos)) 5353 return QualType(TypeParam, 0); 5354 5355 // We canonicalize to the underlying type. 5356 QualType Canonical = getCanonicalType(Decl->getUnderlyingType()); 5357 if (!protocols.empty()) { 5358 // Apply the protocol qualifers. 5359 bool hasError; 5360 Canonical = getCanonicalType(applyObjCProtocolQualifiers( 5361 Canonical, protocols, hasError, true /*allowOnPointerType*/)); 5362 assert(!hasError && "Error when apply protocol qualifier to bound type"); 5363 } 5364 5365 unsigned size = sizeof(ObjCTypeParamType); 5366 size += protocols.size() * sizeof(ObjCProtocolDecl *); 5367 void *mem = Allocate(size, TypeAlignment); 5368 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols); 5369 5370 Types.push_back(newType); 5371 ObjCTypeParamTypes.InsertNode(newType, InsertPos); 5372 return QualType(newType, 0); 5373 } 5374 5375 void ASTContext::adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig, 5376 ObjCTypeParamDecl *New) const { 5377 New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType())); 5378 // Update TypeForDecl after updating TypeSourceInfo. 5379 auto NewTypeParamTy = cast<ObjCTypeParamType>(New->getTypeForDecl()); 5380 SmallVector<ObjCProtocolDecl *, 8> protocols; 5381 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end()); 5382 QualType UpdatedTy = getObjCTypeParamType(New, protocols); 5383 New->setTypeForDecl(UpdatedTy.getTypePtr()); 5384 } 5385 5386 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's 5387 /// protocol list adopt all protocols in QT's qualified-id protocol 5388 /// list. 5389 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT, 5390 ObjCInterfaceDecl *IC) { 5391 if (!QT->isObjCQualifiedIdType()) 5392 return false; 5393 5394 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) { 5395 // If both the right and left sides have qualifiers. 5396 for (auto *Proto : OPT->quals()) { 5397 if (!IC->ClassImplementsProtocol(Proto, false)) 5398 return false; 5399 } 5400 return true; 5401 } 5402 return false; 5403 } 5404 5405 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in 5406 /// QT's qualified-id protocol list adopt all protocols in IDecl's list 5407 /// of protocols. 5408 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT, 5409 ObjCInterfaceDecl *IDecl) { 5410 if (!QT->isObjCQualifiedIdType()) 5411 return false; 5412 const auto *OPT = QT->getAs<ObjCObjectPointerType>(); 5413 if (!OPT) 5414 return false; 5415 if (!IDecl->hasDefinition()) 5416 return false; 5417 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols; 5418 CollectInheritedProtocols(IDecl, InheritedProtocols); 5419 if (InheritedProtocols.empty()) 5420 return false; 5421 // Check that if every protocol in list of id<plist> conforms to a protocol 5422 // of IDecl's, then bridge casting is ok. 5423 bool Conforms = false; 5424 for (auto *Proto : OPT->quals()) { 5425 Conforms = false; 5426 for (auto *PI : InheritedProtocols) { 5427 if (ProtocolCompatibleWithProtocol(Proto, PI)) { 5428 Conforms = true; 5429 break; 5430 } 5431 } 5432 if (!Conforms) 5433 break; 5434 } 5435 if (Conforms) 5436 return true; 5437 5438 for (auto *PI : InheritedProtocols) { 5439 // If both the right and left sides have qualifiers. 5440 bool Adopts = false; 5441 for (auto *Proto : OPT->quals()) { 5442 // return 'true' if 'PI' is in the inheritance hierarchy of Proto 5443 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto))) 5444 break; 5445 } 5446 if (!Adopts) 5447 return false; 5448 } 5449 return true; 5450 } 5451 5452 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for 5453 /// the given object type. 5454 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const { 5455 llvm::FoldingSetNodeID ID; 5456 ObjCObjectPointerType::Profile(ID, ObjectT); 5457 5458 void *InsertPos = nullptr; 5459 if (ObjCObjectPointerType *QT = 5460 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 5461 return QualType(QT, 0); 5462 5463 // Find the canonical object type. 5464 QualType Canonical; 5465 if (!ObjectT.isCanonical()) { 5466 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT)); 5467 5468 // Regenerate InsertPos. 5469 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 5470 } 5471 5472 // No match. 5473 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment); 5474 auto *QType = 5475 new (Mem) ObjCObjectPointerType(Canonical, ObjectT); 5476 5477 Types.push_back(QType); 5478 ObjCObjectPointerTypes.InsertNode(QType, InsertPos); 5479 return QualType(QType, 0); 5480 } 5481 5482 /// getObjCInterfaceType - Return the unique reference to the type for the 5483 /// specified ObjC interface decl. The list of protocols is optional. 5484 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl, 5485 ObjCInterfaceDecl *PrevDecl) const { 5486 if (Decl->TypeForDecl) 5487 return QualType(Decl->TypeForDecl, 0); 5488 5489 if (PrevDecl) { 5490 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl"); 5491 Decl->TypeForDecl = PrevDecl->TypeForDecl; 5492 return QualType(PrevDecl->TypeForDecl, 0); 5493 } 5494 5495 // Prefer the definition, if there is one. 5496 if (const ObjCInterfaceDecl *Def = Decl->getDefinition()) 5497 Decl = Def; 5498 5499 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment); 5500 auto *T = new (Mem) ObjCInterfaceType(Decl); 5501 Decl->TypeForDecl = T; 5502 Types.push_back(T); 5503 return QualType(T, 0); 5504 } 5505 5506 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique 5507 /// TypeOfExprType AST's (since expression's are never shared). For example, 5508 /// multiple declarations that refer to "typeof(x)" all contain different 5509 /// DeclRefExpr's. This doesn't effect the type checker, since it operates 5510 /// on canonical type's (which are always unique). 5511 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const { 5512 TypeOfExprType *toe; 5513 if (tofExpr->isTypeDependent()) { 5514 llvm::FoldingSetNodeID ID; 5515 DependentTypeOfExprType::Profile(ID, *this, tofExpr); 5516 5517 void *InsertPos = nullptr; 5518 DependentTypeOfExprType *Canon 5519 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos); 5520 if (Canon) { 5521 // We already have a "canonical" version of an identical, dependent 5522 // typeof(expr) type. Use that as our canonical type. 5523 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, 5524 QualType((TypeOfExprType*)Canon, 0)); 5525 } else { 5526 // Build a new, canonical typeof(expr) type. 5527 Canon 5528 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr); 5529 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos); 5530 toe = Canon; 5531 } 5532 } else { 5533 QualType Canonical = getCanonicalType(tofExpr->getType()); 5534 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical); 5535 } 5536 Types.push_back(toe); 5537 return QualType(toe, 0); 5538 } 5539 5540 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique 5541 /// TypeOfType nodes. The only motivation to unique these nodes would be 5542 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be 5543 /// an issue. This doesn't affect the type checker, since it operates 5544 /// on canonical types (which are always unique). 5545 QualType ASTContext::getTypeOfType(QualType tofType) const { 5546 QualType Canonical = getCanonicalType(tofType); 5547 auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical); 5548 Types.push_back(tot); 5549 return QualType(tot, 0); 5550 } 5551 5552 /// getReferenceQualifiedType - Given an expr, will return the type for 5553 /// that expression, as in [dcl.type.simple]p4 but without taking id-expressions 5554 /// and class member access into account. 5555 QualType ASTContext::getReferenceQualifiedType(const Expr *E) const { 5556 // C++11 [dcl.type.simple]p4: 5557 // [...] 5558 QualType T = E->getType(); 5559 switch (E->getValueKind()) { 5560 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the 5561 // type of e; 5562 case VK_XValue: 5563 return getRValueReferenceType(T); 5564 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the 5565 // type of e; 5566 case VK_LValue: 5567 return getLValueReferenceType(T); 5568 // - otherwise, decltype(e) is the type of e. 5569 case VK_PRValue: 5570 return T; 5571 } 5572 llvm_unreachable("Unknown value kind"); 5573 } 5574 5575 /// Unlike many "get<Type>" functions, we don't unique DecltypeType 5576 /// nodes. This would never be helpful, since each such type has its own 5577 /// expression, and would not give a significant memory saving, since there 5578 /// is an Expr tree under each such type. 5579 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const { 5580 DecltypeType *dt; 5581 5582 // C++11 [temp.type]p2: 5583 // If an expression e involves a template parameter, decltype(e) denotes a 5584 // unique dependent type. Two such decltype-specifiers refer to the same 5585 // type only if their expressions are equivalent (14.5.6.1). 5586 if (e->isInstantiationDependent()) { 5587 llvm::FoldingSetNodeID ID; 5588 DependentDecltypeType::Profile(ID, *this, e); 5589 5590 void *InsertPos = nullptr; 5591 DependentDecltypeType *Canon 5592 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos); 5593 if (!Canon) { 5594 // Build a new, canonical decltype(expr) type. 5595 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e); 5596 DependentDecltypeTypes.InsertNode(Canon, InsertPos); 5597 } 5598 dt = new (*this, TypeAlignment) 5599 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0)); 5600 } else { 5601 dt = new (*this, TypeAlignment) 5602 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType)); 5603 } 5604 Types.push_back(dt); 5605 return QualType(dt, 0); 5606 } 5607 5608 /// getUnaryTransformationType - We don't unique these, since the memory 5609 /// savings are minimal and these are rare. 5610 QualType ASTContext::getUnaryTransformType(QualType BaseType, 5611 QualType UnderlyingType, 5612 UnaryTransformType::UTTKind Kind) 5613 const { 5614 UnaryTransformType *ut = nullptr; 5615 5616 if (BaseType->isDependentType()) { 5617 // Look in the folding set for an existing type. 5618 llvm::FoldingSetNodeID ID; 5619 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind); 5620 5621 void *InsertPos = nullptr; 5622 DependentUnaryTransformType *Canon 5623 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos); 5624 5625 if (!Canon) { 5626 // Build a new, canonical __underlying_type(type) type. 5627 Canon = new (*this, TypeAlignment) 5628 DependentUnaryTransformType(*this, getCanonicalType(BaseType), 5629 Kind); 5630 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos); 5631 } 5632 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType, 5633 QualType(), Kind, 5634 QualType(Canon, 0)); 5635 } else { 5636 QualType CanonType = getCanonicalType(UnderlyingType); 5637 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType, 5638 UnderlyingType, Kind, 5639 CanonType); 5640 } 5641 Types.push_back(ut); 5642 return QualType(ut, 0); 5643 } 5644 5645 QualType ASTContext::getAutoTypeInternal( 5646 QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent, 5647 bool IsPack, ConceptDecl *TypeConstraintConcept, 5648 ArrayRef<TemplateArgument> TypeConstraintArgs, bool IsCanon) const { 5649 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && 5650 !TypeConstraintConcept && !IsDependent) 5651 return getAutoDeductType(); 5652 5653 // Look in the folding set for an existing type. 5654 void *InsertPos = nullptr; 5655 llvm::FoldingSetNodeID ID; 5656 AutoType::Profile(ID, *this, DeducedType, Keyword, IsDependent, 5657 TypeConstraintConcept, TypeConstraintArgs); 5658 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos)) 5659 return QualType(AT, 0); 5660 5661 QualType Canon; 5662 if (!IsCanon) { 5663 if (DeducedType.isNull()) { 5664 SmallVector<TemplateArgument, 4> CanonArgs; 5665 bool AnyNonCanonArgs = 5666 ::getCanonicalTemplateArguments(*this, TypeConstraintArgs, CanonArgs); 5667 if (AnyNonCanonArgs) { 5668 Canon = getAutoTypeInternal(QualType(), Keyword, IsDependent, IsPack, 5669 TypeConstraintConcept, CanonArgs, true); 5670 // Find the insert position again. 5671 AutoTypes.FindNodeOrInsertPos(ID, InsertPos); 5672 } 5673 } else { 5674 Canon = DeducedType.getCanonicalType(); 5675 } 5676 } 5677 5678 void *Mem = Allocate(sizeof(AutoType) + 5679 sizeof(TemplateArgument) * TypeConstraintArgs.size(), 5680 TypeAlignment); 5681 auto *AT = new (Mem) AutoType( 5682 DeducedType, Keyword, 5683 (IsDependent ? TypeDependence::DependentInstantiation 5684 : TypeDependence::None) | 5685 (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None), 5686 Canon, TypeConstraintConcept, TypeConstraintArgs); 5687 Types.push_back(AT); 5688 AutoTypes.InsertNode(AT, InsertPos); 5689 return QualType(AT, 0); 5690 } 5691 5692 /// getAutoType - Return the uniqued reference to the 'auto' type which has been 5693 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the 5694 /// canonical deduced-but-dependent 'auto' type. 5695 QualType 5696 ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, 5697 bool IsDependent, bool IsPack, 5698 ConceptDecl *TypeConstraintConcept, 5699 ArrayRef<TemplateArgument> TypeConstraintArgs) const { 5700 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack"); 5701 assert((!IsDependent || DeducedType.isNull()) && 5702 "A dependent auto should be undeduced"); 5703 return getAutoTypeInternal(DeducedType, Keyword, IsDependent, IsPack, 5704 TypeConstraintConcept, TypeConstraintArgs); 5705 } 5706 5707 /// Return the uniqued reference to the deduced template specialization type 5708 /// which has been deduced to the given type, or to the canonical undeduced 5709 /// such type, or the canonical deduced-but-dependent such type. 5710 QualType ASTContext::getDeducedTemplateSpecializationType( 5711 TemplateName Template, QualType DeducedType, bool IsDependent) const { 5712 // Look in the folding set for an existing type. 5713 void *InsertPos = nullptr; 5714 llvm::FoldingSetNodeID ID; 5715 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType, 5716 IsDependent); 5717 if (DeducedTemplateSpecializationType *DTST = 5718 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos)) 5719 return QualType(DTST, 0); 5720 5721 auto *DTST = new (*this, TypeAlignment) 5722 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent); 5723 llvm::FoldingSetNodeID TempID; 5724 DTST->Profile(TempID); 5725 assert(ID == TempID && "ID does not match"); 5726 Types.push_back(DTST); 5727 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos); 5728 return QualType(DTST, 0); 5729 } 5730 5731 /// getAtomicType - Return the uniqued reference to the atomic type for 5732 /// the given value type. 5733 QualType ASTContext::getAtomicType(QualType T) const { 5734 // Unique pointers, to guarantee there is only one pointer of a particular 5735 // structure. 5736 llvm::FoldingSetNodeID ID; 5737 AtomicType::Profile(ID, T); 5738 5739 void *InsertPos = nullptr; 5740 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos)) 5741 return QualType(AT, 0); 5742 5743 // If the atomic value type isn't canonical, this won't be a canonical type 5744 // either, so fill in the canonical type field. 5745 QualType Canonical; 5746 if (!T.isCanonical()) { 5747 Canonical = getAtomicType(getCanonicalType(T)); 5748 5749 // Get the new insert position for the node we care about. 5750 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos); 5751 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 5752 } 5753 auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical); 5754 Types.push_back(New); 5755 AtomicTypes.InsertNode(New, InsertPos); 5756 return QualType(New, 0); 5757 } 5758 5759 /// getAutoDeductType - Get type pattern for deducing against 'auto'. 5760 QualType ASTContext::getAutoDeductType() const { 5761 if (AutoDeductTy.isNull()) 5762 AutoDeductTy = QualType(new (*this, TypeAlignment) 5763 AutoType(QualType(), AutoTypeKeyword::Auto, 5764 TypeDependence::None, QualType(), 5765 /*concept*/ nullptr, /*args*/ {}), 5766 0); 5767 return AutoDeductTy; 5768 } 5769 5770 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'. 5771 QualType ASTContext::getAutoRRefDeductType() const { 5772 if (AutoRRefDeductTy.isNull()) 5773 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType()); 5774 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern"); 5775 return AutoRRefDeductTy; 5776 } 5777 5778 /// getTagDeclType - Return the unique reference to the type for the 5779 /// specified TagDecl (struct/union/class/enum) decl. 5780 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const { 5781 assert(Decl); 5782 // FIXME: What is the design on getTagDeclType when it requires casting 5783 // away const? mutable? 5784 return getTypeDeclType(const_cast<TagDecl*>(Decl)); 5785 } 5786 5787 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result 5788 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and 5789 /// needs to agree with the definition in <stddef.h>. 5790 CanQualType ASTContext::getSizeType() const { 5791 return getFromTargetType(Target->getSizeType()); 5792 } 5793 5794 /// Return the unique signed counterpart of the integer type 5795 /// corresponding to size_t. 5796 CanQualType ASTContext::getSignedSizeType() const { 5797 return getFromTargetType(Target->getSignedSizeType()); 5798 } 5799 5800 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5). 5801 CanQualType ASTContext::getIntMaxType() const { 5802 return getFromTargetType(Target->getIntMaxType()); 5803 } 5804 5805 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5). 5806 CanQualType ASTContext::getUIntMaxType() const { 5807 return getFromTargetType(Target->getUIntMaxType()); 5808 } 5809 5810 /// getSignedWCharType - Return the type of "signed wchar_t". 5811 /// Used when in C++, as a GCC extension. 5812 QualType ASTContext::getSignedWCharType() const { 5813 // FIXME: derive from "Target" ? 5814 return WCharTy; 5815 } 5816 5817 /// getUnsignedWCharType - Return the type of "unsigned wchar_t". 5818 /// Used when in C++, as a GCC extension. 5819 QualType ASTContext::getUnsignedWCharType() const { 5820 // FIXME: derive from "Target" ? 5821 return UnsignedIntTy; 5822 } 5823 5824 QualType ASTContext::getIntPtrType() const { 5825 return getFromTargetType(Target->getIntPtrType()); 5826 } 5827 5828 QualType ASTContext::getUIntPtrType() const { 5829 return getCorrespondingUnsignedType(getIntPtrType()); 5830 } 5831 5832 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17) 5833 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9). 5834 QualType ASTContext::getPointerDiffType() const { 5835 return getFromTargetType(Target->getPtrDiffType(0)); 5836 } 5837 5838 /// Return the unique unsigned counterpart of "ptrdiff_t" 5839 /// integer type. The standard (C11 7.21.6.1p7) refers to this type 5840 /// in the definition of %tu format specifier. 5841 QualType ASTContext::getUnsignedPointerDiffType() const { 5842 return getFromTargetType(Target->getUnsignedPtrDiffType(0)); 5843 } 5844 5845 /// Return the unique type for "pid_t" defined in 5846 /// <sys/types.h>. We need this to compute the correct type for vfork(). 5847 QualType ASTContext::getProcessIDType() const { 5848 return getFromTargetType(Target->getProcessIDType()); 5849 } 5850 5851 //===----------------------------------------------------------------------===// 5852 // Type Operators 5853 //===----------------------------------------------------------------------===// 5854 5855 CanQualType ASTContext::getCanonicalParamType(QualType T) const { 5856 // Push qualifiers into arrays, and then discard any remaining 5857 // qualifiers. 5858 T = getCanonicalType(T); 5859 T = getVariableArrayDecayedType(T); 5860 const Type *Ty = T.getTypePtr(); 5861 QualType Result; 5862 if (isa<ArrayType>(Ty)) { 5863 Result = getArrayDecayedType(QualType(Ty,0)); 5864 } else if (isa<FunctionType>(Ty)) { 5865 Result = getPointerType(QualType(Ty, 0)); 5866 } else { 5867 Result = QualType(Ty, 0); 5868 } 5869 5870 return CanQualType::CreateUnsafe(Result); 5871 } 5872 5873 QualType ASTContext::getUnqualifiedArrayType(QualType type, 5874 Qualifiers &quals) { 5875 SplitQualType splitType = type.getSplitUnqualifiedType(); 5876 5877 // FIXME: getSplitUnqualifiedType() actually walks all the way to 5878 // the unqualified desugared type and then drops it on the floor. 5879 // We then have to strip that sugar back off with 5880 // getUnqualifiedDesugaredType(), which is silly. 5881 const auto *AT = 5882 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType()); 5883 5884 // If we don't have an array, just use the results in splitType. 5885 if (!AT) { 5886 quals = splitType.Quals; 5887 return QualType(splitType.Ty, 0); 5888 } 5889 5890 // Otherwise, recurse on the array's element type. 5891 QualType elementType = AT->getElementType(); 5892 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals); 5893 5894 // If that didn't change the element type, AT has no qualifiers, so we 5895 // can just use the results in splitType. 5896 if (elementType == unqualElementType) { 5897 assert(quals.empty()); // from the recursive call 5898 quals = splitType.Quals; 5899 return QualType(splitType.Ty, 0); 5900 } 5901 5902 // Otherwise, add in the qualifiers from the outermost type, then 5903 // build the type back up. 5904 quals.addConsistentQualifiers(splitType.Quals); 5905 5906 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 5907 return getConstantArrayType(unqualElementType, CAT->getSize(), 5908 CAT->getSizeExpr(), CAT->getSizeModifier(), 0); 5909 } 5910 5911 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) { 5912 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0); 5913 } 5914 5915 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) { 5916 return getVariableArrayType(unqualElementType, 5917 VAT->getSizeExpr(), 5918 VAT->getSizeModifier(), 5919 VAT->getIndexTypeCVRQualifiers(), 5920 VAT->getBracketsRange()); 5921 } 5922 5923 const auto *DSAT = cast<DependentSizedArrayType>(AT); 5924 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(), 5925 DSAT->getSizeModifier(), 0, 5926 SourceRange()); 5927 } 5928 5929 /// Attempt to unwrap two types that may both be array types with the same bound 5930 /// (or both be array types of unknown bound) for the purpose of comparing the 5931 /// cv-decomposition of two types per C++ [conv.qual]. 5932 /// 5933 /// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in 5934 /// C++20 [conv.qual], if permitted by the current language mode. 5935 void ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2, 5936 bool AllowPiMismatch) { 5937 while (true) { 5938 auto *AT1 = getAsArrayType(T1); 5939 if (!AT1) 5940 return; 5941 5942 auto *AT2 = getAsArrayType(T2); 5943 if (!AT2) 5944 return; 5945 5946 // If we don't have two array types with the same constant bound nor two 5947 // incomplete array types, we've unwrapped everything we can. 5948 // C++20 also permits one type to be a constant array type and the other 5949 // to be an incomplete array type. 5950 // FIXME: Consider also unwrapping array of unknown bound and VLA. 5951 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) { 5952 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2); 5953 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) || 5954 (AllowPiMismatch && getLangOpts().CPlusPlus20 && 5955 isa<IncompleteArrayType>(AT2)))) 5956 return; 5957 } else if (isa<IncompleteArrayType>(AT1)) { 5958 if (!(isa<IncompleteArrayType>(AT2) || 5959 (AllowPiMismatch && getLangOpts().CPlusPlus20 && 5960 isa<ConstantArrayType>(AT2)))) 5961 return; 5962 } else { 5963 return; 5964 } 5965 5966 T1 = AT1->getElementType(); 5967 T2 = AT2->getElementType(); 5968 } 5969 } 5970 5971 /// Attempt to unwrap two types that may be similar (C++ [conv.qual]). 5972 /// 5973 /// If T1 and T2 are both pointer types of the same kind, or both array types 5974 /// with the same bound, unwraps layers from T1 and T2 until a pointer type is 5975 /// unwrapped. Top-level qualifiers on T1 and T2 are ignored. 5976 /// 5977 /// This function will typically be called in a loop that successively 5978 /// "unwraps" pointer and pointer-to-member types to compare them at each 5979 /// level. 5980 /// 5981 /// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in 5982 /// C++20 [conv.qual], if permitted by the current language mode. 5983 /// 5984 /// \return \c true if a pointer type was unwrapped, \c false if we reached a 5985 /// pair of types that can't be unwrapped further. 5986 bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2, 5987 bool AllowPiMismatch) { 5988 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch); 5989 5990 const auto *T1PtrType = T1->getAs<PointerType>(); 5991 const auto *T2PtrType = T2->getAs<PointerType>(); 5992 if (T1PtrType && T2PtrType) { 5993 T1 = T1PtrType->getPointeeType(); 5994 T2 = T2PtrType->getPointeeType(); 5995 return true; 5996 } 5997 5998 const auto *T1MPType = T1->getAs<MemberPointerType>(); 5999 const auto *T2MPType = T2->getAs<MemberPointerType>(); 6000 if (T1MPType && T2MPType && 6001 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0), 6002 QualType(T2MPType->getClass(), 0))) { 6003 T1 = T1MPType->getPointeeType(); 6004 T2 = T2MPType->getPointeeType(); 6005 return true; 6006 } 6007 6008 if (getLangOpts().ObjC) { 6009 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>(); 6010 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>(); 6011 if (T1OPType && T2OPType) { 6012 T1 = T1OPType->getPointeeType(); 6013 T2 = T2OPType->getPointeeType(); 6014 return true; 6015 } 6016 } 6017 6018 // FIXME: Block pointers, too? 6019 6020 return false; 6021 } 6022 6023 bool ASTContext::hasSimilarType(QualType T1, QualType T2) { 6024 while (true) { 6025 Qualifiers Quals; 6026 T1 = getUnqualifiedArrayType(T1, Quals); 6027 T2 = getUnqualifiedArrayType(T2, Quals); 6028 if (hasSameType(T1, T2)) 6029 return true; 6030 if (!UnwrapSimilarTypes(T1, T2)) 6031 return false; 6032 } 6033 } 6034 6035 bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) { 6036 while (true) { 6037 Qualifiers Quals1, Quals2; 6038 T1 = getUnqualifiedArrayType(T1, Quals1); 6039 T2 = getUnqualifiedArrayType(T2, Quals2); 6040 6041 Quals1.removeCVRQualifiers(); 6042 Quals2.removeCVRQualifiers(); 6043 if (Quals1 != Quals2) 6044 return false; 6045 6046 if (hasSameType(T1, T2)) 6047 return true; 6048 6049 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false)) 6050 return false; 6051 } 6052 } 6053 6054 DeclarationNameInfo 6055 ASTContext::getNameForTemplate(TemplateName Name, 6056 SourceLocation NameLoc) const { 6057 switch (Name.getKind()) { 6058 case TemplateName::QualifiedTemplate: 6059 case TemplateName::Template: 6060 // DNInfo work in progress: CHECKME: what about DNLoc? 6061 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(), 6062 NameLoc); 6063 6064 case TemplateName::OverloadedTemplate: { 6065 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate(); 6066 // DNInfo work in progress: CHECKME: what about DNLoc? 6067 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc); 6068 } 6069 6070 case TemplateName::AssumedTemplate: { 6071 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName(); 6072 return DeclarationNameInfo(Storage->getDeclName(), NameLoc); 6073 } 6074 6075 case TemplateName::DependentTemplate: { 6076 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 6077 DeclarationName DName; 6078 if (DTN->isIdentifier()) { 6079 DName = DeclarationNames.getIdentifier(DTN->getIdentifier()); 6080 return DeclarationNameInfo(DName, NameLoc); 6081 } else { 6082 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator()); 6083 // DNInfo work in progress: FIXME: source locations? 6084 DeclarationNameLoc DNLoc = 6085 DeclarationNameLoc::makeCXXOperatorNameLoc(SourceRange()); 6086 return DeclarationNameInfo(DName, NameLoc, DNLoc); 6087 } 6088 } 6089 6090 case TemplateName::SubstTemplateTemplateParm: { 6091 SubstTemplateTemplateParmStorage *subst 6092 = Name.getAsSubstTemplateTemplateParm(); 6093 return DeclarationNameInfo(subst->getParameter()->getDeclName(), 6094 NameLoc); 6095 } 6096 6097 case TemplateName::SubstTemplateTemplateParmPack: { 6098 SubstTemplateTemplateParmPackStorage *subst 6099 = Name.getAsSubstTemplateTemplateParmPack(); 6100 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(), 6101 NameLoc); 6102 } 6103 } 6104 6105 llvm_unreachable("bad template name kind!"); 6106 } 6107 6108 TemplateName 6109 ASTContext::getCanonicalTemplateName(const TemplateName &Name) const { 6110 switch (Name.getKind()) { 6111 case TemplateName::QualifiedTemplate: 6112 case TemplateName::Template: { 6113 TemplateDecl *Template = Name.getAsTemplateDecl(); 6114 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template)) 6115 Template = getCanonicalTemplateTemplateParmDecl(TTP); 6116 6117 // The canonical template name is the canonical template declaration. 6118 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl())); 6119 } 6120 6121 case TemplateName::OverloadedTemplate: 6122 case TemplateName::AssumedTemplate: 6123 llvm_unreachable("cannot canonicalize unresolved template"); 6124 6125 case TemplateName::DependentTemplate: { 6126 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 6127 assert(DTN && "Non-dependent template names must refer to template decls."); 6128 return DTN->CanonicalTemplateName; 6129 } 6130 6131 case TemplateName::SubstTemplateTemplateParm: { 6132 SubstTemplateTemplateParmStorage *subst 6133 = Name.getAsSubstTemplateTemplateParm(); 6134 return getCanonicalTemplateName(subst->getReplacement()); 6135 } 6136 6137 case TemplateName::SubstTemplateTemplateParmPack: { 6138 SubstTemplateTemplateParmPackStorage *subst 6139 = Name.getAsSubstTemplateTemplateParmPack(); 6140 TemplateTemplateParmDecl *canonParameter 6141 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack()); 6142 TemplateArgument canonArgPack 6143 = getCanonicalTemplateArgument(subst->getArgumentPack()); 6144 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack); 6145 } 6146 } 6147 6148 llvm_unreachable("bad template name!"); 6149 } 6150 6151 bool ASTContext::hasSameTemplateName(const TemplateName &X, 6152 const TemplateName &Y) const { 6153 return getCanonicalTemplateName(X).getAsVoidPointer() == 6154 getCanonicalTemplateName(Y).getAsVoidPointer(); 6155 } 6156 6157 bool ASTContext::isSameTemplateParameter(const NamedDecl *X, 6158 const NamedDecl *Y) { 6159 if (X->getKind() != Y->getKind()) 6160 return false; 6161 6162 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) { 6163 auto *TY = cast<TemplateTypeParmDecl>(Y); 6164 if (TX->isParameterPack() != TY->isParameterPack()) 6165 return false; 6166 if (TX->hasTypeConstraint() != TY->hasTypeConstraint()) 6167 return false; 6168 const TypeConstraint *TXTC = TX->getTypeConstraint(); 6169 const TypeConstraint *TYTC = TY->getTypeConstraint(); 6170 if (!TXTC != !TYTC) 6171 return false; 6172 if (TXTC && TYTC) { 6173 auto *NCX = TXTC->getNamedConcept(); 6174 auto *NCY = TYTC->getNamedConcept(); 6175 if (!NCX || !NCY || !isSameEntity(NCX, NCY)) 6176 return false; 6177 if (TXTC->hasExplicitTemplateArgs() != TYTC->hasExplicitTemplateArgs()) 6178 return false; 6179 if (TXTC->hasExplicitTemplateArgs()) { 6180 auto *TXTCArgs = TXTC->getTemplateArgsAsWritten(); 6181 auto *TYTCArgs = TYTC->getTemplateArgsAsWritten(); 6182 if (TXTCArgs->NumTemplateArgs != TYTCArgs->NumTemplateArgs) 6183 return false; 6184 llvm::FoldingSetNodeID XID, YID; 6185 for (auto &ArgLoc : TXTCArgs->arguments()) 6186 ArgLoc.getArgument().Profile(XID, X->getASTContext()); 6187 for (auto &ArgLoc : TYTCArgs->arguments()) 6188 ArgLoc.getArgument().Profile(YID, Y->getASTContext()); 6189 if (XID != YID) 6190 return false; 6191 } 6192 } 6193 return true; 6194 } 6195 6196 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) { 6197 auto *TY = cast<NonTypeTemplateParmDecl>(Y); 6198 return TX->isParameterPack() == TY->isParameterPack() && 6199 TX->getASTContext().hasSameType(TX->getType(), TY->getType()); 6200 } 6201 6202 auto *TX = cast<TemplateTemplateParmDecl>(X); 6203 auto *TY = cast<TemplateTemplateParmDecl>(Y); 6204 return TX->isParameterPack() == TY->isParameterPack() && 6205 isSameTemplateParameterList(TX->getTemplateParameters(), 6206 TY->getTemplateParameters()); 6207 } 6208 6209 bool ASTContext::isSameTemplateParameterList(const TemplateParameterList *X, 6210 const TemplateParameterList *Y) { 6211 if (X->size() != Y->size()) 6212 return false; 6213 6214 for (unsigned I = 0, N = X->size(); I != N; ++I) 6215 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I))) 6216 return false; 6217 6218 const Expr *XRC = X->getRequiresClause(); 6219 const Expr *YRC = Y->getRequiresClause(); 6220 if (!XRC != !YRC) 6221 return false; 6222 if (XRC) { 6223 llvm::FoldingSetNodeID XRCID, YRCID; 6224 XRC->Profile(XRCID, *this, /*Canonical=*/true); 6225 YRC->Profile(YRCID, *this, /*Canonical=*/true); 6226 if (XRCID != YRCID) 6227 return false; 6228 } 6229 6230 return true; 6231 } 6232 6233 static NamespaceDecl *getNamespace(const NestedNameSpecifier *X) { 6234 if (auto *NS = X->getAsNamespace()) 6235 return NS; 6236 if (auto *NAS = X->getAsNamespaceAlias()) 6237 return NAS->getNamespace(); 6238 return nullptr; 6239 } 6240 6241 static bool isSameQualifier(const NestedNameSpecifier *X, 6242 const NestedNameSpecifier *Y) { 6243 if (auto *NSX = getNamespace(X)) { 6244 auto *NSY = getNamespace(Y); 6245 if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl()) 6246 return false; 6247 } else if (X->getKind() != Y->getKind()) 6248 return false; 6249 6250 // FIXME: For namespaces and types, we're permitted to check that the entity 6251 // is named via the same tokens. We should probably do so. 6252 switch (X->getKind()) { 6253 case NestedNameSpecifier::Identifier: 6254 if (X->getAsIdentifier() != Y->getAsIdentifier()) 6255 return false; 6256 break; 6257 case NestedNameSpecifier::Namespace: 6258 case NestedNameSpecifier::NamespaceAlias: 6259 // We've already checked that we named the same namespace. 6260 break; 6261 case NestedNameSpecifier::TypeSpec: 6262 case NestedNameSpecifier::TypeSpecWithTemplate: 6263 if (X->getAsType()->getCanonicalTypeInternal() != 6264 Y->getAsType()->getCanonicalTypeInternal()) 6265 return false; 6266 break; 6267 case NestedNameSpecifier::Global: 6268 case NestedNameSpecifier::Super: 6269 return true; 6270 } 6271 6272 // Recurse into earlier portion of NNS, if any. 6273 auto *PX = X->getPrefix(); 6274 auto *PY = Y->getPrefix(); 6275 if (PX && PY) 6276 return isSameQualifier(PX, PY); 6277 return !PX && !PY; 6278 } 6279 6280 /// Determine whether the attributes we can overload on are identical for A and 6281 /// B. Will ignore any overloadable attrs represented in the type of A and B. 6282 static bool hasSameOverloadableAttrs(const FunctionDecl *A, 6283 const FunctionDecl *B) { 6284 // Note that pass_object_size attributes are represented in the function's 6285 // ExtParameterInfo, so we don't need to check them here. 6286 6287 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 6288 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>(); 6289 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>(); 6290 6291 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) { 6292 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); 6293 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); 6294 6295 // Return false if the number of enable_if attributes is different. 6296 if (!Cand1A || !Cand2A) 6297 return false; 6298 6299 Cand1ID.clear(); 6300 Cand2ID.clear(); 6301 6302 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true); 6303 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true); 6304 6305 // Return false if any of the enable_if expressions of A and B are 6306 // different. 6307 if (Cand1ID != Cand2ID) 6308 return false; 6309 } 6310 return true; 6311 } 6312 6313 bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) { 6314 if (X == Y) 6315 return true; 6316 6317 if (X->getDeclName() != Y->getDeclName()) 6318 return false; 6319 6320 // Must be in the same context. 6321 // 6322 // Note that we can't use DeclContext::Equals here, because the DeclContexts 6323 // could be two different declarations of the same function. (We will fix the 6324 // semantic DC to refer to the primary definition after merging.) 6325 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()), 6326 cast<Decl>(Y->getDeclContext()->getRedeclContext()))) 6327 return false; 6328 6329 // Two typedefs refer to the same entity if they have the same underlying 6330 // type. 6331 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X)) 6332 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y)) 6333 return hasSameType(TypedefX->getUnderlyingType(), 6334 TypedefY->getUnderlyingType()); 6335 6336 // Must have the same kind. 6337 if (X->getKind() != Y->getKind()) 6338 return false; 6339 6340 // Objective-C classes and protocols with the same name always match. 6341 if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X)) 6342 return true; 6343 6344 if (isa<ClassTemplateSpecializationDecl>(X)) { 6345 // No need to handle these here: we merge them when adding them to the 6346 // template. 6347 return false; 6348 } 6349 6350 // Compatible tags match. 6351 if (const auto *TagX = dyn_cast<TagDecl>(X)) { 6352 const auto *TagY = cast<TagDecl>(Y); 6353 return (TagX->getTagKind() == TagY->getTagKind()) || 6354 ((TagX->getTagKind() == TTK_Struct || 6355 TagX->getTagKind() == TTK_Class || 6356 TagX->getTagKind() == TTK_Interface) && 6357 (TagY->getTagKind() == TTK_Struct || 6358 TagY->getTagKind() == TTK_Class || 6359 TagY->getTagKind() == TTK_Interface)); 6360 } 6361 6362 // Functions with the same type and linkage match. 6363 // FIXME: This needs to cope with merging of prototyped/non-prototyped 6364 // functions, etc. 6365 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) { 6366 const auto *FuncY = cast<FunctionDecl>(Y); 6367 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) { 6368 const auto *CtorY = cast<CXXConstructorDecl>(Y); 6369 if (CtorX->getInheritedConstructor() && 6370 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(), 6371 CtorY->getInheritedConstructor().getConstructor())) 6372 return false; 6373 } 6374 6375 if (FuncX->isMultiVersion() != FuncY->isMultiVersion()) 6376 return false; 6377 6378 // Multiversioned functions with different feature strings are represented 6379 // as separate declarations. 6380 if (FuncX->isMultiVersion()) { 6381 const auto *TAX = FuncX->getAttr<TargetAttr>(); 6382 const auto *TAY = FuncY->getAttr<TargetAttr>(); 6383 assert(TAX && TAY && "Multiversion Function without target attribute"); 6384 6385 if (TAX->getFeaturesStr() != TAY->getFeaturesStr()) 6386 return false; 6387 } 6388 6389 const Expr *XRC = FuncX->getTrailingRequiresClause(); 6390 const Expr *YRC = FuncY->getTrailingRequiresClause(); 6391 if (!XRC != !YRC) 6392 return false; 6393 if (XRC) { 6394 llvm::FoldingSetNodeID XRCID, YRCID; 6395 XRC->Profile(XRCID, *this, /*Canonical=*/true); 6396 YRC->Profile(YRCID, *this, /*Canonical=*/true); 6397 if (XRCID != YRCID) 6398 return false; 6399 } 6400 6401 auto GetTypeAsWritten = [](const FunctionDecl *FD) { 6402 // Map to the first declaration that we've already merged into this one. 6403 // The TSI of redeclarations might not match (due to calling conventions 6404 // being inherited onto the type but not the TSI), but the TSI type of 6405 // the first declaration of the function should match across modules. 6406 FD = FD->getCanonicalDecl(); 6407 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType() 6408 : FD->getType(); 6409 }; 6410 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY); 6411 if (!hasSameType(XT, YT)) { 6412 // We can get functions with different types on the redecl chain in C++17 6413 // if they have differing exception specifications and at least one of 6414 // the excpetion specs is unresolved. 6415 auto *XFPT = XT->getAs<FunctionProtoType>(); 6416 auto *YFPT = YT->getAs<FunctionProtoType>(); 6417 if (getLangOpts().CPlusPlus17 && XFPT && YFPT && 6418 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) || 6419 isUnresolvedExceptionSpec(YFPT->getExceptionSpecType())) && 6420 // FIXME: We could make isSameEntity const after we make 6421 // hasSameFunctionTypeIgnoringExceptionSpec const. 6422 hasSameFunctionTypeIgnoringExceptionSpec(XT, YT)) 6423 return true; 6424 return false; 6425 } 6426 6427 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() && 6428 hasSameOverloadableAttrs(FuncX, FuncY); 6429 } 6430 6431 // Variables with the same type and linkage match. 6432 if (const auto *VarX = dyn_cast<VarDecl>(X)) { 6433 const auto *VarY = cast<VarDecl>(Y); 6434 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) { 6435 if (hasSameType(VarX->getType(), VarY->getType())) 6436 return true; 6437 6438 // We can get decls with different types on the redecl chain. Eg. 6439 // template <typename T> struct S { static T Var[]; }; // #1 6440 // template <typename T> T S<T>::Var[sizeof(T)]; // #2 6441 // Only? happens when completing an incomplete array type. In this case 6442 // when comparing #1 and #2 we should go through their element type. 6443 const ArrayType *VarXTy = getAsArrayType(VarX->getType()); 6444 const ArrayType *VarYTy = getAsArrayType(VarY->getType()); 6445 if (!VarXTy || !VarYTy) 6446 return false; 6447 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType()) 6448 return hasSameType(VarXTy->getElementType(), VarYTy->getElementType()); 6449 } 6450 return false; 6451 } 6452 6453 // Namespaces with the same name and inlinedness match. 6454 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) { 6455 const auto *NamespaceY = cast<NamespaceDecl>(Y); 6456 return NamespaceX->isInline() == NamespaceY->isInline(); 6457 } 6458 6459 // Identical template names and kinds match if their template parameter lists 6460 // and patterns match. 6461 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) { 6462 const auto *TemplateY = cast<TemplateDecl>(Y); 6463 return isSameEntity(TemplateX->getTemplatedDecl(), 6464 TemplateY->getTemplatedDecl()) && 6465 isSameTemplateParameterList(TemplateX->getTemplateParameters(), 6466 TemplateY->getTemplateParameters()); 6467 } 6468 6469 // Fields with the same name and the same type match. 6470 if (const auto *FDX = dyn_cast<FieldDecl>(X)) { 6471 const auto *FDY = cast<FieldDecl>(Y); 6472 // FIXME: Also check the bitwidth is odr-equivalent, if any. 6473 return hasSameType(FDX->getType(), FDY->getType()); 6474 } 6475 6476 // Indirect fields with the same target field match. 6477 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) { 6478 const auto *IFDY = cast<IndirectFieldDecl>(Y); 6479 return IFDX->getAnonField()->getCanonicalDecl() == 6480 IFDY->getAnonField()->getCanonicalDecl(); 6481 } 6482 6483 // Enumerators with the same name match. 6484 if (isa<EnumConstantDecl>(X)) 6485 // FIXME: Also check the value is odr-equivalent. 6486 return true; 6487 6488 // Using shadow declarations with the same target match. 6489 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) { 6490 const auto *USY = cast<UsingShadowDecl>(Y); 6491 return USX->getTargetDecl() == USY->getTargetDecl(); 6492 } 6493 6494 // Using declarations with the same qualifier match. (We already know that 6495 // the name matches.) 6496 if (const auto *UX = dyn_cast<UsingDecl>(X)) { 6497 const auto *UY = cast<UsingDecl>(Y); 6498 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) && 6499 UX->hasTypename() == UY->hasTypename() && 6500 UX->isAccessDeclaration() == UY->isAccessDeclaration(); 6501 } 6502 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) { 6503 const auto *UY = cast<UnresolvedUsingValueDecl>(Y); 6504 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) && 6505 UX->isAccessDeclaration() == UY->isAccessDeclaration(); 6506 } 6507 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) { 6508 return isSameQualifier( 6509 UX->getQualifier(), 6510 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier()); 6511 } 6512 6513 // Using-pack declarations are only created by instantiation, and match if 6514 // they're instantiated from matching UnresolvedUsing...Decls. 6515 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) { 6516 return declaresSameEntity( 6517 UX->getInstantiatedFromUsingDecl(), 6518 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl()); 6519 } 6520 6521 // Namespace alias definitions with the same target match. 6522 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) { 6523 const auto *NAY = cast<NamespaceAliasDecl>(Y); 6524 return NAX->getNamespace()->Equals(NAY->getNamespace()); 6525 } 6526 6527 return false; 6528 } 6529 6530 TemplateArgument 6531 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const { 6532 switch (Arg.getKind()) { 6533 case TemplateArgument::Null: 6534 return Arg; 6535 6536 case TemplateArgument::Expression: 6537 return Arg; 6538 6539 case TemplateArgument::Declaration: { 6540 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl()); 6541 return TemplateArgument(D, Arg.getParamTypeForDecl()); 6542 } 6543 6544 case TemplateArgument::NullPtr: 6545 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()), 6546 /*isNullPtr*/true); 6547 6548 case TemplateArgument::Template: 6549 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate())); 6550 6551 case TemplateArgument::TemplateExpansion: 6552 return TemplateArgument(getCanonicalTemplateName( 6553 Arg.getAsTemplateOrTemplatePattern()), 6554 Arg.getNumTemplateExpansions()); 6555 6556 case TemplateArgument::Integral: 6557 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType())); 6558 6559 case TemplateArgument::Type: 6560 return TemplateArgument(getCanonicalType(Arg.getAsType())); 6561 6562 case TemplateArgument::Pack: { 6563 if (Arg.pack_size() == 0) 6564 return Arg; 6565 6566 auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()]; 6567 unsigned Idx = 0; 6568 for (TemplateArgument::pack_iterator A = Arg.pack_begin(), 6569 AEnd = Arg.pack_end(); 6570 A != AEnd; (void)++A, ++Idx) 6571 CanonArgs[Idx] = getCanonicalTemplateArgument(*A); 6572 6573 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size())); 6574 } 6575 } 6576 6577 // Silence GCC warning 6578 llvm_unreachable("Unhandled template argument kind"); 6579 } 6580 6581 NestedNameSpecifier * 6582 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const { 6583 if (!NNS) 6584 return nullptr; 6585 6586 switch (NNS->getKind()) { 6587 case NestedNameSpecifier::Identifier: 6588 // Canonicalize the prefix but keep the identifier the same. 6589 return NestedNameSpecifier::Create(*this, 6590 getCanonicalNestedNameSpecifier(NNS->getPrefix()), 6591 NNS->getAsIdentifier()); 6592 6593 case NestedNameSpecifier::Namespace: 6594 // A namespace is canonical; build a nested-name-specifier with 6595 // this namespace and no prefix. 6596 return NestedNameSpecifier::Create(*this, nullptr, 6597 NNS->getAsNamespace()->getOriginalNamespace()); 6598 6599 case NestedNameSpecifier::NamespaceAlias: 6600 // A namespace is canonical; build a nested-name-specifier with 6601 // this namespace and no prefix. 6602 return NestedNameSpecifier::Create(*this, nullptr, 6603 NNS->getAsNamespaceAlias()->getNamespace() 6604 ->getOriginalNamespace()); 6605 6606 // The difference between TypeSpec and TypeSpecWithTemplate is that the 6607 // latter will have the 'template' keyword when printed. 6608 case NestedNameSpecifier::TypeSpec: 6609 case NestedNameSpecifier::TypeSpecWithTemplate: { 6610 const Type *T = getCanonicalType(NNS->getAsType()); 6611 6612 // If we have some kind of dependent-named type (e.g., "typename T::type"), 6613 // break it apart into its prefix and identifier, then reconsititute those 6614 // as the canonical nested-name-specifier. This is required to canonicalize 6615 // a dependent nested-name-specifier involving typedefs of dependent-name 6616 // types, e.g., 6617 // typedef typename T::type T1; 6618 // typedef typename T1::type T2; 6619 if (const auto *DNT = T->getAs<DependentNameType>()) 6620 return NestedNameSpecifier::Create( 6621 *this, DNT->getQualifier(), 6622 const_cast<IdentifierInfo *>(DNT->getIdentifier())); 6623 if (const auto *DTST = T->getAs<DependentTemplateSpecializationType>()) 6624 return NestedNameSpecifier::Create(*this, DTST->getQualifier(), true, 6625 const_cast<Type *>(T)); 6626 6627 // TODO: Set 'Template' parameter to true for other template types. 6628 return NestedNameSpecifier::Create(*this, nullptr, false, 6629 const_cast<Type *>(T)); 6630 } 6631 6632 case NestedNameSpecifier::Global: 6633 case NestedNameSpecifier::Super: 6634 // The global specifier and __super specifer are canonical and unique. 6635 return NNS; 6636 } 6637 6638 llvm_unreachable("Invalid NestedNameSpecifier::Kind!"); 6639 } 6640 6641 const ArrayType *ASTContext::getAsArrayType(QualType T) const { 6642 // Handle the non-qualified case efficiently. 6643 if (!T.hasLocalQualifiers()) { 6644 // Handle the common positive case fast. 6645 if (const auto *AT = dyn_cast<ArrayType>(T)) 6646 return AT; 6647 } 6648 6649 // Handle the common negative case fast. 6650 if (!isa<ArrayType>(T.getCanonicalType())) 6651 return nullptr; 6652 6653 // Apply any qualifiers from the array type to the element type. This 6654 // implements C99 6.7.3p8: "If the specification of an array type includes 6655 // any type qualifiers, the element type is so qualified, not the array type." 6656 6657 // If we get here, we either have type qualifiers on the type, or we have 6658 // sugar such as a typedef in the way. If we have type qualifiers on the type 6659 // we must propagate them down into the element type. 6660 6661 SplitQualType split = T.getSplitDesugaredType(); 6662 Qualifiers qs = split.Quals; 6663 6664 // If we have a simple case, just return now. 6665 const auto *ATy = dyn_cast<ArrayType>(split.Ty); 6666 if (!ATy || qs.empty()) 6667 return ATy; 6668 6669 // Otherwise, we have an array and we have qualifiers on it. Push the 6670 // qualifiers into the array element type and return a new array type. 6671 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs); 6672 6673 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy)) 6674 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(), 6675 CAT->getSizeExpr(), 6676 CAT->getSizeModifier(), 6677 CAT->getIndexTypeCVRQualifiers())); 6678 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy)) 6679 return cast<ArrayType>(getIncompleteArrayType(NewEltTy, 6680 IAT->getSizeModifier(), 6681 IAT->getIndexTypeCVRQualifiers())); 6682 6683 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy)) 6684 return cast<ArrayType>( 6685 getDependentSizedArrayType(NewEltTy, 6686 DSAT->getSizeExpr(), 6687 DSAT->getSizeModifier(), 6688 DSAT->getIndexTypeCVRQualifiers(), 6689 DSAT->getBracketsRange())); 6690 6691 const auto *VAT = cast<VariableArrayType>(ATy); 6692 return cast<ArrayType>(getVariableArrayType(NewEltTy, 6693 VAT->getSizeExpr(), 6694 VAT->getSizeModifier(), 6695 VAT->getIndexTypeCVRQualifiers(), 6696 VAT->getBracketsRange())); 6697 } 6698 6699 QualType ASTContext::getAdjustedParameterType(QualType T) const { 6700 if (T->isArrayType() || T->isFunctionType()) 6701 return getDecayedType(T); 6702 return T; 6703 } 6704 6705 QualType ASTContext::getSignatureParameterType(QualType T) const { 6706 T = getVariableArrayDecayedType(T); 6707 T = getAdjustedParameterType(T); 6708 return T.getUnqualifiedType(); 6709 } 6710 6711 QualType ASTContext::getExceptionObjectType(QualType T) const { 6712 // C++ [except.throw]p3: 6713 // A throw-expression initializes a temporary object, called the exception 6714 // object, the type of which is determined by removing any top-level 6715 // cv-qualifiers from the static type of the operand of throw and adjusting 6716 // the type from "array of T" or "function returning T" to "pointer to T" 6717 // or "pointer to function returning T", [...] 6718 T = getVariableArrayDecayedType(T); 6719 if (T->isArrayType() || T->isFunctionType()) 6720 T = getDecayedType(T); 6721 return T.getUnqualifiedType(); 6722 } 6723 6724 /// getArrayDecayedType - Return the properly qualified result of decaying the 6725 /// specified array type to a pointer. This operation is non-trivial when 6726 /// handling typedefs etc. The canonical type of "T" must be an array type, 6727 /// this returns a pointer to a properly qualified element of the array. 6728 /// 6729 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3. 6730 QualType ASTContext::getArrayDecayedType(QualType Ty) const { 6731 // Get the element type with 'getAsArrayType' so that we don't lose any 6732 // typedefs in the element type of the array. This also handles propagation 6733 // of type qualifiers from the array type into the element type if present 6734 // (C99 6.7.3p8). 6735 const ArrayType *PrettyArrayType = getAsArrayType(Ty); 6736 assert(PrettyArrayType && "Not an array type!"); 6737 6738 QualType PtrTy = getPointerType(PrettyArrayType->getElementType()); 6739 6740 // int x[restrict 4] -> int *restrict 6741 QualType Result = getQualifiedType(PtrTy, 6742 PrettyArrayType->getIndexTypeQualifiers()); 6743 6744 // int x[_Nullable] -> int * _Nullable 6745 if (auto Nullability = Ty->getNullability(*this)) { 6746 Result = const_cast<ASTContext *>(this)->getAttributedType( 6747 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result); 6748 } 6749 return Result; 6750 } 6751 6752 QualType ASTContext::getBaseElementType(const ArrayType *array) const { 6753 return getBaseElementType(array->getElementType()); 6754 } 6755 6756 QualType ASTContext::getBaseElementType(QualType type) const { 6757 Qualifiers qs; 6758 while (true) { 6759 SplitQualType split = type.getSplitDesugaredType(); 6760 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe(); 6761 if (!array) break; 6762 6763 type = array->getElementType(); 6764 qs.addConsistentQualifiers(split.Quals); 6765 } 6766 6767 return getQualifiedType(type, qs); 6768 } 6769 6770 /// getConstantArrayElementCount - Returns number of constant array elements. 6771 uint64_t 6772 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const { 6773 uint64_t ElementCount = 1; 6774 do { 6775 ElementCount *= CA->getSize().getZExtValue(); 6776 CA = dyn_cast_or_null<ConstantArrayType>( 6777 CA->getElementType()->getAsArrayTypeUnsafe()); 6778 } while (CA); 6779 return ElementCount; 6780 } 6781 6782 /// getFloatingRank - Return a relative rank for floating point types. 6783 /// This routine will assert if passed a built-in type that isn't a float. 6784 static FloatingRank getFloatingRank(QualType T) { 6785 if (const auto *CT = T->getAs<ComplexType>()) 6786 return getFloatingRank(CT->getElementType()); 6787 6788 switch (T->castAs<BuiltinType>()->getKind()) { 6789 default: llvm_unreachable("getFloatingRank(): not a floating type"); 6790 case BuiltinType::Float16: return Float16Rank; 6791 case BuiltinType::Half: return HalfRank; 6792 case BuiltinType::Float: return FloatRank; 6793 case BuiltinType::Double: return DoubleRank; 6794 case BuiltinType::LongDouble: return LongDoubleRank; 6795 case BuiltinType::Float128: return Float128Rank; 6796 case BuiltinType::BFloat16: return BFloat16Rank; 6797 case BuiltinType::Ibm128: return Ibm128Rank; 6798 } 6799 } 6800 6801 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating 6802 /// point or a complex type (based on typeDomain/typeSize). 6803 /// 'typeDomain' is a real floating point or complex type. 6804 /// 'typeSize' is a real floating point or complex type. 6805 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size, 6806 QualType Domain) const { 6807 FloatingRank EltRank = getFloatingRank(Size); 6808 if (Domain->isComplexType()) { 6809 switch (EltRank) { 6810 case BFloat16Rank: llvm_unreachable("Complex bfloat16 is not supported"); 6811 case Float16Rank: 6812 case HalfRank: llvm_unreachable("Complex half is not supported"); 6813 case Ibm128Rank: return getComplexType(Ibm128Ty); 6814 case FloatRank: return getComplexType(FloatTy); 6815 case DoubleRank: return getComplexType(DoubleTy); 6816 case LongDoubleRank: return getComplexType(LongDoubleTy); 6817 case Float128Rank: return getComplexType(Float128Ty); 6818 } 6819 } 6820 6821 assert(Domain->isRealFloatingType() && "Unknown domain!"); 6822 switch (EltRank) { 6823 case Float16Rank: return HalfTy; 6824 case BFloat16Rank: return BFloat16Ty; 6825 case HalfRank: return HalfTy; 6826 case FloatRank: return FloatTy; 6827 case DoubleRank: return DoubleTy; 6828 case LongDoubleRank: return LongDoubleTy; 6829 case Float128Rank: return Float128Ty; 6830 case Ibm128Rank: 6831 return Ibm128Ty; 6832 } 6833 llvm_unreachable("getFloatingRank(): illegal value for rank"); 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 8981 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, 8982 bool TemplateKeyword, 8983 TemplateDecl *Template) const { 8984 assert(NNS && "Missing nested-name-specifier in qualified template name"); 8985 8986 // FIXME: Canonicalization? 8987 llvm::FoldingSetNodeID ID; 8988 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template); 8989 8990 void *InsertPos = nullptr; 8991 QualifiedTemplateName *QTN = 8992 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 8993 if (!QTN) { 8994 QTN = new (*this, alignof(QualifiedTemplateName)) 8995 QualifiedTemplateName(NNS, TemplateKeyword, Template); 8996 QualifiedTemplateNames.InsertNode(QTN, InsertPos); 8997 } 8998 8999 return TemplateName(QTN); 9000 } 9001 9002 /// Retrieve the template name that represents a dependent 9003 /// template name such as \c MetaFun::template apply. 9004 TemplateName 9005 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 9006 const IdentifierInfo *Name) const { 9007 assert((!NNS || NNS->isDependent()) && 9008 "Nested name specifier must be dependent"); 9009 9010 llvm::FoldingSetNodeID ID; 9011 DependentTemplateName::Profile(ID, NNS, Name); 9012 9013 void *InsertPos = nullptr; 9014 DependentTemplateName *QTN = 9015 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 9016 9017 if (QTN) 9018 return TemplateName(QTN); 9019 9020 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 9021 if (CanonNNS == NNS) { 9022 QTN = new (*this, alignof(DependentTemplateName)) 9023 DependentTemplateName(NNS, Name); 9024 } else { 9025 TemplateName Canon = getDependentTemplateName(CanonNNS, Name); 9026 QTN = new (*this, alignof(DependentTemplateName)) 9027 DependentTemplateName(NNS, Name, Canon); 9028 DependentTemplateName *CheckQTN = 9029 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 9030 assert(!CheckQTN && "Dependent type name canonicalization broken"); 9031 (void)CheckQTN; 9032 } 9033 9034 DependentTemplateNames.InsertNode(QTN, InsertPos); 9035 return TemplateName(QTN); 9036 } 9037 9038 /// Retrieve the template name that represents a dependent 9039 /// template name such as \c MetaFun::template operator+. 9040 TemplateName 9041 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 9042 OverloadedOperatorKind Operator) const { 9043 assert((!NNS || NNS->isDependent()) && 9044 "Nested name specifier must be dependent"); 9045 9046 llvm::FoldingSetNodeID ID; 9047 DependentTemplateName::Profile(ID, NNS, Operator); 9048 9049 void *InsertPos = nullptr; 9050 DependentTemplateName *QTN 9051 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 9052 9053 if (QTN) 9054 return TemplateName(QTN); 9055 9056 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 9057 if (CanonNNS == NNS) { 9058 QTN = new (*this, alignof(DependentTemplateName)) 9059 DependentTemplateName(NNS, Operator); 9060 } else { 9061 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator); 9062 QTN = new (*this, alignof(DependentTemplateName)) 9063 DependentTemplateName(NNS, Operator, Canon); 9064 9065 DependentTemplateName *CheckQTN 9066 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 9067 assert(!CheckQTN && "Dependent template name canonicalization broken"); 9068 (void)CheckQTN; 9069 } 9070 9071 DependentTemplateNames.InsertNode(QTN, InsertPos); 9072 return TemplateName(QTN); 9073 } 9074 9075 TemplateName 9076 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param, 9077 TemplateName replacement) const { 9078 llvm::FoldingSetNodeID ID; 9079 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement); 9080 9081 void *insertPos = nullptr; 9082 SubstTemplateTemplateParmStorage *subst 9083 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos); 9084 9085 if (!subst) { 9086 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement); 9087 SubstTemplateTemplateParms.InsertNode(subst, insertPos); 9088 } 9089 9090 return TemplateName(subst); 9091 } 9092 9093 TemplateName 9094 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param, 9095 const TemplateArgument &ArgPack) const { 9096 auto &Self = const_cast<ASTContext &>(*this); 9097 llvm::FoldingSetNodeID ID; 9098 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack); 9099 9100 void *InsertPos = nullptr; 9101 SubstTemplateTemplateParmPackStorage *Subst 9102 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos); 9103 9104 if (!Subst) { 9105 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param, 9106 ArgPack.pack_size(), 9107 ArgPack.pack_begin()); 9108 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos); 9109 } 9110 9111 return TemplateName(Subst); 9112 } 9113 9114 /// getFromTargetType - Given one of the integer types provided by 9115 /// TargetInfo, produce the corresponding type. The unsigned @p Type 9116 /// is actually a value of type @c TargetInfo::IntType. 9117 CanQualType ASTContext::getFromTargetType(unsigned Type) const { 9118 switch (Type) { 9119 case TargetInfo::NoInt: return {}; 9120 case TargetInfo::SignedChar: return SignedCharTy; 9121 case TargetInfo::UnsignedChar: return UnsignedCharTy; 9122 case TargetInfo::SignedShort: return ShortTy; 9123 case TargetInfo::UnsignedShort: return UnsignedShortTy; 9124 case TargetInfo::SignedInt: return IntTy; 9125 case TargetInfo::UnsignedInt: return UnsignedIntTy; 9126 case TargetInfo::SignedLong: return LongTy; 9127 case TargetInfo::UnsignedLong: return UnsignedLongTy; 9128 case TargetInfo::SignedLongLong: return LongLongTy; 9129 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy; 9130 } 9131 9132 llvm_unreachable("Unhandled TargetInfo::IntType value"); 9133 } 9134 9135 //===----------------------------------------------------------------------===// 9136 // Type Predicates. 9137 //===----------------------------------------------------------------------===// 9138 9139 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's 9140 /// garbage collection attribute. 9141 /// 9142 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const { 9143 if (getLangOpts().getGC() == LangOptions::NonGC) 9144 return Qualifiers::GCNone; 9145 9146 assert(getLangOpts().ObjC); 9147 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr(); 9148 9149 // Default behaviour under objective-C's gc is for ObjC pointers 9150 // (or pointers to them) be treated as though they were declared 9151 // as __strong. 9152 if (GCAttrs == Qualifiers::GCNone) { 9153 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) 9154 return Qualifiers::Strong; 9155 else if (Ty->isPointerType()) 9156 return getObjCGCAttrKind(Ty->castAs<PointerType>()->getPointeeType()); 9157 } else { 9158 // It's not valid to set GC attributes on anything that isn't a 9159 // pointer. 9160 #ifndef NDEBUG 9161 QualType CT = Ty->getCanonicalTypeInternal(); 9162 while (const auto *AT = dyn_cast<ArrayType>(CT)) 9163 CT = AT->getElementType(); 9164 assert(CT->isAnyPointerType() || CT->isBlockPointerType()); 9165 #endif 9166 } 9167 return GCAttrs; 9168 } 9169 9170 //===----------------------------------------------------------------------===// 9171 // Type Compatibility Testing 9172 //===----------------------------------------------------------------------===// 9173 9174 /// areCompatVectorTypes - Return true if the two specified vector types are 9175 /// compatible. 9176 static bool areCompatVectorTypes(const VectorType *LHS, 9177 const VectorType *RHS) { 9178 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 9179 return LHS->getElementType() == RHS->getElementType() && 9180 LHS->getNumElements() == RHS->getNumElements(); 9181 } 9182 9183 /// areCompatMatrixTypes - Return true if the two specified matrix types are 9184 /// compatible. 9185 static bool areCompatMatrixTypes(const ConstantMatrixType *LHS, 9186 const ConstantMatrixType *RHS) { 9187 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 9188 return LHS->getElementType() == RHS->getElementType() && 9189 LHS->getNumRows() == RHS->getNumRows() && 9190 LHS->getNumColumns() == RHS->getNumColumns(); 9191 } 9192 9193 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec, 9194 QualType SecondVec) { 9195 assert(FirstVec->isVectorType() && "FirstVec should be a vector type"); 9196 assert(SecondVec->isVectorType() && "SecondVec should be a vector type"); 9197 9198 if (hasSameUnqualifiedType(FirstVec, SecondVec)) 9199 return true; 9200 9201 // Treat Neon vector types and most AltiVec vector types as if they are the 9202 // equivalent GCC vector types. 9203 const auto *First = FirstVec->castAs<VectorType>(); 9204 const auto *Second = SecondVec->castAs<VectorType>(); 9205 if (First->getNumElements() == Second->getNumElements() && 9206 hasSameType(First->getElementType(), Second->getElementType()) && 9207 First->getVectorKind() != VectorType::AltiVecPixel && 9208 First->getVectorKind() != VectorType::AltiVecBool && 9209 Second->getVectorKind() != VectorType::AltiVecPixel && 9210 Second->getVectorKind() != VectorType::AltiVecBool && 9211 First->getVectorKind() != VectorType::SveFixedLengthDataVector && 9212 First->getVectorKind() != VectorType::SveFixedLengthPredicateVector && 9213 Second->getVectorKind() != VectorType::SveFixedLengthDataVector && 9214 Second->getVectorKind() != VectorType::SveFixedLengthPredicateVector) 9215 return true; 9216 9217 return false; 9218 } 9219 9220 /// getSVETypeSize - Return SVE vector or predicate register size. 9221 static uint64_t getSVETypeSize(ASTContext &Context, const BuiltinType *Ty) { 9222 assert(Ty->isVLSTBuiltinType() && "Invalid SVE Type"); 9223 return Ty->getKind() == BuiltinType::SveBool 9224 ? (Context.getLangOpts().VScaleMin * 128) / Context.getCharWidth() 9225 : Context.getLangOpts().VScaleMin * 128; 9226 } 9227 9228 bool ASTContext::areCompatibleSveTypes(QualType FirstType, 9229 QualType SecondType) { 9230 assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) || 9231 (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) && 9232 "Expected SVE builtin type and vector type!"); 9233 9234 auto IsValidCast = [this](QualType FirstType, QualType SecondType) { 9235 if (const auto *BT = FirstType->getAs<BuiltinType>()) { 9236 if (const auto *VT = SecondType->getAs<VectorType>()) { 9237 // Predicates have the same representation as uint8 so we also have to 9238 // check the kind to make these types incompatible. 9239 if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 9240 return BT->getKind() == BuiltinType::SveBool; 9241 else if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) 9242 return VT->getElementType().getCanonicalType() == 9243 FirstType->getSveEltType(*this); 9244 else if (VT->getVectorKind() == VectorType::GenericVector) 9245 return getTypeSize(SecondType) == getSVETypeSize(*this, BT) && 9246 hasSameType(VT->getElementType(), 9247 getBuiltinVectorTypeInfo(BT).ElementType); 9248 } 9249 } 9250 return false; 9251 }; 9252 9253 return IsValidCast(FirstType, SecondType) || 9254 IsValidCast(SecondType, FirstType); 9255 } 9256 9257 bool ASTContext::areLaxCompatibleSveTypes(QualType FirstType, 9258 QualType SecondType) { 9259 assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) || 9260 (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) && 9261 "Expected SVE builtin type and vector type!"); 9262 9263 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) { 9264 const auto *BT = FirstType->getAs<BuiltinType>(); 9265 if (!BT) 9266 return false; 9267 9268 const auto *VecTy = SecondType->getAs<VectorType>(); 9269 if (VecTy && 9270 (VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector || 9271 VecTy->getVectorKind() == VectorType::GenericVector)) { 9272 const LangOptions::LaxVectorConversionKind LVCKind = 9273 getLangOpts().getLaxVectorConversions(); 9274 9275 // Can not convert between sve predicates and sve vectors because of 9276 // different size. 9277 if (BT->getKind() == BuiltinType::SveBool && 9278 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector) 9279 return false; 9280 9281 // If __ARM_FEATURE_SVE_BITS != N do not allow GNU vector lax conversion. 9282 // "Whenever __ARM_FEATURE_SVE_BITS==N, GNUT implicitly 9283 // converts to VLAT and VLAT implicitly converts to GNUT." 9284 // ACLE Spec Version 00bet6, 3.7.3.2. Behavior common to vectors and 9285 // predicates. 9286 if (VecTy->getVectorKind() == VectorType::GenericVector && 9287 getTypeSize(SecondType) != getSVETypeSize(*this, BT)) 9288 return false; 9289 9290 // If -flax-vector-conversions=all is specified, the types are 9291 // certainly compatible. 9292 if (LVCKind == LangOptions::LaxVectorConversionKind::All) 9293 return true; 9294 9295 // If -flax-vector-conversions=integer is specified, the types are 9296 // compatible if the elements are integer types. 9297 if (LVCKind == LangOptions::LaxVectorConversionKind::Integer) 9298 return VecTy->getElementType().getCanonicalType()->isIntegerType() && 9299 FirstType->getSveEltType(*this)->isIntegerType(); 9300 } 9301 9302 return false; 9303 }; 9304 9305 return IsLaxCompatible(FirstType, SecondType) || 9306 IsLaxCompatible(SecondType, FirstType); 9307 } 9308 9309 bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const { 9310 while (true) { 9311 // __strong id 9312 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) { 9313 if (Attr->getAttrKind() == attr::ObjCOwnership) 9314 return true; 9315 9316 Ty = Attr->getModifiedType(); 9317 9318 // X *__strong (...) 9319 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) { 9320 Ty = Paren->getInnerType(); 9321 9322 // We do not want to look through typedefs, typeof(expr), 9323 // typeof(type), or any other way that the type is somehow 9324 // abstracted. 9325 } else { 9326 return false; 9327 } 9328 } 9329 } 9330 9331 //===----------------------------------------------------------------------===// 9332 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's. 9333 //===----------------------------------------------------------------------===// 9334 9335 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the 9336 /// inheritance hierarchy of 'rProto'. 9337 bool 9338 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, 9339 ObjCProtocolDecl *rProto) const { 9340 if (declaresSameEntity(lProto, rProto)) 9341 return true; 9342 for (auto *PI : rProto->protocols()) 9343 if (ProtocolCompatibleWithProtocol(lProto, PI)) 9344 return true; 9345 return false; 9346 } 9347 9348 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and 9349 /// Class<pr1, ...>. 9350 bool ASTContext::ObjCQualifiedClassTypesAreCompatible( 9351 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) { 9352 for (auto *lhsProto : lhs->quals()) { 9353 bool match = false; 9354 for (auto *rhsProto : rhs->quals()) { 9355 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) { 9356 match = true; 9357 break; 9358 } 9359 } 9360 if (!match) 9361 return false; 9362 } 9363 return true; 9364 } 9365 9366 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an 9367 /// ObjCQualifiedIDType. 9368 bool ASTContext::ObjCQualifiedIdTypesAreCompatible( 9369 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs, 9370 bool compare) { 9371 // Allow id<P..> and an 'id' in all cases. 9372 if (lhs->isObjCIdType() || rhs->isObjCIdType()) 9373 return true; 9374 9375 // Don't allow id<P..> to convert to Class or Class<P..> in either direction. 9376 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() || 9377 rhs->isObjCClassType() || rhs->isObjCQualifiedClassType()) 9378 return false; 9379 9380 if (lhs->isObjCQualifiedIdType()) { 9381 if (rhs->qual_empty()) { 9382 // If the RHS is a unqualified interface pointer "NSString*", 9383 // make sure we check the class hierarchy. 9384 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) { 9385 for (auto *I : lhs->quals()) { 9386 // when comparing an id<P> on lhs with a static type on rhs, 9387 // see if static class implements all of id's protocols, directly or 9388 // through its super class and categories. 9389 if (!rhsID->ClassImplementsProtocol(I, true)) 9390 return false; 9391 } 9392 } 9393 // If there are no qualifiers and no interface, we have an 'id'. 9394 return true; 9395 } 9396 // Both the right and left sides have qualifiers. 9397 for (auto *lhsProto : lhs->quals()) { 9398 bool match = false; 9399 9400 // when comparing an id<P> on lhs with a static type on rhs, 9401 // see if static class implements all of id's protocols, directly or 9402 // through its super class and categories. 9403 for (auto *rhsProto : rhs->quals()) { 9404 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 9405 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 9406 match = true; 9407 break; 9408 } 9409 } 9410 // If the RHS is a qualified interface pointer "NSString<P>*", 9411 // make sure we check the class hierarchy. 9412 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) { 9413 for (auto *I : lhs->quals()) { 9414 // when comparing an id<P> on lhs with a static type on rhs, 9415 // see if static class implements all of id's protocols, directly or 9416 // through its super class and categories. 9417 if (rhsID->ClassImplementsProtocol(I, true)) { 9418 match = true; 9419 break; 9420 } 9421 } 9422 } 9423 if (!match) 9424 return false; 9425 } 9426 9427 return true; 9428 } 9429 9430 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>"); 9431 9432 if (lhs->getInterfaceType()) { 9433 // If both the right and left sides have qualifiers. 9434 for (auto *lhsProto : lhs->quals()) { 9435 bool match = false; 9436 9437 // when comparing an id<P> on rhs with a static type on lhs, 9438 // see if static class implements all of id's protocols, directly or 9439 // through its super class and categories. 9440 // First, lhs protocols in the qualifier list must be found, direct 9441 // or indirect in rhs's qualifier list or it is a mismatch. 9442 for (auto *rhsProto : rhs->quals()) { 9443 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 9444 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 9445 match = true; 9446 break; 9447 } 9448 } 9449 if (!match) 9450 return false; 9451 } 9452 9453 // Static class's protocols, or its super class or category protocols 9454 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch. 9455 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) { 9456 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols; 9457 CollectInheritedProtocols(lhsID, LHSInheritedProtocols); 9458 // This is rather dubious but matches gcc's behavior. If lhs has 9459 // no type qualifier and its class has no static protocol(s) 9460 // assume that it is mismatch. 9461 if (LHSInheritedProtocols.empty() && lhs->qual_empty()) 9462 return false; 9463 for (auto *lhsProto : LHSInheritedProtocols) { 9464 bool match = false; 9465 for (auto *rhsProto : rhs->quals()) { 9466 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 9467 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 9468 match = true; 9469 break; 9470 } 9471 } 9472 if (!match) 9473 return false; 9474 } 9475 } 9476 return true; 9477 } 9478 return false; 9479 } 9480 9481 /// canAssignObjCInterfaces - Return true if the two interface types are 9482 /// compatible for assignment from RHS to LHS. This handles validation of any 9483 /// protocol qualifiers on the LHS or RHS. 9484 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, 9485 const ObjCObjectPointerType *RHSOPT) { 9486 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 9487 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 9488 9489 // If either type represents the built-in 'id' type, return true. 9490 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId()) 9491 return true; 9492 9493 // Function object that propagates a successful result or handles 9494 // __kindof types. 9495 auto finish = [&](bool succeeded) -> bool { 9496 if (succeeded) 9497 return true; 9498 9499 if (!RHS->isKindOfType()) 9500 return false; 9501 9502 // Strip off __kindof and protocol qualifiers, then check whether 9503 // we can assign the other way. 9504 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this), 9505 LHSOPT->stripObjCKindOfTypeAndQuals(*this)); 9506 }; 9507 9508 // Casts from or to id<P> are allowed when the other side has compatible 9509 // protocols. 9510 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) { 9511 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false)); 9512 } 9513 9514 // Verify protocol compatibility for casts from Class<P1> to Class<P2>. 9515 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) { 9516 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT)); 9517 } 9518 9519 // Casts from Class to Class<Foo>, or vice-versa, are allowed. 9520 if (LHS->isObjCClass() && RHS->isObjCClass()) { 9521 return true; 9522 } 9523 9524 // If we have 2 user-defined types, fall into that path. 9525 if (LHS->getInterface() && RHS->getInterface()) { 9526 return finish(canAssignObjCInterfaces(LHS, RHS)); 9527 } 9528 9529 return false; 9530 } 9531 9532 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written 9533 /// for providing type-safety for objective-c pointers used to pass/return 9534 /// arguments in block literals. When passed as arguments, passing 'A*' where 9535 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is 9536 /// not OK. For the return type, the opposite is not OK. 9537 bool ASTContext::canAssignObjCInterfacesInBlockPointer( 9538 const ObjCObjectPointerType *LHSOPT, 9539 const ObjCObjectPointerType *RHSOPT, 9540 bool BlockReturnType) { 9541 9542 // Function object that propagates a successful result or handles 9543 // __kindof types. 9544 auto finish = [&](bool succeeded) -> bool { 9545 if (succeeded) 9546 return true; 9547 9548 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT; 9549 if (!Expected->isKindOfType()) 9550 return false; 9551 9552 // Strip off __kindof and protocol qualifiers, then check whether 9553 // we can assign the other way. 9554 return canAssignObjCInterfacesInBlockPointer( 9555 RHSOPT->stripObjCKindOfTypeAndQuals(*this), 9556 LHSOPT->stripObjCKindOfTypeAndQuals(*this), 9557 BlockReturnType); 9558 }; 9559 9560 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType()) 9561 return true; 9562 9563 if (LHSOPT->isObjCBuiltinType()) { 9564 return finish(RHSOPT->isObjCBuiltinType() || 9565 RHSOPT->isObjCQualifiedIdType()); 9566 } 9567 9568 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) { 9569 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking) 9570 // Use for block parameters previous type checking for compatibility. 9571 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) || 9572 // Or corrected type checking as in non-compat mode. 9573 (!BlockReturnType && 9574 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false))); 9575 else 9576 return finish(ObjCQualifiedIdTypesAreCompatible( 9577 (BlockReturnType ? LHSOPT : RHSOPT), 9578 (BlockReturnType ? RHSOPT : LHSOPT), false)); 9579 } 9580 9581 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType(); 9582 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType(); 9583 if (LHS && RHS) { // We have 2 user-defined types. 9584 if (LHS != RHS) { 9585 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl())) 9586 return finish(BlockReturnType); 9587 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl())) 9588 return finish(!BlockReturnType); 9589 } 9590 else 9591 return true; 9592 } 9593 return false; 9594 } 9595 9596 /// Comparison routine for Objective-C protocols to be used with 9597 /// llvm::array_pod_sort. 9598 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs, 9599 ObjCProtocolDecl * const *rhs) { 9600 return (*lhs)->getName().compare((*rhs)->getName()); 9601 } 9602 9603 /// getIntersectionOfProtocols - This routine finds the intersection of set 9604 /// of protocols inherited from two distinct objective-c pointer objects with 9605 /// the given common base. 9606 /// It is used to build composite qualifier list of the composite type of 9607 /// the conditional expression involving two objective-c pointer objects. 9608 static 9609 void getIntersectionOfProtocols(ASTContext &Context, 9610 const ObjCInterfaceDecl *CommonBase, 9611 const ObjCObjectPointerType *LHSOPT, 9612 const ObjCObjectPointerType *RHSOPT, 9613 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) { 9614 9615 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 9616 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 9617 assert(LHS->getInterface() && "LHS must have an interface base"); 9618 assert(RHS->getInterface() && "RHS must have an interface base"); 9619 9620 // Add all of the protocols for the LHS. 9621 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet; 9622 9623 // Start with the protocol qualifiers. 9624 for (auto proto : LHS->quals()) { 9625 Context.CollectInheritedProtocols(proto, LHSProtocolSet); 9626 } 9627 9628 // Also add the protocols associated with the LHS interface. 9629 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet); 9630 9631 // Add all of the protocols for the RHS. 9632 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet; 9633 9634 // Start with the protocol qualifiers. 9635 for (auto proto : RHS->quals()) { 9636 Context.CollectInheritedProtocols(proto, RHSProtocolSet); 9637 } 9638 9639 // Also add the protocols associated with the RHS interface. 9640 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet); 9641 9642 // Compute the intersection of the collected protocol sets. 9643 for (auto proto : LHSProtocolSet) { 9644 if (RHSProtocolSet.count(proto)) 9645 IntersectionSet.push_back(proto); 9646 } 9647 9648 // Compute the set of protocols that is implied by either the common type or 9649 // the protocols within the intersection. 9650 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols; 9651 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols); 9652 9653 // Remove any implied protocols from the list of inherited protocols. 9654 if (!ImpliedProtocols.empty()) { 9655 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool { 9656 return ImpliedProtocols.contains(proto); 9657 }); 9658 } 9659 9660 // Sort the remaining protocols by name. 9661 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(), 9662 compareObjCProtocolsByName); 9663 } 9664 9665 /// Determine whether the first type is a subtype of the second. 9666 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs, 9667 QualType rhs) { 9668 // Common case: two object pointers. 9669 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>(); 9670 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 9671 if (lhsOPT && rhsOPT) 9672 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT); 9673 9674 // Two block pointers. 9675 const auto *lhsBlock = lhs->getAs<BlockPointerType>(); 9676 const auto *rhsBlock = rhs->getAs<BlockPointerType>(); 9677 if (lhsBlock && rhsBlock) 9678 return ctx.typesAreBlockPointerCompatible(lhs, rhs); 9679 9680 // If either is an unqualified 'id' and the other is a block, it's 9681 // acceptable. 9682 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) || 9683 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock)) 9684 return true; 9685 9686 return false; 9687 } 9688 9689 // Check that the given Objective-C type argument lists are equivalent. 9690 static bool sameObjCTypeArgs(ASTContext &ctx, 9691 const ObjCInterfaceDecl *iface, 9692 ArrayRef<QualType> lhsArgs, 9693 ArrayRef<QualType> rhsArgs, 9694 bool stripKindOf) { 9695 if (lhsArgs.size() != rhsArgs.size()) 9696 return false; 9697 9698 ObjCTypeParamList *typeParams = iface->getTypeParamList(); 9699 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) { 9700 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i])) 9701 continue; 9702 9703 switch (typeParams->begin()[i]->getVariance()) { 9704 case ObjCTypeParamVariance::Invariant: 9705 if (!stripKindOf || 9706 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx), 9707 rhsArgs[i].stripObjCKindOfType(ctx))) { 9708 return false; 9709 } 9710 break; 9711 9712 case ObjCTypeParamVariance::Covariant: 9713 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i])) 9714 return false; 9715 break; 9716 9717 case ObjCTypeParamVariance::Contravariant: 9718 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i])) 9719 return false; 9720 break; 9721 } 9722 } 9723 9724 return true; 9725 } 9726 9727 QualType ASTContext::areCommonBaseCompatible( 9728 const ObjCObjectPointerType *Lptr, 9729 const ObjCObjectPointerType *Rptr) { 9730 const ObjCObjectType *LHS = Lptr->getObjectType(); 9731 const ObjCObjectType *RHS = Rptr->getObjectType(); 9732 const ObjCInterfaceDecl* LDecl = LHS->getInterface(); 9733 const ObjCInterfaceDecl* RDecl = RHS->getInterface(); 9734 9735 if (!LDecl || !RDecl) 9736 return {}; 9737 9738 // When either LHS or RHS is a kindof type, we should return a kindof type. 9739 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return 9740 // kindof(A). 9741 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType(); 9742 9743 // Follow the left-hand side up the class hierarchy until we either hit a 9744 // root or find the RHS. Record the ancestors in case we don't find it. 9745 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4> 9746 LHSAncestors; 9747 while (true) { 9748 // Record this ancestor. We'll need this if the common type isn't in the 9749 // path from the LHS to the root. 9750 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS; 9751 9752 if (declaresSameEntity(LHS->getInterface(), RDecl)) { 9753 // Get the type arguments. 9754 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten(); 9755 bool anyChanges = false; 9756 if (LHS->isSpecialized() && RHS->isSpecialized()) { 9757 // Both have type arguments, compare them. 9758 if (!sameObjCTypeArgs(*this, LHS->getInterface(), 9759 LHS->getTypeArgs(), RHS->getTypeArgs(), 9760 /*stripKindOf=*/true)) 9761 return {}; 9762 } else if (LHS->isSpecialized() != RHS->isSpecialized()) { 9763 // If only one has type arguments, the result will not have type 9764 // arguments. 9765 LHSTypeArgs = {}; 9766 anyChanges = true; 9767 } 9768 9769 // Compute the intersection of protocols. 9770 SmallVector<ObjCProtocolDecl *, 8> Protocols; 9771 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr, 9772 Protocols); 9773 if (!Protocols.empty()) 9774 anyChanges = true; 9775 9776 // If anything in the LHS will have changed, build a new result type. 9777 // If we need to return a kindof type but LHS is not a kindof type, we 9778 // build a new result type. 9779 if (anyChanges || LHS->isKindOfType() != anyKindOf) { 9780 QualType Result = getObjCInterfaceType(LHS->getInterface()); 9781 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols, 9782 anyKindOf || LHS->isKindOfType()); 9783 return getObjCObjectPointerType(Result); 9784 } 9785 9786 return getObjCObjectPointerType(QualType(LHS, 0)); 9787 } 9788 9789 // Find the superclass. 9790 QualType LHSSuperType = LHS->getSuperClassType(); 9791 if (LHSSuperType.isNull()) 9792 break; 9793 9794 LHS = LHSSuperType->castAs<ObjCObjectType>(); 9795 } 9796 9797 // We didn't find anything by following the LHS to its root; now check 9798 // the RHS against the cached set of ancestors. 9799 while (true) { 9800 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl()); 9801 if (KnownLHS != LHSAncestors.end()) { 9802 LHS = KnownLHS->second; 9803 9804 // Get the type arguments. 9805 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten(); 9806 bool anyChanges = false; 9807 if (LHS->isSpecialized() && RHS->isSpecialized()) { 9808 // Both have type arguments, compare them. 9809 if (!sameObjCTypeArgs(*this, LHS->getInterface(), 9810 LHS->getTypeArgs(), RHS->getTypeArgs(), 9811 /*stripKindOf=*/true)) 9812 return {}; 9813 } else if (LHS->isSpecialized() != RHS->isSpecialized()) { 9814 // If only one has type arguments, the result will not have type 9815 // arguments. 9816 RHSTypeArgs = {}; 9817 anyChanges = true; 9818 } 9819 9820 // Compute the intersection of protocols. 9821 SmallVector<ObjCProtocolDecl *, 8> Protocols; 9822 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr, 9823 Protocols); 9824 if (!Protocols.empty()) 9825 anyChanges = true; 9826 9827 // If we need to return a kindof type but RHS is not a kindof type, we 9828 // build a new result type. 9829 if (anyChanges || RHS->isKindOfType() != anyKindOf) { 9830 QualType Result = getObjCInterfaceType(RHS->getInterface()); 9831 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols, 9832 anyKindOf || RHS->isKindOfType()); 9833 return getObjCObjectPointerType(Result); 9834 } 9835 9836 return getObjCObjectPointerType(QualType(RHS, 0)); 9837 } 9838 9839 // Find the superclass of the RHS. 9840 QualType RHSSuperType = RHS->getSuperClassType(); 9841 if (RHSSuperType.isNull()) 9842 break; 9843 9844 RHS = RHSSuperType->castAs<ObjCObjectType>(); 9845 } 9846 9847 return {}; 9848 } 9849 9850 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS, 9851 const ObjCObjectType *RHS) { 9852 assert(LHS->getInterface() && "LHS is not an interface type"); 9853 assert(RHS->getInterface() && "RHS is not an interface type"); 9854 9855 // Verify that the base decls are compatible: the RHS must be a subclass of 9856 // the LHS. 9857 ObjCInterfaceDecl *LHSInterface = LHS->getInterface(); 9858 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface()); 9859 if (!IsSuperClass) 9860 return false; 9861 9862 // If the LHS has protocol qualifiers, determine whether all of them are 9863 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the 9864 // LHS). 9865 if (LHS->getNumProtocols() > 0) { 9866 // OK if conversion of LHS to SuperClass results in narrowing of types 9867 // ; i.e., SuperClass may implement at least one of the protocols 9868 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok. 9869 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>. 9870 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols; 9871 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols); 9872 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's 9873 // qualifiers. 9874 for (auto *RHSPI : RHS->quals()) 9875 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols); 9876 // If there is no protocols associated with RHS, it is not a match. 9877 if (SuperClassInheritedProtocols.empty()) 9878 return false; 9879 9880 for (const auto *LHSProto : LHS->quals()) { 9881 bool SuperImplementsProtocol = false; 9882 for (auto *SuperClassProto : SuperClassInheritedProtocols) 9883 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) { 9884 SuperImplementsProtocol = true; 9885 break; 9886 } 9887 if (!SuperImplementsProtocol) 9888 return false; 9889 } 9890 } 9891 9892 // If the LHS is specialized, we may need to check type arguments. 9893 if (LHS->isSpecialized()) { 9894 // Follow the superclass chain until we've matched the LHS class in the 9895 // hierarchy. This substitutes type arguments through. 9896 const ObjCObjectType *RHSSuper = RHS; 9897 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface)) 9898 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>(); 9899 9900 // If the RHS is specializd, compare type arguments. 9901 if (RHSSuper->isSpecialized() && 9902 !sameObjCTypeArgs(*this, LHS->getInterface(), 9903 LHS->getTypeArgs(), RHSSuper->getTypeArgs(), 9904 /*stripKindOf=*/true)) { 9905 return false; 9906 } 9907 } 9908 9909 return true; 9910 } 9911 9912 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) { 9913 // get the "pointed to" types 9914 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>(); 9915 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>(); 9916 9917 if (!LHSOPT || !RHSOPT) 9918 return false; 9919 9920 return canAssignObjCInterfaces(LHSOPT, RHSOPT) || 9921 canAssignObjCInterfaces(RHSOPT, LHSOPT); 9922 } 9923 9924 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) { 9925 return canAssignObjCInterfaces( 9926 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(), 9927 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>()); 9928 } 9929 9930 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible, 9931 /// both shall have the identically qualified version of a compatible type. 9932 /// C99 6.2.7p1: Two types have compatible types if their types are the 9933 /// same. See 6.7.[2,3,5] for additional rules. 9934 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS, 9935 bool CompareUnqualified) { 9936 if (getLangOpts().CPlusPlus) 9937 return hasSameType(LHS, RHS); 9938 9939 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull(); 9940 } 9941 9942 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) { 9943 return typesAreCompatible(LHS, RHS); 9944 } 9945 9946 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) { 9947 return !mergeTypes(LHS, RHS, true).isNull(); 9948 } 9949 9950 /// mergeTransparentUnionType - if T is a transparent union type and a member 9951 /// of T is compatible with SubType, return the merged type, else return 9952 /// QualType() 9953 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType, 9954 bool OfBlockPointer, 9955 bool Unqualified) { 9956 if (const RecordType *UT = T->getAsUnionType()) { 9957 RecordDecl *UD = UT->getDecl(); 9958 if (UD->hasAttr<TransparentUnionAttr>()) { 9959 for (const auto *I : UD->fields()) { 9960 QualType ET = I->getType().getUnqualifiedType(); 9961 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified); 9962 if (!MT.isNull()) 9963 return MT; 9964 } 9965 } 9966 } 9967 9968 return {}; 9969 } 9970 9971 /// mergeFunctionParameterTypes - merge two types which appear as function 9972 /// parameter types 9973 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs, 9974 bool OfBlockPointer, 9975 bool Unqualified) { 9976 // GNU extension: two types are compatible if they appear as a function 9977 // argument, one of the types is a transparent union type and the other 9978 // type is compatible with a union member 9979 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer, 9980 Unqualified); 9981 if (!lmerge.isNull()) 9982 return lmerge; 9983 9984 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer, 9985 Unqualified); 9986 if (!rmerge.isNull()) 9987 return rmerge; 9988 9989 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified); 9990 } 9991 9992 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, 9993 bool OfBlockPointer, bool Unqualified, 9994 bool AllowCXX) { 9995 const auto *lbase = lhs->castAs<FunctionType>(); 9996 const auto *rbase = rhs->castAs<FunctionType>(); 9997 const auto *lproto = dyn_cast<FunctionProtoType>(lbase); 9998 const auto *rproto = dyn_cast<FunctionProtoType>(rbase); 9999 bool allLTypes = true; 10000 bool allRTypes = true; 10001 10002 // Check return type 10003 QualType retType; 10004 if (OfBlockPointer) { 10005 QualType RHS = rbase->getReturnType(); 10006 QualType LHS = lbase->getReturnType(); 10007 bool UnqualifiedResult = Unqualified; 10008 if (!UnqualifiedResult) 10009 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers()); 10010 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true); 10011 } 10012 else 10013 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false, 10014 Unqualified); 10015 if (retType.isNull()) 10016 return {}; 10017 10018 if (Unqualified) 10019 retType = retType.getUnqualifiedType(); 10020 10021 CanQualType LRetType = getCanonicalType(lbase->getReturnType()); 10022 CanQualType RRetType = getCanonicalType(rbase->getReturnType()); 10023 if (Unqualified) { 10024 LRetType = LRetType.getUnqualifiedType(); 10025 RRetType = RRetType.getUnqualifiedType(); 10026 } 10027 10028 if (getCanonicalType(retType) != LRetType) 10029 allLTypes = false; 10030 if (getCanonicalType(retType) != RRetType) 10031 allRTypes = false; 10032 10033 // FIXME: double check this 10034 // FIXME: should we error if lbase->getRegParmAttr() != 0 && 10035 // rbase->getRegParmAttr() != 0 && 10036 // lbase->getRegParmAttr() != rbase->getRegParmAttr()? 10037 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo(); 10038 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo(); 10039 10040 // Compatible functions must have compatible calling conventions 10041 if (lbaseInfo.getCC() != rbaseInfo.getCC()) 10042 return {}; 10043 10044 // Regparm is part of the calling convention. 10045 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm()) 10046 return {}; 10047 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm()) 10048 return {}; 10049 10050 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult()) 10051 return {}; 10052 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs()) 10053 return {}; 10054 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck()) 10055 return {}; 10056 10057 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'. 10058 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn(); 10059 10060 if (lbaseInfo.getNoReturn() != NoReturn) 10061 allLTypes = false; 10062 if (rbaseInfo.getNoReturn() != NoReturn) 10063 allRTypes = false; 10064 10065 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn); 10066 10067 if (lproto && rproto) { // two C99 style function prototypes 10068 assert((AllowCXX || 10069 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) && 10070 "C++ shouldn't be here"); 10071 // Compatible functions must have the same number of parameters 10072 if (lproto->getNumParams() != rproto->getNumParams()) 10073 return {}; 10074 10075 // Variadic and non-variadic functions aren't compatible 10076 if (lproto->isVariadic() != rproto->isVariadic()) 10077 return {}; 10078 10079 if (lproto->getMethodQuals() != rproto->getMethodQuals()) 10080 return {}; 10081 10082 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos; 10083 bool canUseLeft, canUseRight; 10084 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight, 10085 newParamInfos)) 10086 return {}; 10087 10088 if (!canUseLeft) 10089 allLTypes = false; 10090 if (!canUseRight) 10091 allRTypes = false; 10092 10093 // Check parameter type compatibility 10094 SmallVector<QualType, 10> types; 10095 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) { 10096 QualType lParamType = lproto->getParamType(i).getUnqualifiedType(); 10097 QualType rParamType = rproto->getParamType(i).getUnqualifiedType(); 10098 QualType paramType = mergeFunctionParameterTypes( 10099 lParamType, rParamType, OfBlockPointer, Unqualified); 10100 if (paramType.isNull()) 10101 return {}; 10102 10103 if (Unqualified) 10104 paramType = paramType.getUnqualifiedType(); 10105 10106 types.push_back(paramType); 10107 if (Unqualified) { 10108 lParamType = lParamType.getUnqualifiedType(); 10109 rParamType = rParamType.getUnqualifiedType(); 10110 } 10111 10112 if (getCanonicalType(paramType) != getCanonicalType(lParamType)) 10113 allLTypes = false; 10114 if (getCanonicalType(paramType) != getCanonicalType(rParamType)) 10115 allRTypes = false; 10116 } 10117 10118 if (allLTypes) return lhs; 10119 if (allRTypes) return rhs; 10120 10121 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo(); 10122 EPI.ExtInfo = einfo; 10123 EPI.ExtParameterInfos = 10124 newParamInfos.empty() ? nullptr : newParamInfos.data(); 10125 return getFunctionType(retType, types, EPI); 10126 } 10127 10128 if (lproto) allRTypes = false; 10129 if (rproto) allLTypes = false; 10130 10131 const FunctionProtoType *proto = lproto ? lproto : rproto; 10132 if (proto) { 10133 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here"); 10134 if (proto->isVariadic()) 10135 return {}; 10136 // Check that the types are compatible with the types that 10137 // would result from default argument promotions (C99 6.7.5.3p15). 10138 // The only types actually affected are promotable integer 10139 // types and floats, which would be passed as a different 10140 // type depending on whether the prototype is visible. 10141 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) { 10142 QualType paramTy = proto->getParamType(i); 10143 10144 // Look at the converted type of enum types, since that is the type used 10145 // to pass enum values. 10146 if (const auto *Enum = paramTy->getAs<EnumType>()) { 10147 paramTy = Enum->getDecl()->getIntegerType(); 10148 if (paramTy.isNull()) 10149 return {}; 10150 } 10151 10152 if (paramTy->isPromotableIntegerType() || 10153 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy) 10154 return {}; 10155 } 10156 10157 if (allLTypes) return lhs; 10158 if (allRTypes) return rhs; 10159 10160 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo(); 10161 EPI.ExtInfo = einfo; 10162 return getFunctionType(retType, proto->getParamTypes(), EPI); 10163 } 10164 10165 if (allLTypes) return lhs; 10166 if (allRTypes) return rhs; 10167 return getFunctionNoProtoType(retType, einfo); 10168 } 10169 10170 /// Given that we have an enum type and a non-enum type, try to merge them. 10171 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET, 10172 QualType other, bool isBlockReturnType) { 10173 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char, 10174 // a signed integer type, or an unsigned integer type. 10175 // Compatibility is based on the underlying type, not the promotion 10176 // type. 10177 QualType underlyingType = ET->getDecl()->getIntegerType(); 10178 if (underlyingType.isNull()) 10179 return {}; 10180 if (Context.hasSameType(underlyingType, other)) 10181 return other; 10182 10183 // In block return types, we're more permissive and accept any 10184 // integral type of the same size. 10185 if (isBlockReturnType && other->isIntegerType() && 10186 Context.getTypeSize(underlyingType) == Context.getTypeSize(other)) 10187 return other; 10188 10189 return {}; 10190 } 10191 10192 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, 10193 bool OfBlockPointer, 10194 bool Unqualified, bool BlockReturnType) { 10195 // For C++ we will not reach this code with reference types (see below), 10196 // for OpenMP variant call overloading we might. 10197 // 10198 // C++ [expr]: If an expression initially has the type "reference to T", the 10199 // type is adjusted to "T" prior to any further analysis, the expression 10200 // designates the object or function denoted by the reference, and the 10201 // expression is an lvalue unless the reference is an rvalue reference and 10202 // the expression is a function call (possibly inside parentheses). 10203 auto *LHSRefTy = LHS->getAs<ReferenceType>(); 10204 auto *RHSRefTy = RHS->getAs<ReferenceType>(); 10205 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy && 10206 LHS->getTypeClass() == RHS->getTypeClass()) 10207 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(), 10208 OfBlockPointer, Unqualified, BlockReturnType); 10209 if (LHSRefTy || RHSRefTy) 10210 return {}; 10211 10212 if (Unqualified) { 10213 LHS = LHS.getUnqualifiedType(); 10214 RHS = RHS.getUnqualifiedType(); 10215 } 10216 10217 QualType LHSCan = getCanonicalType(LHS), 10218 RHSCan = getCanonicalType(RHS); 10219 10220 // If two types are identical, they are compatible. 10221 if (LHSCan == RHSCan) 10222 return LHS; 10223 10224 // If the qualifiers are different, the types aren't compatible... mostly. 10225 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 10226 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 10227 if (LQuals != RQuals) { 10228 // If any of these qualifiers are different, we have a type 10229 // mismatch. 10230 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 10231 LQuals.getAddressSpace() != RQuals.getAddressSpace() || 10232 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() || 10233 LQuals.hasUnaligned() != RQuals.hasUnaligned()) 10234 return {}; 10235 10236 // Exactly one GC qualifier difference is allowed: __strong is 10237 // okay if the other type has no GC qualifier but is an Objective 10238 // C object pointer (i.e. implicitly strong by default). We fix 10239 // this by pretending that the unqualified type was actually 10240 // qualified __strong. 10241 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 10242 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 10243 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 10244 10245 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 10246 return {}; 10247 10248 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) { 10249 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong)); 10250 } 10251 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) { 10252 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS); 10253 } 10254 return {}; 10255 } 10256 10257 // Okay, qualifiers are equal. 10258 10259 Type::TypeClass LHSClass = LHSCan->getTypeClass(); 10260 Type::TypeClass RHSClass = RHSCan->getTypeClass(); 10261 10262 // We want to consider the two function types to be the same for these 10263 // comparisons, just force one to the other. 10264 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto; 10265 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto; 10266 10267 // Same as above for arrays 10268 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray) 10269 LHSClass = Type::ConstantArray; 10270 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray) 10271 RHSClass = Type::ConstantArray; 10272 10273 // ObjCInterfaces are just specialized ObjCObjects. 10274 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject; 10275 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject; 10276 10277 // Canonicalize ExtVector -> Vector. 10278 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector; 10279 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector; 10280 10281 // If the canonical type classes don't match. 10282 if (LHSClass != RHSClass) { 10283 // Note that we only have special rules for turning block enum 10284 // returns into block int returns, not vice-versa. 10285 if (const auto *ETy = LHS->getAs<EnumType>()) { 10286 return mergeEnumWithInteger(*this, ETy, RHS, false); 10287 } 10288 if (const EnumType* ETy = RHS->getAs<EnumType>()) { 10289 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType); 10290 } 10291 // allow block pointer type to match an 'id' type. 10292 if (OfBlockPointer && !BlockReturnType) { 10293 if (LHS->isObjCIdType() && RHS->isBlockPointerType()) 10294 return LHS; 10295 if (RHS->isObjCIdType() && LHS->isBlockPointerType()) 10296 return RHS; 10297 } 10298 10299 return {}; 10300 } 10301 10302 // The canonical type classes match. 10303 switch (LHSClass) { 10304 #define TYPE(Class, Base) 10305 #define ABSTRACT_TYPE(Class, Base) 10306 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 10307 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 10308 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 10309 #include "clang/AST/TypeNodes.inc" 10310 llvm_unreachable("Non-canonical and dependent types shouldn't get here"); 10311 10312 case Type::Auto: 10313 case Type::DeducedTemplateSpecialization: 10314 case Type::LValueReference: 10315 case Type::RValueReference: 10316 case Type::MemberPointer: 10317 llvm_unreachable("C++ should never be in mergeTypes"); 10318 10319 case Type::ObjCInterface: 10320 case Type::IncompleteArray: 10321 case Type::VariableArray: 10322 case Type::FunctionProto: 10323 case Type::ExtVector: 10324 llvm_unreachable("Types are eliminated above"); 10325 10326 case Type::Pointer: 10327 { 10328 // Merge two pointer types, while trying to preserve typedef info 10329 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType(); 10330 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType(); 10331 if (Unqualified) { 10332 LHSPointee = LHSPointee.getUnqualifiedType(); 10333 RHSPointee = RHSPointee.getUnqualifiedType(); 10334 } 10335 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false, 10336 Unqualified); 10337 if (ResultType.isNull()) 10338 return {}; 10339 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 10340 return LHS; 10341 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 10342 return RHS; 10343 return getPointerType(ResultType); 10344 } 10345 case Type::BlockPointer: 10346 { 10347 // Merge two block pointer types, while trying to preserve typedef info 10348 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType(); 10349 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType(); 10350 if (Unqualified) { 10351 LHSPointee = LHSPointee.getUnqualifiedType(); 10352 RHSPointee = RHSPointee.getUnqualifiedType(); 10353 } 10354 if (getLangOpts().OpenCL) { 10355 Qualifiers LHSPteeQual = LHSPointee.getQualifiers(); 10356 Qualifiers RHSPteeQual = RHSPointee.getQualifiers(); 10357 // Blocks can't be an expression in a ternary operator (OpenCL v2.0 10358 // 6.12.5) thus the following check is asymmetric. 10359 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual)) 10360 return {}; 10361 LHSPteeQual.removeAddressSpace(); 10362 RHSPteeQual.removeAddressSpace(); 10363 LHSPointee = 10364 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue()); 10365 RHSPointee = 10366 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue()); 10367 } 10368 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer, 10369 Unqualified); 10370 if (ResultType.isNull()) 10371 return {}; 10372 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 10373 return LHS; 10374 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 10375 return RHS; 10376 return getBlockPointerType(ResultType); 10377 } 10378 case Type::Atomic: 10379 { 10380 // Merge two pointer types, while trying to preserve typedef info 10381 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType(); 10382 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType(); 10383 if (Unqualified) { 10384 LHSValue = LHSValue.getUnqualifiedType(); 10385 RHSValue = RHSValue.getUnqualifiedType(); 10386 } 10387 QualType ResultType = mergeTypes(LHSValue, RHSValue, false, 10388 Unqualified); 10389 if (ResultType.isNull()) 10390 return {}; 10391 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType)) 10392 return LHS; 10393 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType)) 10394 return RHS; 10395 return getAtomicType(ResultType); 10396 } 10397 case Type::ConstantArray: 10398 { 10399 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS); 10400 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS); 10401 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize()) 10402 return {}; 10403 10404 QualType LHSElem = getAsArrayType(LHS)->getElementType(); 10405 QualType RHSElem = getAsArrayType(RHS)->getElementType(); 10406 if (Unqualified) { 10407 LHSElem = LHSElem.getUnqualifiedType(); 10408 RHSElem = RHSElem.getUnqualifiedType(); 10409 } 10410 10411 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified); 10412 if (ResultType.isNull()) 10413 return {}; 10414 10415 const VariableArrayType* LVAT = getAsVariableArrayType(LHS); 10416 const VariableArrayType* RVAT = getAsVariableArrayType(RHS); 10417 10418 // If either side is a variable array, and both are complete, check whether 10419 // the current dimension is definite. 10420 if (LVAT || RVAT) { 10421 auto SizeFetch = [this](const VariableArrayType* VAT, 10422 const ConstantArrayType* CAT) 10423 -> std::pair<bool,llvm::APInt> { 10424 if (VAT) { 10425 Optional<llvm::APSInt> TheInt; 10426 Expr *E = VAT->getSizeExpr(); 10427 if (E && (TheInt = E->getIntegerConstantExpr(*this))) 10428 return std::make_pair(true, *TheInt); 10429 return std::make_pair(false, llvm::APSInt()); 10430 } 10431 if (CAT) 10432 return std::make_pair(true, CAT->getSize()); 10433 return std::make_pair(false, llvm::APInt()); 10434 }; 10435 10436 bool HaveLSize, HaveRSize; 10437 llvm::APInt LSize, RSize; 10438 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT); 10439 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT); 10440 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize)) 10441 return {}; // Definite, but unequal, array dimension 10442 } 10443 10444 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 10445 return LHS; 10446 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 10447 return RHS; 10448 if (LCAT) 10449 return getConstantArrayType(ResultType, LCAT->getSize(), 10450 LCAT->getSizeExpr(), 10451 ArrayType::ArraySizeModifier(), 0); 10452 if (RCAT) 10453 return getConstantArrayType(ResultType, RCAT->getSize(), 10454 RCAT->getSizeExpr(), 10455 ArrayType::ArraySizeModifier(), 0); 10456 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 10457 return LHS; 10458 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 10459 return RHS; 10460 if (LVAT) { 10461 // FIXME: This isn't correct! But tricky to implement because 10462 // the array's size has to be the size of LHS, but the type 10463 // has to be different. 10464 return LHS; 10465 } 10466 if (RVAT) { 10467 // FIXME: This isn't correct! But tricky to implement because 10468 // the array's size has to be the size of RHS, but the type 10469 // has to be different. 10470 return RHS; 10471 } 10472 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS; 10473 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS; 10474 return getIncompleteArrayType(ResultType, 10475 ArrayType::ArraySizeModifier(), 0); 10476 } 10477 case Type::FunctionNoProto: 10478 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified); 10479 case Type::Record: 10480 case Type::Enum: 10481 return {}; 10482 case Type::Builtin: 10483 // Only exactly equal builtin types are compatible, which is tested above. 10484 return {}; 10485 case Type::Complex: 10486 // Distinct complex types are incompatible. 10487 return {}; 10488 case Type::Vector: 10489 // FIXME: The merged type should be an ExtVector! 10490 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(), 10491 RHSCan->castAs<VectorType>())) 10492 return LHS; 10493 return {}; 10494 case Type::ConstantMatrix: 10495 if (areCompatMatrixTypes(LHSCan->castAs<ConstantMatrixType>(), 10496 RHSCan->castAs<ConstantMatrixType>())) 10497 return LHS; 10498 return {}; 10499 case Type::ObjCObject: { 10500 // Check if the types are assignment compatible. 10501 // FIXME: This should be type compatibility, e.g. whether 10502 // "LHS x; RHS x;" at global scope is legal. 10503 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectType>(), 10504 RHS->castAs<ObjCObjectType>())) 10505 return LHS; 10506 return {}; 10507 } 10508 case Type::ObjCObjectPointer: 10509 if (OfBlockPointer) { 10510 if (canAssignObjCInterfacesInBlockPointer( 10511 LHS->castAs<ObjCObjectPointerType>(), 10512 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType)) 10513 return LHS; 10514 return {}; 10515 } 10516 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectPointerType>(), 10517 RHS->castAs<ObjCObjectPointerType>())) 10518 return LHS; 10519 return {}; 10520 case Type::Pipe: 10521 assert(LHS != RHS && 10522 "Equivalent pipe types should have already been handled!"); 10523 return {}; 10524 case Type::BitInt: { 10525 // Merge two bit-precise int types, while trying to preserve typedef info. 10526 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned(); 10527 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned(); 10528 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits(); 10529 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits(); 10530 10531 // Like unsigned/int, shouldn't have a type if they don't match. 10532 if (LHSUnsigned != RHSUnsigned) 10533 return {}; 10534 10535 if (LHSBits != RHSBits) 10536 return {}; 10537 return LHS; 10538 } 10539 } 10540 10541 llvm_unreachable("Invalid Type::Class!"); 10542 } 10543 10544 bool ASTContext::mergeExtParameterInfo( 10545 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType, 10546 bool &CanUseFirst, bool &CanUseSecond, 10547 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) { 10548 assert(NewParamInfos.empty() && "param info list not empty"); 10549 CanUseFirst = CanUseSecond = true; 10550 bool FirstHasInfo = FirstFnType->hasExtParameterInfos(); 10551 bool SecondHasInfo = SecondFnType->hasExtParameterInfos(); 10552 10553 // Fast path: if the first type doesn't have ext parameter infos, 10554 // we match if and only if the second type also doesn't have them. 10555 if (!FirstHasInfo && !SecondHasInfo) 10556 return true; 10557 10558 bool NeedParamInfo = false; 10559 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size() 10560 : SecondFnType->getExtParameterInfos().size(); 10561 10562 for (size_t I = 0; I < E; ++I) { 10563 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam; 10564 if (FirstHasInfo) 10565 FirstParam = FirstFnType->getExtParameterInfo(I); 10566 if (SecondHasInfo) 10567 SecondParam = SecondFnType->getExtParameterInfo(I); 10568 10569 // Cannot merge unless everything except the noescape flag matches. 10570 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false)) 10571 return false; 10572 10573 bool FirstNoEscape = FirstParam.isNoEscape(); 10574 bool SecondNoEscape = SecondParam.isNoEscape(); 10575 bool IsNoEscape = FirstNoEscape && SecondNoEscape; 10576 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape)); 10577 if (NewParamInfos.back().getOpaqueValue()) 10578 NeedParamInfo = true; 10579 if (FirstNoEscape != IsNoEscape) 10580 CanUseFirst = false; 10581 if (SecondNoEscape != IsNoEscape) 10582 CanUseSecond = false; 10583 } 10584 10585 if (!NeedParamInfo) 10586 NewParamInfos.clear(); 10587 10588 return true; 10589 } 10590 10591 void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) { 10592 ObjCLayouts[CD] = nullptr; 10593 } 10594 10595 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 10596 /// 'RHS' attributes and returns the merged version; including for function 10597 /// return types. 10598 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) { 10599 QualType LHSCan = getCanonicalType(LHS), 10600 RHSCan = getCanonicalType(RHS); 10601 // If two types are identical, they are compatible. 10602 if (LHSCan == RHSCan) 10603 return LHS; 10604 if (RHSCan->isFunctionType()) { 10605 if (!LHSCan->isFunctionType()) 10606 return {}; 10607 QualType OldReturnType = 10608 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType(); 10609 QualType NewReturnType = 10610 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType(); 10611 QualType ResReturnType = 10612 mergeObjCGCQualifiers(NewReturnType, OldReturnType); 10613 if (ResReturnType.isNull()) 10614 return {}; 10615 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) { 10616 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo(); 10617 // In either case, use OldReturnType to build the new function type. 10618 const auto *F = LHS->castAs<FunctionType>(); 10619 if (const auto *FPT = cast<FunctionProtoType>(F)) { 10620 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10621 EPI.ExtInfo = getFunctionExtInfo(LHS); 10622 QualType ResultType = 10623 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI); 10624 return ResultType; 10625 } 10626 } 10627 return {}; 10628 } 10629 10630 // If the qualifiers are different, the types can still be merged. 10631 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 10632 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 10633 if (LQuals != RQuals) { 10634 // If any of these qualifiers are different, we have a type mismatch. 10635 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 10636 LQuals.getAddressSpace() != RQuals.getAddressSpace()) 10637 return {}; 10638 10639 // Exactly one GC qualifier difference is allowed: __strong is 10640 // okay if the other type has no GC qualifier but is an Objective 10641 // C object pointer (i.e. implicitly strong by default). We fix 10642 // this by pretending that the unqualified type was actually 10643 // qualified __strong. 10644 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 10645 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 10646 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 10647 10648 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 10649 return {}; 10650 10651 if (GC_L == Qualifiers::Strong) 10652 return LHS; 10653 if (GC_R == Qualifiers::Strong) 10654 return RHS; 10655 return {}; 10656 } 10657 10658 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) { 10659 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType(); 10660 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType(); 10661 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT); 10662 if (ResQT == LHSBaseQT) 10663 return LHS; 10664 if (ResQT == RHSBaseQT) 10665 return RHS; 10666 } 10667 return {}; 10668 } 10669 10670 //===----------------------------------------------------------------------===// 10671 // Integer Predicates 10672 //===----------------------------------------------------------------------===// 10673 10674 unsigned ASTContext::getIntWidth(QualType T) const { 10675 if (const auto *ET = T->getAs<EnumType>()) 10676 T = ET->getDecl()->getIntegerType(); 10677 if (T->isBooleanType()) 10678 return 1; 10679 if (const auto *EIT = T->getAs<BitIntType>()) 10680 return EIT->getNumBits(); 10681 // For builtin types, just use the standard type sizing method 10682 return (unsigned)getTypeSize(T); 10683 } 10684 10685 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const { 10686 assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) && 10687 "Unexpected type"); 10688 10689 // Turn <4 x signed int> -> <4 x unsigned int> 10690 if (const auto *VTy = T->getAs<VectorType>()) 10691 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()), 10692 VTy->getNumElements(), VTy->getVectorKind()); 10693 10694 // For _BitInt, return an unsigned _BitInt with same width. 10695 if (const auto *EITy = T->getAs<BitIntType>()) 10696 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits()); 10697 10698 // For enums, get the underlying integer type of the enum, and let the general 10699 // integer type signchanging code handle it. 10700 if (const auto *ETy = T->getAs<EnumType>()) 10701 T = ETy->getDecl()->getIntegerType(); 10702 10703 switch (T->castAs<BuiltinType>()->getKind()) { 10704 case BuiltinType::Char_S: 10705 case BuiltinType::SChar: 10706 return UnsignedCharTy; 10707 case BuiltinType::Short: 10708 return UnsignedShortTy; 10709 case BuiltinType::Int: 10710 return UnsignedIntTy; 10711 case BuiltinType::Long: 10712 return UnsignedLongTy; 10713 case BuiltinType::LongLong: 10714 return UnsignedLongLongTy; 10715 case BuiltinType::Int128: 10716 return UnsignedInt128Ty; 10717 // wchar_t is special. It is either signed or not, but when it's signed, 10718 // there's no matching "unsigned wchar_t". Therefore we return the unsigned 10719 // version of it's underlying type instead. 10720 case BuiltinType::WChar_S: 10721 return getUnsignedWCharType(); 10722 10723 case BuiltinType::ShortAccum: 10724 return UnsignedShortAccumTy; 10725 case BuiltinType::Accum: 10726 return UnsignedAccumTy; 10727 case BuiltinType::LongAccum: 10728 return UnsignedLongAccumTy; 10729 case BuiltinType::SatShortAccum: 10730 return SatUnsignedShortAccumTy; 10731 case BuiltinType::SatAccum: 10732 return SatUnsignedAccumTy; 10733 case BuiltinType::SatLongAccum: 10734 return SatUnsignedLongAccumTy; 10735 case BuiltinType::ShortFract: 10736 return UnsignedShortFractTy; 10737 case BuiltinType::Fract: 10738 return UnsignedFractTy; 10739 case BuiltinType::LongFract: 10740 return UnsignedLongFractTy; 10741 case BuiltinType::SatShortFract: 10742 return SatUnsignedShortFractTy; 10743 case BuiltinType::SatFract: 10744 return SatUnsignedFractTy; 10745 case BuiltinType::SatLongFract: 10746 return SatUnsignedLongFractTy; 10747 default: 10748 llvm_unreachable("Unexpected signed integer or fixed point type"); 10749 } 10750 } 10751 10752 QualType ASTContext::getCorrespondingSignedType(QualType T) const { 10753 assert((T->hasUnsignedIntegerRepresentation() || 10754 T->isUnsignedFixedPointType()) && 10755 "Unexpected type"); 10756 10757 // Turn <4 x unsigned int> -> <4 x signed int> 10758 if (const auto *VTy = T->getAs<VectorType>()) 10759 return getVectorType(getCorrespondingSignedType(VTy->getElementType()), 10760 VTy->getNumElements(), VTy->getVectorKind()); 10761 10762 // For _BitInt, return a signed _BitInt with same width. 10763 if (const auto *EITy = T->getAs<BitIntType>()) 10764 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits()); 10765 10766 // For enums, get the underlying integer type of the enum, and let the general 10767 // integer type signchanging code handle it. 10768 if (const auto *ETy = T->getAs<EnumType>()) 10769 T = ETy->getDecl()->getIntegerType(); 10770 10771 switch (T->castAs<BuiltinType>()->getKind()) { 10772 case BuiltinType::Char_U: 10773 case BuiltinType::UChar: 10774 return SignedCharTy; 10775 case BuiltinType::UShort: 10776 return ShortTy; 10777 case BuiltinType::UInt: 10778 return IntTy; 10779 case BuiltinType::ULong: 10780 return LongTy; 10781 case BuiltinType::ULongLong: 10782 return LongLongTy; 10783 case BuiltinType::UInt128: 10784 return Int128Ty; 10785 // wchar_t is special. It is either unsigned or not, but when it's unsigned, 10786 // there's no matching "signed wchar_t". Therefore we return the signed 10787 // version of it's underlying type instead. 10788 case BuiltinType::WChar_U: 10789 return getSignedWCharType(); 10790 10791 case BuiltinType::UShortAccum: 10792 return ShortAccumTy; 10793 case BuiltinType::UAccum: 10794 return AccumTy; 10795 case BuiltinType::ULongAccum: 10796 return LongAccumTy; 10797 case BuiltinType::SatUShortAccum: 10798 return SatShortAccumTy; 10799 case BuiltinType::SatUAccum: 10800 return SatAccumTy; 10801 case BuiltinType::SatULongAccum: 10802 return SatLongAccumTy; 10803 case BuiltinType::UShortFract: 10804 return ShortFractTy; 10805 case BuiltinType::UFract: 10806 return FractTy; 10807 case BuiltinType::ULongFract: 10808 return LongFractTy; 10809 case BuiltinType::SatUShortFract: 10810 return SatShortFractTy; 10811 case BuiltinType::SatUFract: 10812 return SatFractTy; 10813 case BuiltinType::SatULongFract: 10814 return SatLongFractTy; 10815 default: 10816 llvm_unreachable("Unexpected unsigned integer or fixed point type"); 10817 } 10818 } 10819 10820 ASTMutationListener::~ASTMutationListener() = default; 10821 10822 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD, 10823 QualType ReturnType) {} 10824 10825 //===----------------------------------------------------------------------===// 10826 // Builtin Type Computation 10827 //===----------------------------------------------------------------------===// 10828 10829 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the 10830 /// pointer over the consumed characters. This returns the resultant type. If 10831 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic 10832 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of 10833 /// a vector of "i*". 10834 /// 10835 /// RequiresICE is filled in on return to indicate whether the value is required 10836 /// to be an Integer Constant Expression. 10837 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, 10838 ASTContext::GetBuiltinTypeError &Error, 10839 bool &RequiresICE, 10840 bool AllowTypeModifiers) { 10841 // Modifiers. 10842 int HowLong = 0; 10843 bool Signed = false, Unsigned = false; 10844 RequiresICE = false; 10845 10846 // Read the prefixed modifiers first. 10847 bool Done = false; 10848 #ifndef NDEBUG 10849 bool IsSpecial = false; 10850 #endif 10851 while (!Done) { 10852 switch (*Str++) { 10853 default: Done = true; --Str; break; 10854 case 'I': 10855 RequiresICE = true; 10856 break; 10857 case 'S': 10858 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!"); 10859 assert(!Signed && "Can't use 'S' modifier multiple times!"); 10860 Signed = true; 10861 break; 10862 case 'U': 10863 assert(!Signed && "Can't use both 'S' and 'U' modifiers!"); 10864 assert(!Unsigned && "Can't use 'U' modifier multiple times!"); 10865 Unsigned = true; 10866 break; 10867 case 'L': 10868 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers"); 10869 assert(HowLong <= 2 && "Can't have LLLL modifier"); 10870 ++HowLong; 10871 break; 10872 case 'N': 10873 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise. 10874 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10875 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!"); 10876 #ifndef NDEBUG 10877 IsSpecial = true; 10878 #endif 10879 if (Context.getTargetInfo().getLongWidth() == 32) 10880 ++HowLong; 10881 break; 10882 case 'W': 10883 // This modifier represents int64 type. 10884 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10885 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!"); 10886 #ifndef NDEBUG 10887 IsSpecial = true; 10888 #endif 10889 switch (Context.getTargetInfo().getInt64Type()) { 10890 default: 10891 llvm_unreachable("Unexpected integer type"); 10892 case TargetInfo::SignedLong: 10893 HowLong = 1; 10894 break; 10895 case TargetInfo::SignedLongLong: 10896 HowLong = 2; 10897 break; 10898 } 10899 break; 10900 case 'Z': 10901 // This modifier represents int32 type. 10902 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10903 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!"); 10904 #ifndef NDEBUG 10905 IsSpecial = true; 10906 #endif 10907 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) { 10908 default: 10909 llvm_unreachable("Unexpected integer type"); 10910 case TargetInfo::SignedInt: 10911 HowLong = 0; 10912 break; 10913 case TargetInfo::SignedLong: 10914 HowLong = 1; 10915 break; 10916 case TargetInfo::SignedLongLong: 10917 HowLong = 2; 10918 break; 10919 } 10920 break; 10921 case 'O': 10922 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10923 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!"); 10924 #ifndef NDEBUG 10925 IsSpecial = true; 10926 #endif 10927 if (Context.getLangOpts().OpenCL) 10928 HowLong = 1; 10929 else 10930 HowLong = 2; 10931 break; 10932 } 10933 } 10934 10935 QualType Type; 10936 10937 // Read the base type. 10938 switch (*Str++) { 10939 default: llvm_unreachable("Unknown builtin type letter!"); 10940 case 'x': 10941 assert(HowLong == 0 && !Signed && !Unsigned && 10942 "Bad modifiers used with 'x'!"); 10943 Type = Context.Float16Ty; 10944 break; 10945 case 'y': 10946 assert(HowLong == 0 && !Signed && !Unsigned && 10947 "Bad modifiers used with 'y'!"); 10948 Type = Context.BFloat16Ty; 10949 break; 10950 case 'v': 10951 assert(HowLong == 0 && !Signed && !Unsigned && 10952 "Bad modifiers used with 'v'!"); 10953 Type = Context.VoidTy; 10954 break; 10955 case 'h': 10956 assert(HowLong == 0 && !Signed && !Unsigned && 10957 "Bad modifiers used with 'h'!"); 10958 Type = Context.HalfTy; 10959 break; 10960 case 'f': 10961 assert(HowLong == 0 && !Signed && !Unsigned && 10962 "Bad modifiers used with 'f'!"); 10963 Type = Context.FloatTy; 10964 break; 10965 case 'd': 10966 assert(HowLong < 3 && !Signed && !Unsigned && 10967 "Bad modifiers used with 'd'!"); 10968 if (HowLong == 1) 10969 Type = Context.LongDoubleTy; 10970 else if (HowLong == 2) 10971 Type = Context.Float128Ty; 10972 else 10973 Type = Context.DoubleTy; 10974 break; 10975 case 's': 10976 assert(HowLong == 0 && "Bad modifiers used with 's'!"); 10977 if (Unsigned) 10978 Type = Context.UnsignedShortTy; 10979 else 10980 Type = Context.ShortTy; 10981 break; 10982 case 'i': 10983 if (HowLong == 3) 10984 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty; 10985 else if (HowLong == 2) 10986 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy; 10987 else if (HowLong == 1) 10988 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy; 10989 else 10990 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy; 10991 break; 10992 case 'c': 10993 assert(HowLong == 0 && "Bad modifiers used with 'c'!"); 10994 if (Signed) 10995 Type = Context.SignedCharTy; 10996 else if (Unsigned) 10997 Type = Context.UnsignedCharTy; 10998 else 10999 Type = Context.CharTy; 11000 break; 11001 case 'b': // boolean 11002 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!"); 11003 Type = Context.BoolTy; 11004 break; 11005 case 'z': // size_t. 11006 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!"); 11007 Type = Context.getSizeType(); 11008 break; 11009 case 'w': // wchar_t. 11010 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!"); 11011 Type = Context.getWideCharType(); 11012 break; 11013 case 'F': 11014 Type = Context.getCFConstantStringType(); 11015 break; 11016 case 'G': 11017 Type = Context.getObjCIdType(); 11018 break; 11019 case 'H': 11020 Type = Context.getObjCSelType(); 11021 break; 11022 case 'M': 11023 Type = Context.getObjCSuperType(); 11024 break; 11025 case 'a': 11026 Type = Context.getBuiltinVaListType(); 11027 assert(!Type.isNull() && "builtin va list type not initialized!"); 11028 break; 11029 case 'A': 11030 // This is a "reference" to a va_list; however, what exactly 11031 // this means depends on how va_list is defined. There are two 11032 // different kinds of va_list: ones passed by value, and ones 11033 // passed by reference. An example of a by-value va_list is 11034 // x86, where va_list is a char*. An example of by-ref va_list 11035 // is x86-64, where va_list is a __va_list_tag[1]. For x86, 11036 // we want this argument to be a char*&; for x86-64, we want 11037 // it to be a __va_list_tag*. 11038 Type = Context.getBuiltinVaListType(); 11039 assert(!Type.isNull() && "builtin va list type not initialized!"); 11040 if (Type->isArrayType()) 11041 Type = Context.getArrayDecayedType(Type); 11042 else 11043 Type = Context.getLValueReferenceType(Type); 11044 break; 11045 case 'q': { 11046 char *End; 11047 unsigned NumElements = strtoul(Str, &End, 10); 11048 assert(End != Str && "Missing vector size"); 11049 Str = End; 11050 11051 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 11052 RequiresICE, false); 11053 assert(!RequiresICE && "Can't require vector ICE"); 11054 11055 Type = Context.getScalableVectorType(ElementType, NumElements); 11056 break; 11057 } 11058 case 'V': { 11059 char *End; 11060 unsigned NumElements = strtoul(Str, &End, 10); 11061 assert(End != Str && "Missing vector size"); 11062 Str = End; 11063 11064 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 11065 RequiresICE, false); 11066 assert(!RequiresICE && "Can't require vector ICE"); 11067 11068 // TODO: No way to make AltiVec vectors in builtins yet. 11069 Type = Context.getVectorType(ElementType, NumElements, 11070 VectorType::GenericVector); 11071 break; 11072 } 11073 case 'E': { 11074 char *End; 11075 11076 unsigned NumElements = strtoul(Str, &End, 10); 11077 assert(End != Str && "Missing vector size"); 11078 11079 Str = End; 11080 11081 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 11082 false); 11083 Type = Context.getExtVectorType(ElementType, NumElements); 11084 break; 11085 } 11086 case 'X': { 11087 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 11088 false); 11089 assert(!RequiresICE && "Can't require complex ICE"); 11090 Type = Context.getComplexType(ElementType); 11091 break; 11092 } 11093 case 'Y': 11094 Type = Context.getPointerDiffType(); 11095 break; 11096 case 'P': 11097 Type = Context.getFILEType(); 11098 if (Type.isNull()) { 11099 Error = ASTContext::GE_Missing_stdio; 11100 return {}; 11101 } 11102 break; 11103 case 'J': 11104 if (Signed) 11105 Type = Context.getsigjmp_bufType(); 11106 else 11107 Type = Context.getjmp_bufType(); 11108 11109 if (Type.isNull()) { 11110 Error = ASTContext::GE_Missing_setjmp; 11111 return {}; 11112 } 11113 break; 11114 case 'K': 11115 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!"); 11116 Type = Context.getucontext_tType(); 11117 11118 if (Type.isNull()) { 11119 Error = ASTContext::GE_Missing_ucontext; 11120 return {}; 11121 } 11122 break; 11123 case 'p': 11124 Type = Context.getProcessIDType(); 11125 break; 11126 } 11127 11128 // If there are modifiers and if we're allowed to parse them, go for it. 11129 Done = !AllowTypeModifiers; 11130 while (!Done) { 11131 switch (char c = *Str++) { 11132 default: Done = true; --Str; break; 11133 case '*': 11134 case '&': { 11135 // Both pointers and references can have their pointee types 11136 // qualified with an address space. 11137 char *End; 11138 unsigned AddrSpace = strtoul(Str, &End, 10); 11139 if (End != Str) { 11140 // Note AddrSpace == 0 is not the same as an unspecified address space. 11141 Type = Context.getAddrSpaceQualType( 11142 Type, 11143 Context.getLangASForBuiltinAddressSpace(AddrSpace)); 11144 Str = End; 11145 } 11146 if (c == '*') 11147 Type = Context.getPointerType(Type); 11148 else 11149 Type = Context.getLValueReferenceType(Type); 11150 break; 11151 } 11152 // FIXME: There's no way to have a built-in with an rvalue ref arg. 11153 case 'C': 11154 Type = Type.withConst(); 11155 break; 11156 case 'D': 11157 Type = Context.getVolatileType(Type); 11158 break; 11159 case 'R': 11160 Type = Type.withRestrict(); 11161 break; 11162 } 11163 } 11164 11165 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) && 11166 "Integer constant 'I' type must be an integer"); 11167 11168 return Type; 11169 } 11170 11171 // On some targets such as PowerPC, some of the builtins are defined with custom 11172 // type descriptors for target-dependent types. These descriptors are decoded in 11173 // other functions, but it may be useful to be able to fall back to default 11174 // descriptor decoding to define builtins mixing target-dependent and target- 11175 // independent types. This function allows decoding one type descriptor with 11176 // default decoding. 11177 QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context, 11178 GetBuiltinTypeError &Error, bool &RequireICE, 11179 bool AllowTypeModifiers) const { 11180 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers); 11181 } 11182 11183 /// GetBuiltinType - Return the type for the specified builtin. 11184 QualType ASTContext::GetBuiltinType(unsigned Id, 11185 GetBuiltinTypeError &Error, 11186 unsigned *IntegerConstantArgs) const { 11187 const char *TypeStr = BuiltinInfo.getTypeString(Id); 11188 if (TypeStr[0] == '\0') { 11189 Error = GE_Missing_type; 11190 return {}; 11191 } 11192 11193 SmallVector<QualType, 8> ArgTypes; 11194 11195 bool RequiresICE = false; 11196 Error = GE_None; 11197 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error, 11198 RequiresICE, true); 11199 if (Error != GE_None) 11200 return {}; 11201 11202 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE"); 11203 11204 while (TypeStr[0] && TypeStr[0] != '.') { 11205 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true); 11206 if (Error != GE_None) 11207 return {}; 11208 11209 // If this argument is required to be an IntegerConstantExpression and the 11210 // caller cares, fill in the bitmask we return. 11211 if (RequiresICE && IntegerConstantArgs) 11212 *IntegerConstantArgs |= 1 << ArgTypes.size(); 11213 11214 // Do array -> pointer decay. The builtin should use the decayed type. 11215 if (Ty->isArrayType()) 11216 Ty = getArrayDecayedType(Ty); 11217 11218 ArgTypes.push_back(Ty); 11219 } 11220 11221 if (Id == Builtin::BI__GetExceptionInfo) 11222 return {}; 11223 11224 assert((TypeStr[0] != '.' || TypeStr[1] == 0) && 11225 "'.' should only occur at end of builtin type list!"); 11226 11227 bool Variadic = (TypeStr[0] == '.'); 11228 11229 FunctionType::ExtInfo EI(getDefaultCallingConvention( 11230 Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true)); 11231 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true); 11232 11233 11234 // We really shouldn't be making a no-proto type here. 11235 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus) 11236 return getFunctionNoProtoType(ResType, EI); 11237 11238 FunctionProtoType::ExtProtoInfo EPI; 11239 EPI.ExtInfo = EI; 11240 EPI.Variadic = Variadic; 11241 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id)) 11242 EPI.ExceptionSpec.Type = 11243 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone; 11244 11245 return getFunctionType(ResType, ArgTypes, EPI); 11246 } 11247 11248 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, 11249 const FunctionDecl *FD) { 11250 if (!FD->isExternallyVisible()) 11251 return GVA_Internal; 11252 11253 // Non-user-provided functions get emitted as weak definitions with every 11254 // use, no matter whether they've been explicitly instantiated etc. 11255 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 11256 if (!MD->isUserProvided()) 11257 return GVA_DiscardableODR; 11258 11259 GVALinkage External; 11260 switch (FD->getTemplateSpecializationKind()) { 11261 case TSK_Undeclared: 11262 case TSK_ExplicitSpecialization: 11263 External = GVA_StrongExternal; 11264 break; 11265 11266 case TSK_ExplicitInstantiationDefinition: 11267 return GVA_StrongODR; 11268 11269 // C++11 [temp.explicit]p10: 11270 // [ Note: The intent is that an inline function that is the subject of 11271 // an explicit instantiation declaration will still be implicitly 11272 // instantiated when used so that the body can be considered for 11273 // inlining, but that no out-of-line copy of the inline function would be 11274 // generated in the translation unit. -- end note ] 11275 case TSK_ExplicitInstantiationDeclaration: 11276 return GVA_AvailableExternally; 11277 11278 case TSK_ImplicitInstantiation: 11279 External = GVA_DiscardableODR; 11280 break; 11281 } 11282 11283 if (!FD->isInlined()) 11284 return External; 11285 11286 if ((!Context.getLangOpts().CPlusPlus && 11287 !Context.getTargetInfo().getCXXABI().isMicrosoft() && 11288 !FD->hasAttr<DLLExportAttr>()) || 11289 FD->hasAttr<GNUInlineAttr>()) { 11290 // FIXME: This doesn't match gcc's behavior for dllexport inline functions. 11291 11292 // GNU or C99 inline semantics. Determine whether this symbol should be 11293 // externally visible. 11294 if (FD->isInlineDefinitionExternallyVisible()) 11295 return External; 11296 11297 // C99 inline semantics, where the symbol is not externally visible. 11298 return GVA_AvailableExternally; 11299 } 11300 11301 // Functions specified with extern and inline in -fms-compatibility mode 11302 // forcibly get emitted. While the body of the function cannot be later 11303 // replaced, the function definition cannot be discarded. 11304 if (FD->isMSExternInline()) 11305 return GVA_StrongODR; 11306 11307 return GVA_DiscardableODR; 11308 } 11309 11310 static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context, 11311 const Decl *D, GVALinkage L) { 11312 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx 11313 // dllexport/dllimport on inline functions. 11314 if (D->hasAttr<DLLImportAttr>()) { 11315 if (L == GVA_DiscardableODR || L == GVA_StrongODR) 11316 return GVA_AvailableExternally; 11317 } else if (D->hasAttr<DLLExportAttr>()) { 11318 if (L == GVA_DiscardableODR) 11319 return GVA_StrongODR; 11320 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) { 11321 // Device-side functions with __global__ attribute must always be 11322 // visible externally so they can be launched from host. 11323 if (D->hasAttr<CUDAGlobalAttr>() && 11324 (L == GVA_DiscardableODR || L == GVA_Internal)) 11325 return GVA_StrongODR; 11326 // Single source offloading languages like CUDA/HIP need to be able to 11327 // access static device variables from host code of the same compilation 11328 // unit. This is done by externalizing the static variable with a shared 11329 // name between the host and device compilation which is the same for the 11330 // same compilation unit whereas different among different compilation 11331 // units. 11332 if (Context.shouldExternalizeStaticVar(D)) 11333 return GVA_StrongExternal; 11334 } 11335 return L; 11336 } 11337 11338 /// Adjust the GVALinkage for a declaration based on what an external AST source 11339 /// knows about whether there can be other definitions of this declaration. 11340 static GVALinkage 11341 adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D, 11342 GVALinkage L) { 11343 ExternalASTSource *Source = Ctx.getExternalSource(); 11344 if (!Source) 11345 return L; 11346 11347 switch (Source->hasExternalDefinitions(D)) { 11348 case ExternalASTSource::EK_Never: 11349 // Other translation units rely on us to provide the definition. 11350 if (L == GVA_DiscardableODR) 11351 return GVA_StrongODR; 11352 break; 11353 11354 case ExternalASTSource::EK_Always: 11355 return GVA_AvailableExternally; 11356 11357 case ExternalASTSource::EK_ReplyHazy: 11358 break; 11359 } 11360 return L; 11361 } 11362 11363 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const { 11364 return adjustGVALinkageForExternalDefinitionKind(*this, FD, 11365 adjustGVALinkageForAttributes(*this, FD, 11366 basicGVALinkageForFunction(*this, FD))); 11367 } 11368 11369 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context, 11370 const VarDecl *VD) { 11371 if (!VD->isExternallyVisible()) 11372 return GVA_Internal; 11373 11374 if (VD->isStaticLocal()) { 11375 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod(); 11376 while (LexicalContext && !isa<FunctionDecl>(LexicalContext)) 11377 LexicalContext = LexicalContext->getLexicalParent(); 11378 11379 // ObjC Blocks can create local variables that don't have a FunctionDecl 11380 // LexicalContext. 11381 if (!LexicalContext) 11382 return GVA_DiscardableODR; 11383 11384 // Otherwise, let the static local variable inherit its linkage from the 11385 // nearest enclosing function. 11386 auto StaticLocalLinkage = 11387 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext)); 11388 11389 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must 11390 // be emitted in any object with references to the symbol for the object it 11391 // contains, whether inline or out-of-line." 11392 // Similar behavior is observed with MSVC. An alternative ABI could use 11393 // StrongODR/AvailableExternally to match the function, but none are 11394 // known/supported currently. 11395 if (StaticLocalLinkage == GVA_StrongODR || 11396 StaticLocalLinkage == GVA_AvailableExternally) 11397 return GVA_DiscardableODR; 11398 return StaticLocalLinkage; 11399 } 11400 11401 // MSVC treats in-class initialized static data members as definitions. 11402 // By giving them non-strong linkage, out-of-line definitions won't 11403 // cause link errors. 11404 if (Context.isMSStaticDataMemberInlineDefinition(VD)) 11405 return GVA_DiscardableODR; 11406 11407 // Most non-template variables have strong linkage; inline variables are 11408 // linkonce_odr or (occasionally, for compatibility) weak_odr. 11409 GVALinkage StrongLinkage; 11410 switch (Context.getInlineVariableDefinitionKind(VD)) { 11411 case ASTContext::InlineVariableDefinitionKind::None: 11412 StrongLinkage = GVA_StrongExternal; 11413 break; 11414 case ASTContext::InlineVariableDefinitionKind::Weak: 11415 case ASTContext::InlineVariableDefinitionKind::WeakUnknown: 11416 StrongLinkage = GVA_DiscardableODR; 11417 break; 11418 case ASTContext::InlineVariableDefinitionKind::Strong: 11419 StrongLinkage = GVA_StrongODR; 11420 break; 11421 } 11422 11423 switch (VD->getTemplateSpecializationKind()) { 11424 case TSK_Undeclared: 11425 return StrongLinkage; 11426 11427 case TSK_ExplicitSpecialization: 11428 return Context.getTargetInfo().getCXXABI().isMicrosoft() && 11429 VD->isStaticDataMember() 11430 ? GVA_StrongODR 11431 : StrongLinkage; 11432 11433 case TSK_ExplicitInstantiationDefinition: 11434 return GVA_StrongODR; 11435 11436 case TSK_ExplicitInstantiationDeclaration: 11437 return GVA_AvailableExternally; 11438 11439 case TSK_ImplicitInstantiation: 11440 return GVA_DiscardableODR; 11441 } 11442 11443 llvm_unreachable("Invalid Linkage!"); 11444 } 11445 11446 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) { 11447 return adjustGVALinkageForExternalDefinitionKind(*this, VD, 11448 adjustGVALinkageForAttributes(*this, VD, 11449 basicGVALinkageForVariable(*this, VD))); 11450 } 11451 11452 bool ASTContext::DeclMustBeEmitted(const Decl *D) { 11453 if (const auto *VD = dyn_cast<VarDecl>(D)) { 11454 if (!VD->isFileVarDecl()) 11455 return false; 11456 // Global named register variables (GNU extension) are never emitted. 11457 if (VD->getStorageClass() == SC_Register) 11458 return false; 11459 if (VD->getDescribedVarTemplate() || 11460 isa<VarTemplatePartialSpecializationDecl>(VD)) 11461 return false; 11462 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 11463 // We never need to emit an uninstantiated function template. 11464 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 11465 return false; 11466 } else if (isa<PragmaCommentDecl>(D)) 11467 return true; 11468 else if (isa<PragmaDetectMismatchDecl>(D)) 11469 return true; 11470 else if (isa<OMPRequiresDecl>(D)) 11471 return true; 11472 else if (isa<OMPThreadPrivateDecl>(D)) 11473 return !D->getDeclContext()->isDependentContext(); 11474 else if (isa<OMPAllocateDecl>(D)) 11475 return !D->getDeclContext()->isDependentContext(); 11476 else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D)) 11477 return !D->getDeclContext()->isDependentContext(); 11478 else if (isa<ImportDecl>(D)) 11479 return true; 11480 else 11481 return false; 11482 11483 // If this is a member of a class template, we do not need to emit it. 11484 if (D->getDeclContext()->isDependentContext()) 11485 return false; 11486 11487 // Weak references don't produce any output by themselves. 11488 if (D->hasAttr<WeakRefAttr>()) 11489 return false; 11490 11491 // Aliases and used decls are required. 11492 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>()) 11493 return true; 11494 11495 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 11496 // Forward declarations aren't required. 11497 if (!FD->doesThisDeclarationHaveABody()) 11498 return FD->doesDeclarationForceExternallyVisibleDefinition(); 11499 11500 // Constructors and destructors are required. 11501 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>()) 11502 return true; 11503 11504 // The key function for a class is required. This rule only comes 11505 // into play when inline functions can be key functions, though. 11506 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 11507 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 11508 const CXXRecordDecl *RD = MD->getParent(); 11509 if (MD->isOutOfLine() && RD->isDynamicClass()) { 11510 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD); 11511 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl()) 11512 return true; 11513 } 11514 } 11515 } 11516 11517 GVALinkage Linkage = GetGVALinkageForFunction(FD); 11518 11519 // static, static inline, always_inline, and extern inline functions can 11520 // always be deferred. Normal inline functions can be deferred in C99/C++. 11521 // Implicit template instantiations can also be deferred in C++. 11522 return !isDiscardableGVALinkage(Linkage); 11523 } 11524 11525 const auto *VD = cast<VarDecl>(D); 11526 assert(VD->isFileVarDecl() && "Expected file scoped var"); 11527 11528 // If the decl is marked as `declare target to`, it should be emitted for the 11529 // host and for the device. 11530 if (LangOpts.OpenMP && 11531 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 11532 return true; 11533 11534 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly && 11535 !isMSStaticDataMemberInlineDefinition(VD)) 11536 return false; 11537 11538 // Variables that can be needed in other TUs are required. 11539 auto Linkage = GetGVALinkageForVariable(VD); 11540 if (!isDiscardableGVALinkage(Linkage)) 11541 return true; 11542 11543 // We never need to emit a variable that is available in another TU. 11544 if (Linkage == GVA_AvailableExternally) 11545 return false; 11546 11547 // Variables that have destruction with side-effects are required. 11548 if (VD->needsDestruction(*this)) 11549 return true; 11550 11551 // Variables that have initialization with side-effects are required. 11552 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) && 11553 // We can get a value-dependent initializer during error recovery. 11554 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 11555 return true; 11556 11557 // Likewise, variables with tuple-like bindings are required if their 11558 // bindings have side-effects. 11559 if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) 11560 for (const auto *BD : DD->bindings()) 11561 if (const auto *BindingVD = BD->getHoldingVar()) 11562 if (DeclMustBeEmitted(BindingVD)) 11563 return true; 11564 11565 return false; 11566 } 11567 11568 void ASTContext::forEachMultiversionedFunctionVersion( 11569 const FunctionDecl *FD, 11570 llvm::function_ref<void(FunctionDecl *)> Pred) const { 11571 assert(FD->isMultiVersion() && "Only valid for multiversioned functions"); 11572 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls; 11573 FD = FD->getMostRecentDecl(); 11574 // FIXME: The order of traversal here matters and depends on the order of 11575 // lookup results, which happens to be (mostly) oldest-to-newest, but we 11576 // shouldn't rely on that. 11577 for (auto *CurDecl : 11578 FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) { 11579 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl(); 11580 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) && 11581 std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) { 11582 SeenDecls.insert(CurFD); 11583 Pred(CurFD); 11584 } 11585 } 11586 } 11587 11588 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic, 11589 bool IsCXXMethod, 11590 bool IsBuiltin) const { 11591 // Pass through to the C++ ABI object 11592 if (IsCXXMethod) 11593 return ABI->getDefaultMethodCallConv(IsVariadic); 11594 11595 // Builtins ignore user-specified default calling convention and remain the 11596 // Target's default calling convention. 11597 if (!IsBuiltin) { 11598 switch (LangOpts.getDefaultCallingConv()) { 11599 case LangOptions::DCC_None: 11600 break; 11601 case LangOptions::DCC_CDecl: 11602 return CC_C; 11603 case LangOptions::DCC_FastCall: 11604 if (getTargetInfo().hasFeature("sse2") && !IsVariadic) 11605 return CC_X86FastCall; 11606 break; 11607 case LangOptions::DCC_StdCall: 11608 if (!IsVariadic) 11609 return CC_X86StdCall; 11610 break; 11611 case LangOptions::DCC_VectorCall: 11612 // __vectorcall cannot be applied to variadic functions. 11613 if (!IsVariadic) 11614 return CC_X86VectorCall; 11615 break; 11616 case LangOptions::DCC_RegCall: 11617 // __regcall cannot be applied to variadic functions. 11618 if (!IsVariadic) 11619 return CC_X86RegCall; 11620 break; 11621 } 11622 } 11623 return Target->getDefaultCallingConv(); 11624 } 11625 11626 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const { 11627 // Pass through to the C++ ABI object 11628 return ABI->isNearlyEmpty(RD); 11629 } 11630 11631 VTableContextBase *ASTContext::getVTableContext() { 11632 if (!VTContext.get()) { 11633 auto ABI = Target->getCXXABI(); 11634 if (ABI.isMicrosoft()) 11635 VTContext.reset(new MicrosoftVTableContext(*this)); 11636 else { 11637 auto ComponentLayout = getLangOpts().RelativeCXXABIVTables 11638 ? ItaniumVTableContext::Relative 11639 : ItaniumVTableContext::Pointer; 11640 VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout)); 11641 } 11642 } 11643 return VTContext.get(); 11644 } 11645 11646 MangleContext *ASTContext::createMangleContext(const TargetInfo *T) { 11647 if (!T) 11648 T = Target; 11649 switch (T->getCXXABI().getKind()) { 11650 case TargetCXXABI::AppleARM64: 11651 case TargetCXXABI::Fuchsia: 11652 case TargetCXXABI::GenericAArch64: 11653 case TargetCXXABI::GenericItanium: 11654 case TargetCXXABI::GenericARM: 11655 case TargetCXXABI::GenericMIPS: 11656 case TargetCXXABI::iOS: 11657 case TargetCXXABI::WebAssembly: 11658 case TargetCXXABI::WatchOS: 11659 case TargetCXXABI::XL: 11660 return ItaniumMangleContext::create(*this, getDiagnostics()); 11661 case TargetCXXABI::Microsoft: 11662 return MicrosoftMangleContext::create(*this, getDiagnostics()); 11663 } 11664 llvm_unreachable("Unsupported ABI"); 11665 } 11666 11667 MangleContext *ASTContext::createDeviceMangleContext(const TargetInfo &T) { 11668 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft && 11669 "Device mangle context does not support Microsoft mangling."); 11670 switch (T.getCXXABI().getKind()) { 11671 case TargetCXXABI::AppleARM64: 11672 case TargetCXXABI::Fuchsia: 11673 case TargetCXXABI::GenericAArch64: 11674 case TargetCXXABI::GenericItanium: 11675 case TargetCXXABI::GenericARM: 11676 case TargetCXXABI::GenericMIPS: 11677 case TargetCXXABI::iOS: 11678 case TargetCXXABI::WebAssembly: 11679 case TargetCXXABI::WatchOS: 11680 case TargetCXXABI::XL: 11681 return ItaniumMangleContext::create( 11682 *this, getDiagnostics(), 11683 [](ASTContext &, const NamedDecl *ND) -> llvm::Optional<unsigned> { 11684 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) 11685 return RD->getDeviceLambdaManglingNumber(); 11686 return llvm::None; 11687 }); 11688 case TargetCXXABI::Microsoft: 11689 return MicrosoftMangleContext::create(*this, getDiagnostics()); 11690 } 11691 llvm_unreachable("Unsupported ABI"); 11692 } 11693 11694 CXXABI::~CXXABI() = default; 11695 11696 size_t ASTContext::getSideTableAllocatedMemory() const { 11697 return ASTRecordLayouts.getMemorySize() + 11698 llvm::capacity_in_bytes(ObjCLayouts) + 11699 llvm::capacity_in_bytes(KeyFunctions) + 11700 llvm::capacity_in_bytes(ObjCImpls) + 11701 llvm::capacity_in_bytes(BlockVarCopyInits) + 11702 llvm::capacity_in_bytes(DeclAttrs) + 11703 llvm::capacity_in_bytes(TemplateOrInstantiation) + 11704 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) + 11705 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) + 11706 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) + 11707 llvm::capacity_in_bytes(OverriddenMethods) + 11708 llvm::capacity_in_bytes(Types) + 11709 llvm::capacity_in_bytes(VariableArrayTypes); 11710 } 11711 11712 /// getIntTypeForBitwidth - 11713 /// sets integer QualTy according to specified details: 11714 /// bitwidth, signed/unsigned. 11715 /// Returns empty type if there is no appropriate target types. 11716 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth, 11717 unsigned Signed) const { 11718 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed); 11719 CanQualType QualTy = getFromTargetType(Ty); 11720 if (!QualTy && DestWidth == 128) 11721 return Signed ? Int128Ty : UnsignedInt128Ty; 11722 return QualTy; 11723 } 11724 11725 /// getRealTypeForBitwidth - 11726 /// sets floating point QualTy according to specified bitwidth. 11727 /// Returns empty type if there is no appropriate target types. 11728 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth, 11729 FloatModeKind ExplicitType) const { 11730 FloatModeKind Ty = 11731 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType); 11732 switch (Ty) { 11733 case FloatModeKind::Float: 11734 return FloatTy; 11735 case FloatModeKind::Double: 11736 return DoubleTy; 11737 case FloatModeKind::LongDouble: 11738 return LongDoubleTy; 11739 case FloatModeKind::Float128: 11740 return Float128Ty; 11741 case FloatModeKind::Ibm128: 11742 return Ibm128Ty; 11743 case FloatModeKind::NoFloat: 11744 return {}; 11745 } 11746 11747 llvm_unreachable("Unhandled TargetInfo::RealType value"); 11748 } 11749 11750 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) { 11751 if (Number > 1) 11752 MangleNumbers[ND] = Number; 11753 } 11754 11755 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const { 11756 auto I = MangleNumbers.find(ND); 11757 return I != MangleNumbers.end() ? I->second : 1; 11758 } 11759 11760 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) { 11761 if (Number > 1) 11762 StaticLocalNumbers[VD] = Number; 11763 } 11764 11765 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const { 11766 auto I = StaticLocalNumbers.find(VD); 11767 return I != StaticLocalNumbers.end() ? I->second : 1; 11768 } 11769 11770 MangleNumberingContext & 11771 ASTContext::getManglingNumberContext(const DeclContext *DC) { 11772 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C. 11773 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC]; 11774 if (!MCtx) 11775 MCtx = createMangleNumberingContext(); 11776 return *MCtx; 11777 } 11778 11779 MangleNumberingContext & 11780 ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) { 11781 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C. 11782 std::unique_ptr<MangleNumberingContext> &MCtx = 11783 ExtraMangleNumberingContexts[D]; 11784 if (!MCtx) 11785 MCtx = createMangleNumberingContext(); 11786 return *MCtx; 11787 } 11788 11789 std::unique_ptr<MangleNumberingContext> 11790 ASTContext::createMangleNumberingContext() const { 11791 return ABI->createMangleNumberingContext(); 11792 } 11793 11794 const CXXConstructorDecl * 11795 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) { 11796 return ABI->getCopyConstructorForExceptionObject( 11797 cast<CXXRecordDecl>(RD->getFirstDecl())); 11798 } 11799 11800 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD, 11801 CXXConstructorDecl *CD) { 11802 return ABI->addCopyConstructorForExceptionObject( 11803 cast<CXXRecordDecl>(RD->getFirstDecl()), 11804 cast<CXXConstructorDecl>(CD->getFirstDecl())); 11805 } 11806 11807 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD, 11808 TypedefNameDecl *DD) { 11809 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD); 11810 } 11811 11812 TypedefNameDecl * 11813 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) { 11814 return ABI->getTypedefNameForUnnamedTagDecl(TD); 11815 } 11816 11817 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD, 11818 DeclaratorDecl *DD) { 11819 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD); 11820 } 11821 11822 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) { 11823 return ABI->getDeclaratorForUnnamedTagDecl(TD); 11824 } 11825 11826 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) { 11827 ParamIndices[D] = index; 11828 } 11829 11830 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const { 11831 ParameterIndexTable::const_iterator I = ParamIndices.find(D); 11832 assert(I != ParamIndices.end() && 11833 "ParmIndices lacks entry set by ParmVarDecl"); 11834 return I->second; 11835 } 11836 11837 QualType ASTContext::getStringLiteralArrayType(QualType EltTy, 11838 unsigned Length) const { 11839 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 11840 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 11841 EltTy = EltTy.withConst(); 11842 11843 EltTy = adjustStringLiteralBaseType(EltTy); 11844 11845 // Get an array type for the string, according to C99 6.4.5. This includes 11846 // the null terminator character. 11847 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr, 11848 ArrayType::Normal, /*IndexTypeQuals*/ 0); 11849 } 11850 11851 StringLiteral * 11852 ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const { 11853 StringLiteral *&Result = StringLiteralCache[Key]; 11854 if (!Result) 11855 Result = StringLiteral::Create( 11856 *this, Key, StringLiteral::Ascii, 11857 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()), 11858 SourceLocation()); 11859 return Result; 11860 } 11861 11862 MSGuidDecl * 11863 ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const { 11864 assert(MSGuidTagDecl && "building MS GUID without MS extensions?"); 11865 11866 llvm::FoldingSetNodeID ID; 11867 MSGuidDecl::Profile(ID, Parts); 11868 11869 void *InsertPos; 11870 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos)) 11871 return Existing; 11872 11873 QualType GUIDType = getMSGuidType().withConst(); 11874 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts); 11875 MSGuidDecls.InsertNode(New, InsertPos); 11876 return New; 11877 } 11878 11879 TemplateParamObjectDecl * 11880 ASTContext::getTemplateParamObjectDecl(QualType T, const APValue &V) const { 11881 assert(T->isRecordType() && "template param object of unexpected type"); 11882 11883 // C++ [temp.param]p8: 11884 // [...] a static storage duration object of type 'const T' [...] 11885 T.addConst(); 11886 11887 llvm::FoldingSetNodeID ID; 11888 TemplateParamObjectDecl::Profile(ID, T, V); 11889 11890 void *InsertPos; 11891 if (TemplateParamObjectDecl *Existing = 11892 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos)) 11893 return Existing; 11894 11895 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V); 11896 TemplateParamObjectDecls.InsertNode(New, InsertPos); 11897 return New; 11898 } 11899 11900 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const { 11901 const llvm::Triple &T = getTargetInfo().getTriple(); 11902 if (!T.isOSDarwin()) 11903 return false; 11904 11905 if (!(T.isiOS() && T.isOSVersionLT(7)) && 11906 !(T.isMacOSX() && T.isOSVersionLT(10, 9))) 11907 return false; 11908 11909 QualType AtomicTy = E->getPtr()->getType()->getPointeeType(); 11910 CharUnits sizeChars = getTypeSizeInChars(AtomicTy); 11911 uint64_t Size = sizeChars.getQuantity(); 11912 CharUnits alignChars = getTypeAlignInChars(AtomicTy); 11913 unsigned Align = alignChars.getQuantity(); 11914 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth(); 11915 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits); 11916 } 11917 11918 bool 11919 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, 11920 const ObjCMethodDecl *MethodImpl) { 11921 // No point trying to match an unavailable/deprecated mothod. 11922 if (MethodDecl->hasAttr<UnavailableAttr>() 11923 || MethodDecl->hasAttr<DeprecatedAttr>()) 11924 return false; 11925 if (MethodDecl->getObjCDeclQualifier() != 11926 MethodImpl->getObjCDeclQualifier()) 11927 return false; 11928 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType())) 11929 return false; 11930 11931 if (MethodDecl->param_size() != MethodImpl->param_size()) 11932 return false; 11933 11934 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(), 11935 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(), 11936 EF = MethodDecl->param_end(); 11937 IM != EM && IF != EF; ++IM, ++IF) { 11938 const ParmVarDecl *DeclVar = (*IF); 11939 const ParmVarDecl *ImplVar = (*IM); 11940 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier()) 11941 return false; 11942 if (!hasSameType(DeclVar->getType(), ImplVar->getType())) 11943 return false; 11944 } 11945 11946 return (MethodDecl->isVariadic() == MethodImpl->isVariadic()); 11947 } 11948 11949 uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const { 11950 LangAS AS; 11951 if (QT->getUnqualifiedDesugaredType()->isNullPtrType()) 11952 AS = LangAS::Default; 11953 else 11954 AS = QT->getPointeeType().getAddressSpace(); 11955 11956 return getTargetInfo().getNullPointerValue(AS); 11957 } 11958 11959 unsigned ASTContext::getTargetAddressSpace(QualType T) const { 11960 // Return the address space for the type. If the type is a 11961 // function type without an address space qualifier, the 11962 // program address space is used. Otherwise, the target picks 11963 // the best address space based on the type information 11964 return T->isFunctionType() && !T.hasAddressSpace() 11965 ? getTargetInfo().getProgramAddressSpace() 11966 : getTargetAddressSpace(T.getQualifiers()); 11967 } 11968 11969 unsigned ASTContext::getTargetAddressSpace(Qualifiers Q) const { 11970 return getTargetAddressSpace(Q.getAddressSpace()); 11971 } 11972 11973 unsigned ASTContext::getTargetAddressSpace(LangAS AS) const { 11974 if (isTargetAddressSpace(AS)) 11975 return toTargetAddressSpace(AS); 11976 else 11977 return (*AddrSpaceMap)[(unsigned)AS]; 11978 } 11979 11980 QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const { 11981 assert(Ty->isFixedPointType()); 11982 11983 if (Ty->isSaturatedFixedPointType()) return Ty; 11984 11985 switch (Ty->castAs<BuiltinType>()->getKind()) { 11986 default: 11987 llvm_unreachable("Not a fixed point type!"); 11988 case BuiltinType::ShortAccum: 11989 return SatShortAccumTy; 11990 case BuiltinType::Accum: 11991 return SatAccumTy; 11992 case BuiltinType::LongAccum: 11993 return SatLongAccumTy; 11994 case BuiltinType::UShortAccum: 11995 return SatUnsignedShortAccumTy; 11996 case BuiltinType::UAccum: 11997 return SatUnsignedAccumTy; 11998 case BuiltinType::ULongAccum: 11999 return SatUnsignedLongAccumTy; 12000 case BuiltinType::ShortFract: 12001 return SatShortFractTy; 12002 case BuiltinType::Fract: 12003 return SatFractTy; 12004 case BuiltinType::LongFract: 12005 return SatLongFractTy; 12006 case BuiltinType::UShortFract: 12007 return SatUnsignedShortFractTy; 12008 case BuiltinType::UFract: 12009 return SatUnsignedFractTy; 12010 case BuiltinType::ULongFract: 12011 return SatUnsignedLongFractTy; 12012 } 12013 } 12014 12015 LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const { 12016 if (LangOpts.OpenCL) 12017 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS); 12018 12019 if (LangOpts.CUDA) 12020 return getTargetInfo().getCUDABuiltinAddressSpace(AS); 12021 12022 return getLangASFromTargetAS(AS); 12023 } 12024 12025 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that 12026 // doesn't include ASTContext.h 12027 template 12028 clang::LazyGenerationalUpdatePtr< 12029 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType 12030 clang::LazyGenerationalUpdatePtr< 12031 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue( 12032 const clang::ASTContext &Ctx, Decl *Value); 12033 12034 unsigned char ASTContext::getFixedPointScale(QualType Ty) const { 12035 assert(Ty->isFixedPointType()); 12036 12037 const TargetInfo &Target = getTargetInfo(); 12038 switch (Ty->castAs<BuiltinType>()->getKind()) { 12039 default: 12040 llvm_unreachable("Not a fixed point type!"); 12041 case BuiltinType::ShortAccum: 12042 case BuiltinType::SatShortAccum: 12043 return Target.getShortAccumScale(); 12044 case BuiltinType::Accum: 12045 case BuiltinType::SatAccum: 12046 return Target.getAccumScale(); 12047 case BuiltinType::LongAccum: 12048 case BuiltinType::SatLongAccum: 12049 return Target.getLongAccumScale(); 12050 case BuiltinType::UShortAccum: 12051 case BuiltinType::SatUShortAccum: 12052 return Target.getUnsignedShortAccumScale(); 12053 case BuiltinType::UAccum: 12054 case BuiltinType::SatUAccum: 12055 return Target.getUnsignedAccumScale(); 12056 case BuiltinType::ULongAccum: 12057 case BuiltinType::SatULongAccum: 12058 return Target.getUnsignedLongAccumScale(); 12059 case BuiltinType::ShortFract: 12060 case BuiltinType::SatShortFract: 12061 return Target.getShortFractScale(); 12062 case BuiltinType::Fract: 12063 case BuiltinType::SatFract: 12064 return Target.getFractScale(); 12065 case BuiltinType::LongFract: 12066 case BuiltinType::SatLongFract: 12067 return Target.getLongFractScale(); 12068 case BuiltinType::UShortFract: 12069 case BuiltinType::SatUShortFract: 12070 return Target.getUnsignedShortFractScale(); 12071 case BuiltinType::UFract: 12072 case BuiltinType::SatUFract: 12073 return Target.getUnsignedFractScale(); 12074 case BuiltinType::ULongFract: 12075 case BuiltinType::SatULongFract: 12076 return Target.getUnsignedLongFractScale(); 12077 } 12078 } 12079 12080 unsigned char ASTContext::getFixedPointIBits(QualType Ty) const { 12081 assert(Ty->isFixedPointType()); 12082 12083 const TargetInfo &Target = getTargetInfo(); 12084 switch (Ty->castAs<BuiltinType>()->getKind()) { 12085 default: 12086 llvm_unreachable("Not a fixed point type!"); 12087 case BuiltinType::ShortAccum: 12088 case BuiltinType::SatShortAccum: 12089 return Target.getShortAccumIBits(); 12090 case BuiltinType::Accum: 12091 case BuiltinType::SatAccum: 12092 return Target.getAccumIBits(); 12093 case BuiltinType::LongAccum: 12094 case BuiltinType::SatLongAccum: 12095 return Target.getLongAccumIBits(); 12096 case BuiltinType::UShortAccum: 12097 case BuiltinType::SatUShortAccum: 12098 return Target.getUnsignedShortAccumIBits(); 12099 case BuiltinType::UAccum: 12100 case BuiltinType::SatUAccum: 12101 return Target.getUnsignedAccumIBits(); 12102 case BuiltinType::ULongAccum: 12103 case BuiltinType::SatULongAccum: 12104 return Target.getUnsignedLongAccumIBits(); 12105 case BuiltinType::ShortFract: 12106 case BuiltinType::SatShortFract: 12107 case BuiltinType::Fract: 12108 case BuiltinType::SatFract: 12109 case BuiltinType::LongFract: 12110 case BuiltinType::SatLongFract: 12111 case BuiltinType::UShortFract: 12112 case BuiltinType::SatUShortFract: 12113 case BuiltinType::UFract: 12114 case BuiltinType::SatUFract: 12115 case BuiltinType::ULongFract: 12116 case BuiltinType::SatULongFract: 12117 return 0; 12118 } 12119 } 12120 12121 llvm::FixedPointSemantics 12122 ASTContext::getFixedPointSemantics(QualType Ty) const { 12123 assert((Ty->isFixedPointType() || Ty->isIntegerType()) && 12124 "Can only get the fixed point semantics for a " 12125 "fixed point or integer type."); 12126 if (Ty->isIntegerType()) 12127 return llvm::FixedPointSemantics::GetIntegerSemantics( 12128 getIntWidth(Ty), Ty->isSignedIntegerType()); 12129 12130 bool isSigned = Ty->isSignedFixedPointType(); 12131 return llvm::FixedPointSemantics( 12132 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned, 12133 Ty->isSaturatedFixedPointType(), 12134 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding()); 12135 } 12136 12137 llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const { 12138 assert(Ty->isFixedPointType()); 12139 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty)); 12140 } 12141 12142 llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const { 12143 assert(Ty->isFixedPointType()); 12144 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty)); 12145 } 12146 12147 QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const { 12148 assert(Ty->isUnsignedFixedPointType() && 12149 "Expected unsigned fixed point type"); 12150 12151 switch (Ty->castAs<BuiltinType>()->getKind()) { 12152 case BuiltinType::UShortAccum: 12153 return ShortAccumTy; 12154 case BuiltinType::UAccum: 12155 return AccumTy; 12156 case BuiltinType::ULongAccum: 12157 return LongAccumTy; 12158 case BuiltinType::SatUShortAccum: 12159 return SatShortAccumTy; 12160 case BuiltinType::SatUAccum: 12161 return SatAccumTy; 12162 case BuiltinType::SatULongAccum: 12163 return SatLongAccumTy; 12164 case BuiltinType::UShortFract: 12165 return ShortFractTy; 12166 case BuiltinType::UFract: 12167 return FractTy; 12168 case BuiltinType::ULongFract: 12169 return LongFractTy; 12170 case BuiltinType::SatUShortFract: 12171 return SatShortFractTy; 12172 case BuiltinType::SatUFract: 12173 return SatFractTy; 12174 case BuiltinType::SatULongFract: 12175 return SatLongFractTy; 12176 default: 12177 llvm_unreachable("Unexpected unsigned fixed point type"); 12178 } 12179 } 12180 12181 ParsedTargetAttr 12182 ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const { 12183 assert(TD != nullptr); 12184 ParsedTargetAttr ParsedAttr = TD->parse(); 12185 12186 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) { 12187 return !Target->isValidFeatureName(StringRef{Feat}.substr(1)); 12188 }); 12189 return ParsedAttr; 12190 } 12191 12192 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 12193 const FunctionDecl *FD) const { 12194 if (FD) 12195 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD)); 12196 else 12197 Target->initFeatureMap(FeatureMap, getDiagnostics(), 12198 Target->getTargetOpts().CPU, 12199 Target->getTargetOpts().Features); 12200 } 12201 12202 // Fills in the supplied string map with the set of target features for the 12203 // passed in function. 12204 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 12205 GlobalDecl GD) const { 12206 StringRef TargetCPU = Target->getTargetOpts().CPU; 12207 const FunctionDecl *FD = GD.getDecl()->getAsFunction(); 12208 if (const auto *TD = FD->getAttr<TargetAttr>()) { 12209 ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD); 12210 12211 // Make a copy of the features as passed on the command line into the 12212 // beginning of the additional features from the function to override. 12213 ParsedAttr.Features.insert( 12214 ParsedAttr.Features.begin(), 12215 Target->getTargetOpts().FeaturesAsWritten.begin(), 12216 Target->getTargetOpts().FeaturesAsWritten.end()); 12217 12218 if (ParsedAttr.Architecture != "" && 12219 Target->isValidCPUName(ParsedAttr.Architecture)) 12220 TargetCPU = ParsedAttr.Architecture; 12221 12222 // Now populate the feature map, first with the TargetCPU which is either 12223 // the default or a new one from the target attribute string. Then we'll use 12224 // the passed in features (FeaturesAsWritten) along with the new ones from 12225 // the attribute. 12226 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, 12227 ParsedAttr.Features); 12228 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) { 12229 llvm::SmallVector<StringRef, 32> FeaturesTmp; 12230 Target->getCPUSpecificCPUDispatchFeatures( 12231 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp); 12232 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end()); 12233 Features.insert(Features.begin(), 12234 Target->getTargetOpts().FeaturesAsWritten.begin(), 12235 Target->getTargetOpts().FeaturesAsWritten.end()); 12236 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features); 12237 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) { 12238 std::vector<std::string> Features; 12239 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex()); 12240 if (VersionStr.startswith("arch=")) 12241 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1); 12242 else if (VersionStr != "default") 12243 Features.push_back((StringRef{"+"} + VersionStr).str()); 12244 12245 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features); 12246 } else { 12247 FeatureMap = Target->getTargetOpts().FeatureMap; 12248 } 12249 } 12250 12251 OMPTraitInfo &ASTContext::getNewOMPTraitInfo() { 12252 OMPTraitInfoVector.emplace_back(new OMPTraitInfo()); 12253 return *OMPTraitInfoVector.back(); 12254 } 12255 12256 const StreamingDiagnostic &clang:: 12257 operator<<(const StreamingDiagnostic &DB, 12258 const ASTContext::SectionInfo &Section) { 12259 if (Section.Decl) 12260 return DB << Section.Decl; 12261 return DB << "a prior #pragma section"; 12262 } 12263 12264 bool ASTContext::mayExternalizeStaticVar(const Decl *D) const { 12265 bool IsStaticVar = 12266 isa<VarDecl>(D) && cast<VarDecl>(D)->getStorageClass() == SC_Static; 12267 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() && 12268 !D->getAttr<CUDADeviceAttr>()->isImplicit()) || 12269 (D->hasAttr<CUDAConstantAttr>() && 12270 !D->getAttr<CUDAConstantAttr>()->isImplicit()); 12271 // CUDA/HIP: static managed variables need to be externalized since it is 12272 // a declaration in IR, therefore cannot have internal linkage. 12273 return IsStaticVar && 12274 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar); 12275 } 12276 12277 bool ASTContext::shouldExternalizeStaticVar(const Decl *D) const { 12278 return mayExternalizeStaticVar(D) && 12279 (D->hasAttr<HIPManagedAttr>() || 12280 CUDADeviceVarODRUsedByHost.count(cast<VarDecl>(D))); 12281 } 12282 12283 StringRef ASTContext::getCUIDHash() const { 12284 if (!CUIDHash.empty()) 12285 return CUIDHash; 12286 if (LangOpts.CUID.empty()) 12287 return StringRef(); 12288 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true); 12289 return CUIDHash; 12290 } 12291