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 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list"); 8552 // namespace std { struct __va_list { 8553 // Note that we create the namespace even in C. This is intentional so that 8554 // the type is consistent between C and C++, which is important in cases where 8555 // the types need to match between translation units (e.g. with 8556 // -fsanitize=cfi-icall). Ideally we wouldn't have created this namespace at 8557 // all, but it's now part of the ABI (e.g. in mangled names), so we can't 8558 // change it. 8559 auto *NS = NamespaceDecl::Create( 8560 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(), 8561 /*Inline*/ false, SourceLocation(), SourceLocation(), 8562 &Context->Idents.get("std"), 8563 /*PrevDecl*/ nullptr); 8564 NS->setImplicit(); 8565 VaListTagDecl->setDeclContext(NS); 8566 8567 VaListTagDecl->startDefinition(); 8568 8569 const size_t NumFields = 5; 8570 QualType FieldTypes[NumFields]; 8571 const char *FieldNames[NumFields]; 8572 8573 // void *__stack; 8574 FieldTypes[0] = Context->getPointerType(Context->VoidTy); 8575 FieldNames[0] = "__stack"; 8576 8577 // void *__gr_top; 8578 FieldTypes[1] = Context->getPointerType(Context->VoidTy); 8579 FieldNames[1] = "__gr_top"; 8580 8581 // void *__vr_top; 8582 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8583 FieldNames[2] = "__vr_top"; 8584 8585 // int __gr_offs; 8586 FieldTypes[3] = Context->IntTy; 8587 FieldNames[3] = "__gr_offs"; 8588 8589 // int __vr_offs; 8590 FieldTypes[4] = Context->IntTy; 8591 FieldNames[4] = "__vr_offs"; 8592 8593 // Create fields 8594 for (unsigned i = 0; i < NumFields; ++i) { 8595 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8596 VaListTagDecl, 8597 SourceLocation(), 8598 SourceLocation(), 8599 &Context->Idents.get(FieldNames[i]), 8600 FieldTypes[i], /*TInfo=*/nullptr, 8601 /*BitWidth=*/nullptr, 8602 /*Mutable=*/false, 8603 ICIS_NoInit); 8604 Field->setAccess(AS_public); 8605 VaListTagDecl->addDecl(Field); 8606 } 8607 VaListTagDecl->completeDefinition(); 8608 Context->VaListTagDecl = VaListTagDecl; 8609 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8610 8611 // } __builtin_va_list; 8612 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list"); 8613 } 8614 8615 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) { 8616 // typedef struct __va_list_tag { 8617 RecordDecl *VaListTagDecl; 8618 8619 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8620 VaListTagDecl->startDefinition(); 8621 8622 const size_t NumFields = 5; 8623 QualType FieldTypes[NumFields]; 8624 const char *FieldNames[NumFields]; 8625 8626 // unsigned char gpr; 8627 FieldTypes[0] = Context->UnsignedCharTy; 8628 FieldNames[0] = "gpr"; 8629 8630 // unsigned char fpr; 8631 FieldTypes[1] = Context->UnsignedCharTy; 8632 FieldNames[1] = "fpr"; 8633 8634 // unsigned short reserved; 8635 FieldTypes[2] = Context->UnsignedShortTy; 8636 FieldNames[2] = "reserved"; 8637 8638 // void* overflow_arg_area; 8639 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 8640 FieldNames[3] = "overflow_arg_area"; 8641 8642 // void* reg_save_area; 8643 FieldTypes[4] = Context->getPointerType(Context->VoidTy); 8644 FieldNames[4] = "reg_save_area"; 8645 8646 // Create fields 8647 for (unsigned i = 0; i < NumFields; ++i) { 8648 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl, 8649 SourceLocation(), 8650 SourceLocation(), 8651 &Context->Idents.get(FieldNames[i]), 8652 FieldTypes[i], /*TInfo=*/nullptr, 8653 /*BitWidth=*/nullptr, 8654 /*Mutable=*/false, 8655 ICIS_NoInit); 8656 Field->setAccess(AS_public); 8657 VaListTagDecl->addDecl(Field); 8658 } 8659 VaListTagDecl->completeDefinition(); 8660 Context->VaListTagDecl = VaListTagDecl; 8661 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8662 8663 // } __va_list_tag; 8664 TypedefDecl *VaListTagTypedefDecl = 8665 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); 8666 8667 QualType VaListTagTypedefType = 8668 Context->getTypedefType(VaListTagTypedefDecl); 8669 8670 // typedef __va_list_tag __builtin_va_list[1]; 8671 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8672 QualType VaListTagArrayType 8673 = Context->getConstantArrayType(VaListTagTypedefType, 8674 Size, nullptr, ArrayType::Normal, 0); 8675 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8676 } 8677 8678 static TypedefDecl * 8679 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) { 8680 // struct __va_list_tag { 8681 RecordDecl *VaListTagDecl; 8682 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8683 VaListTagDecl->startDefinition(); 8684 8685 const size_t NumFields = 4; 8686 QualType FieldTypes[NumFields]; 8687 const char *FieldNames[NumFields]; 8688 8689 // unsigned gp_offset; 8690 FieldTypes[0] = Context->UnsignedIntTy; 8691 FieldNames[0] = "gp_offset"; 8692 8693 // unsigned fp_offset; 8694 FieldTypes[1] = Context->UnsignedIntTy; 8695 FieldNames[1] = "fp_offset"; 8696 8697 // void* overflow_arg_area; 8698 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8699 FieldNames[2] = "overflow_arg_area"; 8700 8701 // void* reg_save_area; 8702 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 8703 FieldNames[3] = "reg_save_area"; 8704 8705 // Create fields 8706 for (unsigned i = 0; i < NumFields; ++i) { 8707 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8708 VaListTagDecl, 8709 SourceLocation(), 8710 SourceLocation(), 8711 &Context->Idents.get(FieldNames[i]), 8712 FieldTypes[i], /*TInfo=*/nullptr, 8713 /*BitWidth=*/nullptr, 8714 /*Mutable=*/false, 8715 ICIS_NoInit); 8716 Field->setAccess(AS_public); 8717 VaListTagDecl->addDecl(Field); 8718 } 8719 VaListTagDecl->completeDefinition(); 8720 Context->VaListTagDecl = VaListTagDecl; 8721 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8722 8723 // }; 8724 8725 // typedef struct __va_list_tag __builtin_va_list[1]; 8726 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8727 QualType VaListTagArrayType = Context->getConstantArrayType( 8728 VaListTagType, Size, nullptr, ArrayType::Normal, 0); 8729 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8730 } 8731 8732 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) { 8733 // typedef int __builtin_va_list[4]; 8734 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4); 8735 QualType IntArrayType = Context->getConstantArrayType( 8736 Context->IntTy, Size, nullptr, ArrayType::Normal, 0); 8737 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list"); 8738 } 8739 8740 static TypedefDecl * 8741 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) { 8742 // struct __va_list 8743 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list"); 8744 if (Context->getLangOpts().CPlusPlus) { 8745 // namespace std { struct __va_list { 8746 NamespaceDecl *NS; 8747 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context), 8748 Context->getTranslationUnitDecl(), 8749 /*Inline*/false, SourceLocation(), 8750 SourceLocation(), &Context->Idents.get("std"), 8751 /*PrevDecl*/ nullptr); 8752 NS->setImplicit(); 8753 VaListDecl->setDeclContext(NS); 8754 } 8755 8756 VaListDecl->startDefinition(); 8757 8758 // void * __ap; 8759 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8760 VaListDecl, 8761 SourceLocation(), 8762 SourceLocation(), 8763 &Context->Idents.get("__ap"), 8764 Context->getPointerType(Context->VoidTy), 8765 /*TInfo=*/nullptr, 8766 /*BitWidth=*/nullptr, 8767 /*Mutable=*/false, 8768 ICIS_NoInit); 8769 Field->setAccess(AS_public); 8770 VaListDecl->addDecl(Field); 8771 8772 // }; 8773 VaListDecl->completeDefinition(); 8774 Context->VaListTagDecl = VaListDecl; 8775 8776 // typedef struct __va_list __builtin_va_list; 8777 QualType T = Context->getRecordType(VaListDecl); 8778 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 8779 } 8780 8781 static TypedefDecl * 8782 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) { 8783 // struct __va_list_tag { 8784 RecordDecl *VaListTagDecl; 8785 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8786 VaListTagDecl->startDefinition(); 8787 8788 const size_t NumFields = 4; 8789 QualType FieldTypes[NumFields]; 8790 const char *FieldNames[NumFields]; 8791 8792 // long __gpr; 8793 FieldTypes[0] = Context->LongTy; 8794 FieldNames[0] = "__gpr"; 8795 8796 // long __fpr; 8797 FieldTypes[1] = Context->LongTy; 8798 FieldNames[1] = "__fpr"; 8799 8800 // void *__overflow_arg_area; 8801 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8802 FieldNames[2] = "__overflow_arg_area"; 8803 8804 // void *__reg_save_area; 8805 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 8806 FieldNames[3] = "__reg_save_area"; 8807 8808 // Create fields 8809 for (unsigned i = 0; i < NumFields; ++i) { 8810 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8811 VaListTagDecl, 8812 SourceLocation(), 8813 SourceLocation(), 8814 &Context->Idents.get(FieldNames[i]), 8815 FieldTypes[i], /*TInfo=*/nullptr, 8816 /*BitWidth=*/nullptr, 8817 /*Mutable=*/false, 8818 ICIS_NoInit); 8819 Field->setAccess(AS_public); 8820 VaListTagDecl->addDecl(Field); 8821 } 8822 VaListTagDecl->completeDefinition(); 8823 Context->VaListTagDecl = VaListTagDecl; 8824 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8825 8826 // }; 8827 8828 // typedef __va_list_tag __builtin_va_list[1]; 8829 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8830 QualType VaListTagArrayType = Context->getConstantArrayType( 8831 VaListTagType, Size, nullptr, ArrayType::Normal, 0); 8832 8833 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8834 } 8835 8836 static TypedefDecl *CreateHexagonBuiltinVaListDecl(const ASTContext *Context) { 8837 // typedef struct __va_list_tag { 8838 RecordDecl *VaListTagDecl; 8839 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8840 VaListTagDecl->startDefinition(); 8841 8842 const size_t NumFields = 3; 8843 QualType FieldTypes[NumFields]; 8844 const char *FieldNames[NumFields]; 8845 8846 // void *CurrentSavedRegisterArea; 8847 FieldTypes[0] = Context->getPointerType(Context->VoidTy); 8848 FieldNames[0] = "__current_saved_reg_area_pointer"; 8849 8850 // void *SavedRegAreaEnd; 8851 FieldTypes[1] = Context->getPointerType(Context->VoidTy); 8852 FieldNames[1] = "__saved_reg_area_end_pointer"; 8853 8854 // void *OverflowArea; 8855 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8856 FieldNames[2] = "__overflow_area_pointer"; 8857 8858 // Create fields 8859 for (unsigned i = 0; i < NumFields; ++i) { 8860 FieldDecl *Field = FieldDecl::Create( 8861 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(), 8862 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i], 8863 /*TInfo=*/nullptr, 8864 /*BitWidth=*/nullptr, 8865 /*Mutable=*/false, ICIS_NoInit); 8866 Field->setAccess(AS_public); 8867 VaListTagDecl->addDecl(Field); 8868 } 8869 VaListTagDecl->completeDefinition(); 8870 Context->VaListTagDecl = VaListTagDecl; 8871 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8872 8873 // } __va_list_tag; 8874 TypedefDecl *VaListTagTypedefDecl = 8875 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); 8876 8877 QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl); 8878 8879 // typedef __va_list_tag __builtin_va_list[1]; 8880 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8881 QualType VaListTagArrayType = Context->getConstantArrayType( 8882 VaListTagTypedefType, Size, nullptr, ArrayType::Normal, 0); 8883 8884 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8885 } 8886 8887 static TypedefDecl *CreateVaListDecl(const ASTContext *Context, 8888 TargetInfo::BuiltinVaListKind Kind) { 8889 switch (Kind) { 8890 case TargetInfo::CharPtrBuiltinVaList: 8891 return CreateCharPtrBuiltinVaListDecl(Context); 8892 case TargetInfo::VoidPtrBuiltinVaList: 8893 return CreateVoidPtrBuiltinVaListDecl(Context); 8894 case TargetInfo::AArch64ABIBuiltinVaList: 8895 return CreateAArch64ABIBuiltinVaListDecl(Context); 8896 case TargetInfo::PowerABIBuiltinVaList: 8897 return CreatePowerABIBuiltinVaListDecl(Context); 8898 case TargetInfo::X86_64ABIBuiltinVaList: 8899 return CreateX86_64ABIBuiltinVaListDecl(Context); 8900 case TargetInfo::PNaClABIBuiltinVaList: 8901 return CreatePNaClABIBuiltinVaListDecl(Context); 8902 case TargetInfo::AAPCSABIBuiltinVaList: 8903 return CreateAAPCSABIBuiltinVaListDecl(Context); 8904 case TargetInfo::SystemZBuiltinVaList: 8905 return CreateSystemZBuiltinVaListDecl(Context); 8906 case TargetInfo::HexagonBuiltinVaList: 8907 return CreateHexagonBuiltinVaListDecl(Context); 8908 } 8909 8910 llvm_unreachable("Unhandled __builtin_va_list type kind"); 8911 } 8912 8913 TypedefDecl *ASTContext::getBuiltinVaListDecl() const { 8914 if (!BuiltinVaListDecl) { 8915 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind()); 8916 assert(BuiltinVaListDecl->isImplicit()); 8917 } 8918 8919 return BuiltinVaListDecl; 8920 } 8921 8922 Decl *ASTContext::getVaListTagDecl() const { 8923 // Force the creation of VaListTagDecl by building the __builtin_va_list 8924 // declaration. 8925 if (!VaListTagDecl) 8926 (void)getBuiltinVaListDecl(); 8927 8928 return VaListTagDecl; 8929 } 8930 8931 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const { 8932 if (!BuiltinMSVaListDecl) 8933 BuiltinMSVaListDecl = CreateMSVaListDecl(this); 8934 8935 return BuiltinMSVaListDecl; 8936 } 8937 8938 bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const { 8939 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID()); 8940 } 8941 8942 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) { 8943 assert(ObjCConstantStringType.isNull() && 8944 "'NSConstantString' type already set!"); 8945 8946 ObjCConstantStringType = getObjCInterfaceType(Decl); 8947 } 8948 8949 /// Retrieve the template name that corresponds to a non-empty 8950 /// lookup. 8951 TemplateName 8952 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin, 8953 UnresolvedSetIterator End) const { 8954 unsigned size = End - Begin; 8955 assert(size > 1 && "set is not overloaded!"); 8956 8957 void *memory = Allocate(sizeof(OverloadedTemplateStorage) + 8958 size * sizeof(FunctionTemplateDecl*)); 8959 auto *OT = new (memory) OverloadedTemplateStorage(size); 8960 8961 NamedDecl **Storage = OT->getStorage(); 8962 for (UnresolvedSetIterator I = Begin; I != End; ++I) { 8963 NamedDecl *D = *I; 8964 assert(isa<FunctionTemplateDecl>(D) || 8965 isa<UnresolvedUsingValueDecl>(D) || 8966 (isa<UsingShadowDecl>(D) && 8967 isa<FunctionTemplateDecl>(D->getUnderlyingDecl()))); 8968 *Storage++ = D; 8969 } 8970 8971 return TemplateName(OT); 8972 } 8973 8974 /// Retrieve a template name representing an unqualified-id that has been 8975 /// assumed to name a template for ADL purposes. 8976 TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const { 8977 auto *OT = new (*this) AssumedTemplateStorage(Name); 8978 return TemplateName(OT); 8979 } 8980 8981 /// Retrieve the template name that represents a qualified 8982 /// template name such as \c std::vector. 8983 TemplateName 8984 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, 8985 bool TemplateKeyword, 8986 TemplateDecl *Template) const { 8987 assert(NNS && "Missing nested-name-specifier in qualified template name"); 8988 8989 // FIXME: Canonicalization? 8990 llvm::FoldingSetNodeID ID; 8991 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template); 8992 8993 void *InsertPos = nullptr; 8994 QualifiedTemplateName *QTN = 8995 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 8996 if (!QTN) { 8997 QTN = new (*this, alignof(QualifiedTemplateName)) 8998 QualifiedTemplateName(NNS, TemplateKeyword, Template); 8999 QualifiedTemplateNames.InsertNode(QTN, InsertPos); 9000 } 9001 9002 return TemplateName(QTN); 9003 } 9004 9005 /// Retrieve the template name that represents a dependent 9006 /// template name such as \c MetaFun::template apply. 9007 TemplateName 9008 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 9009 const IdentifierInfo *Name) const { 9010 assert((!NNS || NNS->isDependent()) && 9011 "Nested name specifier must be dependent"); 9012 9013 llvm::FoldingSetNodeID ID; 9014 DependentTemplateName::Profile(ID, NNS, Name); 9015 9016 void *InsertPos = nullptr; 9017 DependentTemplateName *QTN = 9018 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 9019 9020 if (QTN) 9021 return TemplateName(QTN); 9022 9023 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 9024 if (CanonNNS == NNS) { 9025 QTN = new (*this, alignof(DependentTemplateName)) 9026 DependentTemplateName(NNS, Name); 9027 } else { 9028 TemplateName Canon = getDependentTemplateName(CanonNNS, Name); 9029 QTN = new (*this, alignof(DependentTemplateName)) 9030 DependentTemplateName(NNS, Name, Canon); 9031 DependentTemplateName *CheckQTN = 9032 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 9033 assert(!CheckQTN && "Dependent type name canonicalization broken"); 9034 (void)CheckQTN; 9035 } 9036 9037 DependentTemplateNames.InsertNode(QTN, InsertPos); 9038 return TemplateName(QTN); 9039 } 9040 9041 /// Retrieve the template name that represents a dependent 9042 /// template name such as \c MetaFun::template operator+. 9043 TemplateName 9044 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 9045 OverloadedOperatorKind Operator) const { 9046 assert((!NNS || NNS->isDependent()) && 9047 "Nested name specifier must be dependent"); 9048 9049 llvm::FoldingSetNodeID ID; 9050 DependentTemplateName::Profile(ID, NNS, Operator); 9051 9052 void *InsertPos = nullptr; 9053 DependentTemplateName *QTN 9054 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 9055 9056 if (QTN) 9057 return TemplateName(QTN); 9058 9059 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 9060 if (CanonNNS == NNS) { 9061 QTN = new (*this, alignof(DependentTemplateName)) 9062 DependentTemplateName(NNS, Operator); 9063 } else { 9064 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator); 9065 QTN = new (*this, alignof(DependentTemplateName)) 9066 DependentTemplateName(NNS, Operator, Canon); 9067 9068 DependentTemplateName *CheckQTN 9069 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 9070 assert(!CheckQTN && "Dependent template name canonicalization broken"); 9071 (void)CheckQTN; 9072 } 9073 9074 DependentTemplateNames.InsertNode(QTN, InsertPos); 9075 return TemplateName(QTN); 9076 } 9077 9078 TemplateName 9079 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param, 9080 TemplateName replacement) const { 9081 llvm::FoldingSetNodeID ID; 9082 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement); 9083 9084 void *insertPos = nullptr; 9085 SubstTemplateTemplateParmStorage *subst 9086 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos); 9087 9088 if (!subst) { 9089 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement); 9090 SubstTemplateTemplateParms.InsertNode(subst, insertPos); 9091 } 9092 9093 return TemplateName(subst); 9094 } 9095 9096 TemplateName 9097 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param, 9098 const TemplateArgument &ArgPack) const { 9099 auto &Self = const_cast<ASTContext &>(*this); 9100 llvm::FoldingSetNodeID ID; 9101 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack); 9102 9103 void *InsertPos = nullptr; 9104 SubstTemplateTemplateParmPackStorage *Subst 9105 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos); 9106 9107 if (!Subst) { 9108 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param, 9109 ArgPack.pack_size(), 9110 ArgPack.pack_begin()); 9111 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos); 9112 } 9113 9114 return TemplateName(Subst); 9115 } 9116 9117 /// getFromTargetType - Given one of the integer types provided by 9118 /// TargetInfo, produce the corresponding type. The unsigned @p Type 9119 /// is actually a value of type @c TargetInfo::IntType. 9120 CanQualType ASTContext::getFromTargetType(unsigned Type) const { 9121 switch (Type) { 9122 case TargetInfo::NoInt: return {}; 9123 case TargetInfo::SignedChar: return SignedCharTy; 9124 case TargetInfo::UnsignedChar: return UnsignedCharTy; 9125 case TargetInfo::SignedShort: return ShortTy; 9126 case TargetInfo::UnsignedShort: return UnsignedShortTy; 9127 case TargetInfo::SignedInt: return IntTy; 9128 case TargetInfo::UnsignedInt: return UnsignedIntTy; 9129 case TargetInfo::SignedLong: return LongTy; 9130 case TargetInfo::UnsignedLong: return UnsignedLongTy; 9131 case TargetInfo::SignedLongLong: return LongLongTy; 9132 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy; 9133 } 9134 9135 llvm_unreachable("Unhandled TargetInfo::IntType value"); 9136 } 9137 9138 //===----------------------------------------------------------------------===// 9139 // Type Predicates. 9140 //===----------------------------------------------------------------------===// 9141 9142 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's 9143 /// garbage collection attribute. 9144 /// 9145 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const { 9146 if (getLangOpts().getGC() == LangOptions::NonGC) 9147 return Qualifiers::GCNone; 9148 9149 assert(getLangOpts().ObjC); 9150 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr(); 9151 9152 // Default behaviour under objective-C's gc is for ObjC pointers 9153 // (or pointers to them) be treated as though they were declared 9154 // as __strong. 9155 if (GCAttrs == Qualifiers::GCNone) { 9156 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) 9157 return Qualifiers::Strong; 9158 else if (Ty->isPointerType()) 9159 return getObjCGCAttrKind(Ty->castAs<PointerType>()->getPointeeType()); 9160 } else { 9161 // It's not valid to set GC attributes on anything that isn't a 9162 // pointer. 9163 #ifndef NDEBUG 9164 QualType CT = Ty->getCanonicalTypeInternal(); 9165 while (const auto *AT = dyn_cast<ArrayType>(CT)) 9166 CT = AT->getElementType(); 9167 assert(CT->isAnyPointerType() || CT->isBlockPointerType()); 9168 #endif 9169 } 9170 return GCAttrs; 9171 } 9172 9173 //===----------------------------------------------------------------------===// 9174 // Type Compatibility Testing 9175 //===----------------------------------------------------------------------===// 9176 9177 /// areCompatVectorTypes - Return true if the two specified vector types are 9178 /// compatible. 9179 static bool areCompatVectorTypes(const VectorType *LHS, 9180 const VectorType *RHS) { 9181 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 9182 return LHS->getElementType() == RHS->getElementType() && 9183 LHS->getNumElements() == RHS->getNumElements(); 9184 } 9185 9186 /// areCompatMatrixTypes - Return true if the two specified matrix types are 9187 /// compatible. 9188 static bool areCompatMatrixTypes(const ConstantMatrixType *LHS, 9189 const ConstantMatrixType *RHS) { 9190 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 9191 return LHS->getElementType() == RHS->getElementType() && 9192 LHS->getNumRows() == RHS->getNumRows() && 9193 LHS->getNumColumns() == RHS->getNumColumns(); 9194 } 9195 9196 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec, 9197 QualType SecondVec) { 9198 assert(FirstVec->isVectorType() && "FirstVec should be a vector type"); 9199 assert(SecondVec->isVectorType() && "SecondVec should be a vector type"); 9200 9201 if (hasSameUnqualifiedType(FirstVec, SecondVec)) 9202 return true; 9203 9204 // Treat Neon vector types and most AltiVec vector types as if they are the 9205 // equivalent GCC vector types. 9206 const auto *First = FirstVec->castAs<VectorType>(); 9207 const auto *Second = SecondVec->castAs<VectorType>(); 9208 if (First->getNumElements() == Second->getNumElements() && 9209 hasSameType(First->getElementType(), Second->getElementType()) && 9210 First->getVectorKind() != VectorType::AltiVecPixel && 9211 First->getVectorKind() != VectorType::AltiVecBool && 9212 Second->getVectorKind() != VectorType::AltiVecPixel && 9213 Second->getVectorKind() != VectorType::AltiVecBool && 9214 First->getVectorKind() != VectorType::SveFixedLengthDataVector && 9215 First->getVectorKind() != VectorType::SveFixedLengthPredicateVector && 9216 Second->getVectorKind() != VectorType::SveFixedLengthDataVector && 9217 Second->getVectorKind() != VectorType::SveFixedLengthPredicateVector) 9218 return true; 9219 9220 return false; 9221 } 9222 9223 /// getSVETypeSize - Return SVE vector or predicate register size. 9224 static uint64_t getSVETypeSize(ASTContext &Context, const BuiltinType *Ty) { 9225 assert(Ty->isVLSTBuiltinType() && "Invalid SVE Type"); 9226 return Ty->getKind() == BuiltinType::SveBool 9227 ? (Context.getLangOpts().VScaleMin * 128) / Context.getCharWidth() 9228 : Context.getLangOpts().VScaleMin * 128; 9229 } 9230 9231 bool ASTContext::areCompatibleSveTypes(QualType FirstType, 9232 QualType SecondType) { 9233 assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) || 9234 (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) && 9235 "Expected SVE builtin type and vector type!"); 9236 9237 auto IsValidCast = [this](QualType FirstType, QualType SecondType) { 9238 if (const auto *BT = FirstType->getAs<BuiltinType>()) { 9239 if (const auto *VT = SecondType->getAs<VectorType>()) { 9240 // Predicates have the same representation as uint8 so we also have to 9241 // check the kind to make these types incompatible. 9242 if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 9243 return BT->getKind() == BuiltinType::SveBool; 9244 else if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) 9245 return VT->getElementType().getCanonicalType() == 9246 FirstType->getSveEltType(*this); 9247 else if (VT->getVectorKind() == VectorType::GenericVector) 9248 return getTypeSize(SecondType) == getSVETypeSize(*this, BT) && 9249 hasSameType(VT->getElementType(), 9250 getBuiltinVectorTypeInfo(BT).ElementType); 9251 } 9252 } 9253 return false; 9254 }; 9255 9256 return IsValidCast(FirstType, SecondType) || 9257 IsValidCast(SecondType, FirstType); 9258 } 9259 9260 bool ASTContext::areLaxCompatibleSveTypes(QualType FirstType, 9261 QualType SecondType) { 9262 assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) || 9263 (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) && 9264 "Expected SVE builtin type and vector type!"); 9265 9266 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) { 9267 const auto *BT = FirstType->getAs<BuiltinType>(); 9268 if (!BT) 9269 return false; 9270 9271 const auto *VecTy = SecondType->getAs<VectorType>(); 9272 if (VecTy && 9273 (VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector || 9274 VecTy->getVectorKind() == VectorType::GenericVector)) { 9275 const LangOptions::LaxVectorConversionKind LVCKind = 9276 getLangOpts().getLaxVectorConversions(); 9277 9278 // Can not convert between sve predicates and sve vectors because of 9279 // different size. 9280 if (BT->getKind() == BuiltinType::SveBool && 9281 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector) 9282 return false; 9283 9284 // If __ARM_FEATURE_SVE_BITS != N do not allow GNU vector lax conversion. 9285 // "Whenever __ARM_FEATURE_SVE_BITS==N, GNUT implicitly 9286 // converts to VLAT and VLAT implicitly converts to GNUT." 9287 // ACLE Spec Version 00bet6, 3.7.3.2. Behavior common to vectors and 9288 // predicates. 9289 if (VecTy->getVectorKind() == VectorType::GenericVector && 9290 getTypeSize(SecondType) != getSVETypeSize(*this, BT)) 9291 return false; 9292 9293 // If -flax-vector-conversions=all is specified, the types are 9294 // certainly compatible. 9295 if (LVCKind == LangOptions::LaxVectorConversionKind::All) 9296 return true; 9297 9298 // If -flax-vector-conversions=integer is specified, the types are 9299 // compatible if the elements are integer types. 9300 if (LVCKind == LangOptions::LaxVectorConversionKind::Integer) 9301 return VecTy->getElementType().getCanonicalType()->isIntegerType() && 9302 FirstType->getSveEltType(*this)->isIntegerType(); 9303 } 9304 9305 return false; 9306 }; 9307 9308 return IsLaxCompatible(FirstType, SecondType) || 9309 IsLaxCompatible(SecondType, FirstType); 9310 } 9311 9312 bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const { 9313 while (true) { 9314 // __strong id 9315 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) { 9316 if (Attr->getAttrKind() == attr::ObjCOwnership) 9317 return true; 9318 9319 Ty = Attr->getModifiedType(); 9320 9321 // X *__strong (...) 9322 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) { 9323 Ty = Paren->getInnerType(); 9324 9325 // We do not want to look through typedefs, typeof(expr), 9326 // typeof(type), or any other way that the type is somehow 9327 // abstracted. 9328 } else { 9329 return false; 9330 } 9331 } 9332 } 9333 9334 //===----------------------------------------------------------------------===// 9335 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's. 9336 //===----------------------------------------------------------------------===// 9337 9338 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the 9339 /// inheritance hierarchy of 'rProto'. 9340 bool 9341 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, 9342 ObjCProtocolDecl *rProto) const { 9343 if (declaresSameEntity(lProto, rProto)) 9344 return true; 9345 for (auto *PI : rProto->protocols()) 9346 if (ProtocolCompatibleWithProtocol(lProto, PI)) 9347 return true; 9348 return false; 9349 } 9350 9351 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and 9352 /// Class<pr1, ...>. 9353 bool ASTContext::ObjCQualifiedClassTypesAreCompatible( 9354 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) { 9355 for (auto *lhsProto : lhs->quals()) { 9356 bool match = false; 9357 for (auto *rhsProto : rhs->quals()) { 9358 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) { 9359 match = true; 9360 break; 9361 } 9362 } 9363 if (!match) 9364 return false; 9365 } 9366 return true; 9367 } 9368 9369 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an 9370 /// ObjCQualifiedIDType. 9371 bool ASTContext::ObjCQualifiedIdTypesAreCompatible( 9372 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs, 9373 bool compare) { 9374 // Allow id<P..> and an 'id' in all cases. 9375 if (lhs->isObjCIdType() || rhs->isObjCIdType()) 9376 return true; 9377 9378 // Don't allow id<P..> to convert to Class or Class<P..> in either direction. 9379 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() || 9380 rhs->isObjCClassType() || rhs->isObjCQualifiedClassType()) 9381 return false; 9382 9383 if (lhs->isObjCQualifiedIdType()) { 9384 if (rhs->qual_empty()) { 9385 // If the RHS is a unqualified interface pointer "NSString*", 9386 // make sure we check the class hierarchy. 9387 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) { 9388 for (auto *I : lhs->quals()) { 9389 // when comparing an id<P> on lhs with a static type on rhs, 9390 // see if static class implements all of id's protocols, directly or 9391 // through its super class and categories. 9392 if (!rhsID->ClassImplementsProtocol(I, true)) 9393 return false; 9394 } 9395 } 9396 // If there are no qualifiers and no interface, we have an 'id'. 9397 return true; 9398 } 9399 // Both the right and left sides have qualifiers. 9400 for (auto *lhsProto : lhs->quals()) { 9401 bool match = false; 9402 9403 // when comparing an id<P> on lhs with a static type on rhs, 9404 // see if static class implements all of id's protocols, directly or 9405 // through its super class and categories. 9406 for (auto *rhsProto : rhs->quals()) { 9407 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 9408 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 9409 match = true; 9410 break; 9411 } 9412 } 9413 // If the RHS is a qualified interface pointer "NSString<P>*", 9414 // make sure we check the class hierarchy. 9415 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) { 9416 for (auto *I : lhs->quals()) { 9417 // when comparing an id<P> on lhs with a static type on rhs, 9418 // see if static class implements all of id's protocols, directly or 9419 // through its super class and categories. 9420 if (rhsID->ClassImplementsProtocol(I, true)) { 9421 match = true; 9422 break; 9423 } 9424 } 9425 } 9426 if (!match) 9427 return false; 9428 } 9429 9430 return true; 9431 } 9432 9433 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>"); 9434 9435 if (lhs->getInterfaceType()) { 9436 // If both the right and left sides have qualifiers. 9437 for (auto *lhsProto : lhs->quals()) { 9438 bool match = false; 9439 9440 // when comparing an id<P> on rhs with a static type on lhs, 9441 // see if static class implements all of id's protocols, directly or 9442 // through its super class and categories. 9443 // First, lhs protocols in the qualifier list must be found, direct 9444 // or indirect in rhs's qualifier list or it is a mismatch. 9445 for (auto *rhsProto : rhs->quals()) { 9446 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 9447 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 9448 match = true; 9449 break; 9450 } 9451 } 9452 if (!match) 9453 return false; 9454 } 9455 9456 // Static class's protocols, or its super class or category protocols 9457 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch. 9458 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) { 9459 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols; 9460 CollectInheritedProtocols(lhsID, LHSInheritedProtocols); 9461 // This is rather dubious but matches gcc's behavior. If lhs has 9462 // no type qualifier and its class has no static protocol(s) 9463 // assume that it is mismatch. 9464 if (LHSInheritedProtocols.empty() && lhs->qual_empty()) 9465 return false; 9466 for (auto *lhsProto : LHSInheritedProtocols) { 9467 bool match = false; 9468 for (auto *rhsProto : rhs->quals()) { 9469 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 9470 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 9471 match = true; 9472 break; 9473 } 9474 } 9475 if (!match) 9476 return false; 9477 } 9478 } 9479 return true; 9480 } 9481 return false; 9482 } 9483 9484 /// canAssignObjCInterfaces - Return true if the two interface types are 9485 /// compatible for assignment from RHS to LHS. This handles validation of any 9486 /// protocol qualifiers on the LHS or RHS. 9487 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, 9488 const ObjCObjectPointerType *RHSOPT) { 9489 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 9490 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 9491 9492 // If either type represents the built-in 'id' type, return true. 9493 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId()) 9494 return true; 9495 9496 // Function object that propagates a successful result or handles 9497 // __kindof types. 9498 auto finish = [&](bool succeeded) -> bool { 9499 if (succeeded) 9500 return true; 9501 9502 if (!RHS->isKindOfType()) 9503 return false; 9504 9505 // Strip off __kindof and protocol qualifiers, then check whether 9506 // we can assign the other way. 9507 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this), 9508 LHSOPT->stripObjCKindOfTypeAndQuals(*this)); 9509 }; 9510 9511 // Casts from or to id<P> are allowed when the other side has compatible 9512 // protocols. 9513 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) { 9514 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false)); 9515 } 9516 9517 // Verify protocol compatibility for casts from Class<P1> to Class<P2>. 9518 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) { 9519 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT)); 9520 } 9521 9522 // Casts from Class to Class<Foo>, or vice-versa, are allowed. 9523 if (LHS->isObjCClass() && RHS->isObjCClass()) { 9524 return true; 9525 } 9526 9527 // If we have 2 user-defined types, fall into that path. 9528 if (LHS->getInterface() && RHS->getInterface()) { 9529 return finish(canAssignObjCInterfaces(LHS, RHS)); 9530 } 9531 9532 return false; 9533 } 9534 9535 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written 9536 /// for providing type-safety for objective-c pointers used to pass/return 9537 /// arguments in block literals. When passed as arguments, passing 'A*' where 9538 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is 9539 /// not OK. For the return type, the opposite is not OK. 9540 bool ASTContext::canAssignObjCInterfacesInBlockPointer( 9541 const ObjCObjectPointerType *LHSOPT, 9542 const ObjCObjectPointerType *RHSOPT, 9543 bool BlockReturnType) { 9544 9545 // Function object that propagates a successful result or handles 9546 // __kindof types. 9547 auto finish = [&](bool succeeded) -> bool { 9548 if (succeeded) 9549 return true; 9550 9551 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT; 9552 if (!Expected->isKindOfType()) 9553 return false; 9554 9555 // Strip off __kindof and protocol qualifiers, then check whether 9556 // we can assign the other way. 9557 return canAssignObjCInterfacesInBlockPointer( 9558 RHSOPT->stripObjCKindOfTypeAndQuals(*this), 9559 LHSOPT->stripObjCKindOfTypeAndQuals(*this), 9560 BlockReturnType); 9561 }; 9562 9563 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType()) 9564 return true; 9565 9566 if (LHSOPT->isObjCBuiltinType()) { 9567 return finish(RHSOPT->isObjCBuiltinType() || 9568 RHSOPT->isObjCQualifiedIdType()); 9569 } 9570 9571 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) { 9572 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking) 9573 // Use for block parameters previous type checking for compatibility. 9574 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) || 9575 // Or corrected type checking as in non-compat mode. 9576 (!BlockReturnType && 9577 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false))); 9578 else 9579 return finish(ObjCQualifiedIdTypesAreCompatible( 9580 (BlockReturnType ? LHSOPT : RHSOPT), 9581 (BlockReturnType ? RHSOPT : LHSOPT), false)); 9582 } 9583 9584 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType(); 9585 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType(); 9586 if (LHS && RHS) { // We have 2 user-defined types. 9587 if (LHS != RHS) { 9588 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl())) 9589 return finish(BlockReturnType); 9590 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl())) 9591 return finish(!BlockReturnType); 9592 } 9593 else 9594 return true; 9595 } 9596 return false; 9597 } 9598 9599 /// Comparison routine for Objective-C protocols to be used with 9600 /// llvm::array_pod_sort. 9601 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs, 9602 ObjCProtocolDecl * const *rhs) { 9603 return (*lhs)->getName().compare((*rhs)->getName()); 9604 } 9605 9606 /// getIntersectionOfProtocols - This routine finds the intersection of set 9607 /// of protocols inherited from two distinct objective-c pointer objects with 9608 /// the given common base. 9609 /// It is used to build composite qualifier list of the composite type of 9610 /// the conditional expression involving two objective-c pointer objects. 9611 static 9612 void getIntersectionOfProtocols(ASTContext &Context, 9613 const ObjCInterfaceDecl *CommonBase, 9614 const ObjCObjectPointerType *LHSOPT, 9615 const ObjCObjectPointerType *RHSOPT, 9616 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) { 9617 9618 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 9619 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 9620 assert(LHS->getInterface() && "LHS must have an interface base"); 9621 assert(RHS->getInterface() && "RHS must have an interface base"); 9622 9623 // Add all of the protocols for the LHS. 9624 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet; 9625 9626 // Start with the protocol qualifiers. 9627 for (auto proto : LHS->quals()) { 9628 Context.CollectInheritedProtocols(proto, LHSProtocolSet); 9629 } 9630 9631 // Also add the protocols associated with the LHS interface. 9632 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet); 9633 9634 // Add all of the protocols for the RHS. 9635 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet; 9636 9637 // Start with the protocol qualifiers. 9638 for (auto proto : RHS->quals()) { 9639 Context.CollectInheritedProtocols(proto, RHSProtocolSet); 9640 } 9641 9642 // Also add the protocols associated with the RHS interface. 9643 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet); 9644 9645 // Compute the intersection of the collected protocol sets. 9646 for (auto proto : LHSProtocolSet) { 9647 if (RHSProtocolSet.count(proto)) 9648 IntersectionSet.push_back(proto); 9649 } 9650 9651 // Compute the set of protocols that is implied by either the common type or 9652 // the protocols within the intersection. 9653 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols; 9654 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols); 9655 9656 // Remove any implied protocols from the list of inherited protocols. 9657 if (!ImpliedProtocols.empty()) { 9658 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool { 9659 return ImpliedProtocols.contains(proto); 9660 }); 9661 } 9662 9663 // Sort the remaining protocols by name. 9664 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(), 9665 compareObjCProtocolsByName); 9666 } 9667 9668 /// Determine whether the first type is a subtype of the second. 9669 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs, 9670 QualType rhs) { 9671 // Common case: two object pointers. 9672 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>(); 9673 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 9674 if (lhsOPT && rhsOPT) 9675 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT); 9676 9677 // Two block pointers. 9678 const auto *lhsBlock = lhs->getAs<BlockPointerType>(); 9679 const auto *rhsBlock = rhs->getAs<BlockPointerType>(); 9680 if (lhsBlock && rhsBlock) 9681 return ctx.typesAreBlockPointerCompatible(lhs, rhs); 9682 9683 // If either is an unqualified 'id' and the other is a block, it's 9684 // acceptable. 9685 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) || 9686 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock)) 9687 return true; 9688 9689 return false; 9690 } 9691 9692 // Check that the given Objective-C type argument lists are equivalent. 9693 static bool sameObjCTypeArgs(ASTContext &ctx, 9694 const ObjCInterfaceDecl *iface, 9695 ArrayRef<QualType> lhsArgs, 9696 ArrayRef<QualType> rhsArgs, 9697 bool stripKindOf) { 9698 if (lhsArgs.size() != rhsArgs.size()) 9699 return false; 9700 9701 ObjCTypeParamList *typeParams = iface->getTypeParamList(); 9702 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) { 9703 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i])) 9704 continue; 9705 9706 switch (typeParams->begin()[i]->getVariance()) { 9707 case ObjCTypeParamVariance::Invariant: 9708 if (!stripKindOf || 9709 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx), 9710 rhsArgs[i].stripObjCKindOfType(ctx))) { 9711 return false; 9712 } 9713 break; 9714 9715 case ObjCTypeParamVariance::Covariant: 9716 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i])) 9717 return false; 9718 break; 9719 9720 case ObjCTypeParamVariance::Contravariant: 9721 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i])) 9722 return false; 9723 break; 9724 } 9725 } 9726 9727 return true; 9728 } 9729 9730 QualType ASTContext::areCommonBaseCompatible( 9731 const ObjCObjectPointerType *Lptr, 9732 const ObjCObjectPointerType *Rptr) { 9733 const ObjCObjectType *LHS = Lptr->getObjectType(); 9734 const ObjCObjectType *RHS = Rptr->getObjectType(); 9735 const ObjCInterfaceDecl* LDecl = LHS->getInterface(); 9736 const ObjCInterfaceDecl* RDecl = RHS->getInterface(); 9737 9738 if (!LDecl || !RDecl) 9739 return {}; 9740 9741 // When either LHS or RHS is a kindof type, we should return a kindof type. 9742 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return 9743 // kindof(A). 9744 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType(); 9745 9746 // Follow the left-hand side up the class hierarchy until we either hit a 9747 // root or find the RHS. Record the ancestors in case we don't find it. 9748 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4> 9749 LHSAncestors; 9750 while (true) { 9751 // Record this ancestor. We'll need this if the common type isn't in the 9752 // path from the LHS to the root. 9753 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS; 9754 9755 if (declaresSameEntity(LHS->getInterface(), RDecl)) { 9756 // Get the type arguments. 9757 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten(); 9758 bool anyChanges = false; 9759 if (LHS->isSpecialized() && RHS->isSpecialized()) { 9760 // Both have type arguments, compare them. 9761 if (!sameObjCTypeArgs(*this, LHS->getInterface(), 9762 LHS->getTypeArgs(), RHS->getTypeArgs(), 9763 /*stripKindOf=*/true)) 9764 return {}; 9765 } else if (LHS->isSpecialized() != RHS->isSpecialized()) { 9766 // If only one has type arguments, the result will not have type 9767 // arguments. 9768 LHSTypeArgs = {}; 9769 anyChanges = true; 9770 } 9771 9772 // Compute the intersection of protocols. 9773 SmallVector<ObjCProtocolDecl *, 8> Protocols; 9774 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr, 9775 Protocols); 9776 if (!Protocols.empty()) 9777 anyChanges = true; 9778 9779 // If anything in the LHS will have changed, build a new result type. 9780 // If we need to return a kindof type but LHS is not a kindof type, we 9781 // build a new result type. 9782 if (anyChanges || LHS->isKindOfType() != anyKindOf) { 9783 QualType Result = getObjCInterfaceType(LHS->getInterface()); 9784 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols, 9785 anyKindOf || LHS->isKindOfType()); 9786 return getObjCObjectPointerType(Result); 9787 } 9788 9789 return getObjCObjectPointerType(QualType(LHS, 0)); 9790 } 9791 9792 // Find the superclass. 9793 QualType LHSSuperType = LHS->getSuperClassType(); 9794 if (LHSSuperType.isNull()) 9795 break; 9796 9797 LHS = LHSSuperType->castAs<ObjCObjectType>(); 9798 } 9799 9800 // We didn't find anything by following the LHS to its root; now check 9801 // the RHS against the cached set of ancestors. 9802 while (true) { 9803 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl()); 9804 if (KnownLHS != LHSAncestors.end()) { 9805 LHS = KnownLHS->second; 9806 9807 // Get the type arguments. 9808 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten(); 9809 bool anyChanges = false; 9810 if (LHS->isSpecialized() && RHS->isSpecialized()) { 9811 // Both have type arguments, compare them. 9812 if (!sameObjCTypeArgs(*this, LHS->getInterface(), 9813 LHS->getTypeArgs(), RHS->getTypeArgs(), 9814 /*stripKindOf=*/true)) 9815 return {}; 9816 } else if (LHS->isSpecialized() != RHS->isSpecialized()) { 9817 // If only one has type arguments, the result will not have type 9818 // arguments. 9819 RHSTypeArgs = {}; 9820 anyChanges = true; 9821 } 9822 9823 // Compute the intersection of protocols. 9824 SmallVector<ObjCProtocolDecl *, 8> Protocols; 9825 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr, 9826 Protocols); 9827 if (!Protocols.empty()) 9828 anyChanges = true; 9829 9830 // If we need to return a kindof type but RHS is not a kindof type, we 9831 // build a new result type. 9832 if (anyChanges || RHS->isKindOfType() != anyKindOf) { 9833 QualType Result = getObjCInterfaceType(RHS->getInterface()); 9834 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols, 9835 anyKindOf || RHS->isKindOfType()); 9836 return getObjCObjectPointerType(Result); 9837 } 9838 9839 return getObjCObjectPointerType(QualType(RHS, 0)); 9840 } 9841 9842 // Find the superclass of the RHS. 9843 QualType RHSSuperType = RHS->getSuperClassType(); 9844 if (RHSSuperType.isNull()) 9845 break; 9846 9847 RHS = RHSSuperType->castAs<ObjCObjectType>(); 9848 } 9849 9850 return {}; 9851 } 9852 9853 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS, 9854 const ObjCObjectType *RHS) { 9855 assert(LHS->getInterface() && "LHS is not an interface type"); 9856 assert(RHS->getInterface() && "RHS is not an interface type"); 9857 9858 // Verify that the base decls are compatible: the RHS must be a subclass of 9859 // the LHS. 9860 ObjCInterfaceDecl *LHSInterface = LHS->getInterface(); 9861 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface()); 9862 if (!IsSuperClass) 9863 return false; 9864 9865 // If the LHS has protocol qualifiers, determine whether all of them are 9866 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the 9867 // LHS). 9868 if (LHS->getNumProtocols() > 0) { 9869 // OK if conversion of LHS to SuperClass results in narrowing of types 9870 // ; i.e., SuperClass may implement at least one of the protocols 9871 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok. 9872 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>. 9873 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols; 9874 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols); 9875 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's 9876 // qualifiers. 9877 for (auto *RHSPI : RHS->quals()) 9878 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols); 9879 // If there is no protocols associated with RHS, it is not a match. 9880 if (SuperClassInheritedProtocols.empty()) 9881 return false; 9882 9883 for (const auto *LHSProto : LHS->quals()) { 9884 bool SuperImplementsProtocol = false; 9885 for (auto *SuperClassProto : SuperClassInheritedProtocols) 9886 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) { 9887 SuperImplementsProtocol = true; 9888 break; 9889 } 9890 if (!SuperImplementsProtocol) 9891 return false; 9892 } 9893 } 9894 9895 // If the LHS is specialized, we may need to check type arguments. 9896 if (LHS->isSpecialized()) { 9897 // Follow the superclass chain until we've matched the LHS class in the 9898 // hierarchy. This substitutes type arguments through. 9899 const ObjCObjectType *RHSSuper = RHS; 9900 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface)) 9901 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>(); 9902 9903 // If the RHS is specializd, compare type arguments. 9904 if (RHSSuper->isSpecialized() && 9905 !sameObjCTypeArgs(*this, LHS->getInterface(), 9906 LHS->getTypeArgs(), RHSSuper->getTypeArgs(), 9907 /*stripKindOf=*/true)) { 9908 return false; 9909 } 9910 } 9911 9912 return true; 9913 } 9914 9915 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) { 9916 // get the "pointed to" types 9917 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>(); 9918 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>(); 9919 9920 if (!LHSOPT || !RHSOPT) 9921 return false; 9922 9923 return canAssignObjCInterfaces(LHSOPT, RHSOPT) || 9924 canAssignObjCInterfaces(RHSOPT, LHSOPT); 9925 } 9926 9927 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) { 9928 return canAssignObjCInterfaces( 9929 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(), 9930 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>()); 9931 } 9932 9933 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible, 9934 /// both shall have the identically qualified version of a compatible type. 9935 /// C99 6.2.7p1: Two types have compatible types if their types are the 9936 /// same. See 6.7.[2,3,5] for additional rules. 9937 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS, 9938 bool CompareUnqualified) { 9939 if (getLangOpts().CPlusPlus) 9940 return hasSameType(LHS, RHS); 9941 9942 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull(); 9943 } 9944 9945 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) { 9946 return typesAreCompatible(LHS, RHS); 9947 } 9948 9949 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) { 9950 return !mergeTypes(LHS, RHS, true).isNull(); 9951 } 9952 9953 /// mergeTransparentUnionType - if T is a transparent union type and a member 9954 /// of T is compatible with SubType, return the merged type, else return 9955 /// QualType() 9956 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType, 9957 bool OfBlockPointer, 9958 bool Unqualified) { 9959 if (const RecordType *UT = T->getAsUnionType()) { 9960 RecordDecl *UD = UT->getDecl(); 9961 if (UD->hasAttr<TransparentUnionAttr>()) { 9962 for (const auto *I : UD->fields()) { 9963 QualType ET = I->getType().getUnqualifiedType(); 9964 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified); 9965 if (!MT.isNull()) 9966 return MT; 9967 } 9968 } 9969 } 9970 9971 return {}; 9972 } 9973 9974 /// mergeFunctionParameterTypes - merge two types which appear as function 9975 /// parameter types 9976 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs, 9977 bool OfBlockPointer, 9978 bool Unqualified) { 9979 // GNU extension: two types are compatible if they appear as a function 9980 // argument, one of the types is a transparent union type and the other 9981 // type is compatible with a union member 9982 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer, 9983 Unqualified); 9984 if (!lmerge.isNull()) 9985 return lmerge; 9986 9987 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer, 9988 Unqualified); 9989 if (!rmerge.isNull()) 9990 return rmerge; 9991 9992 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified); 9993 } 9994 9995 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, 9996 bool OfBlockPointer, bool Unqualified, 9997 bool AllowCXX) { 9998 const auto *lbase = lhs->castAs<FunctionType>(); 9999 const auto *rbase = rhs->castAs<FunctionType>(); 10000 const auto *lproto = dyn_cast<FunctionProtoType>(lbase); 10001 const auto *rproto = dyn_cast<FunctionProtoType>(rbase); 10002 bool allLTypes = true; 10003 bool allRTypes = true; 10004 10005 // Check return type 10006 QualType retType; 10007 if (OfBlockPointer) { 10008 QualType RHS = rbase->getReturnType(); 10009 QualType LHS = lbase->getReturnType(); 10010 bool UnqualifiedResult = Unqualified; 10011 if (!UnqualifiedResult) 10012 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers()); 10013 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true); 10014 } 10015 else 10016 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false, 10017 Unqualified); 10018 if (retType.isNull()) 10019 return {}; 10020 10021 if (Unqualified) 10022 retType = retType.getUnqualifiedType(); 10023 10024 CanQualType LRetType = getCanonicalType(lbase->getReturnType()); 10025 CanQualType RRetType = getCanonicalType(rbase->getReturnType()); 10026 if (Unqualified) { 10027 LRetType = LRetType.getUnqualifiedType(); 10028 RRetType = RRetType.getUnqualifiedType(); 10029 } 10030 10031 if (getCanonicalType(retType) != LRetType) 10032 allLTypes = false; 10033 if (getCanonicalType(retType) != RRetType) 10034 allRTypes = false; 10035 10036 // FIXME: double check this 10037 // FIXME: should we error if lbase->getRegParmAttr() != 0 && 10038 // rbase->getRegParmAttr() != 0 && 10039 // lbase->getRegParmAttr() != rbase->getRegParmAttr()? 10040 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo(); 10041 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo(); 10042 10043 // Compatible functions must have compatible calling conventions 10044 if (lbaseInfo.getCC() != rbaseInfo.getCC()) 10045 return {}; 10046 10047 // Regparm is part of the calling convention. 10048 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm()) 10049 return {}; 10050 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm()) 10051 return {}; 10052 10053 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult()) 10054 return {}; 10055 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs()) 10056 return {}; 10057 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck()) 10058 return {}; 10059 10060 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'. 10061 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn(); 10062 10063 if (lbaseInfo.getNoReturn() != NoReturn) 10064 allLTypes = false; 10065 if (rbaseInfo.getNoReturn() != NoReturn) 10066 allRTypes = false; 10067 10068 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn); 10069 10070 if (lproto && rproto) { // two C99 style function prototypes 10071 assert((AllowCXX || 10072 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) && 10073 "C++ shouldn't be here"); 10074 // Compatible functions must have the same number of parameters 10075 if (lproto->getNumParams() != rproto->getNumParams()) 10076 return {}; 10077 10078 // Variadic and non-variadic functions aren't compatible 10079 if (lproto->isVariadic() != rproto->isVariadic()) 10080 return {}; 10081 10082 if (lproto->getMethodQuals() != rproto->getMethodQuals()) 10083 return {}; 10084 10085 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos; 10086 bool canUseLeft, canUseRight; 10087 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight, 10088 newParamInfos)) 10089 return {}; 10090 10091 if (!canUseLeft) 10092 allLTypes = false; 10093 if (!canUseRight) 10094 allRTypes = false; 10095 10096 // Check parameter type compatibility 10097 SmallVector<QualType, 10> types; 10098 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) { 10099 QualType lParamType = lproto->getParamType(i).getUnqualifiedType(); 10100 QualType rParamType = rproto->getParamType(i).getUnqualifiedType(); 10101 QualType paramType = mergeFunctionParameterTypes( 10102 lParamType, rParamType, OfBlockPointer, Unqualified); 10103 if (paramType.isNull()) 10104 return {}; 10105 10106 if (Unqualified) 10107 paramType = paramType.getUnqualifiedType(); 10108 10109 types.push_back(paramType); 10110 if (Unqualified) { 10111 lParamType = lParamType.getUnqualifiedType(); 10112 rParamType = rParamType.getUnqualifiedType(); 10113 } 10114 10115 if (getCanonicalType(paramType) != getCanonicalType(lParamType)) 10116 allLTypes = false; 10117 if (getCanonicalType(paramType) != getCanonicalType(rParamType)) 10118 allRTypes = false; 10119 } 10120 10121 if (allLTypes) return lhs; 10122 if (allRTypes) return rhs; 10123 10124 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo(); 10125 EPI.ExtInfo = einfo; 10126 EPI.ExtParameterInfos = 10127 newParamInfos.empty() ? nullptr : newParamInfos.data(); 10128 return getFunctionType(retType, types, EPI); 10129 } 10130 10131 if (lproto) allRTypes = false; 10132 if (rproto) allLTypes = false; 10133 10134 const FunctionProtoType *proto = lproto ? lproto : rproto; 10135 if (proto) { 10136 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here"); 10137 if (proto->isVariadic()) 10138 return {}; 10139 // Check that the types are compatible with the types that 10140 // would result from default argument promotions (C99 6.7.5.3p15). 10141 // The only types actually affected are promotable integer 10142 // types and floats, which would be passed as a different 10143 // type depending on whether the prototype is visible. 10144 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) { 10145 QualType paramTy = proto->getParamType(i); 10146 10147 // Look at the converted type of enum types, since that is the type used 10148 // to pass enum values. 10149 if (const auto *Enum = paramTy->getAs<EnumType>()) { 10150 paramTy = Enum->getDecl()->getIntegerType(); 10151 if (paramTy.isNull()) 10152 return {}; 10153 } 10154 10155 if (paramTy->isPromotableIntegerType() || 10156 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy) 10157 return {}; 10158 } 10159 10160 if (allLTypes) return lhs; 10161 if (allRTypes) return rhs; 10162 10163 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo(); 10164 EPI.ExtInfo = einfo; 10165 return getFunctionType(retType, proto->getParamTypes(), EPI); 10166 } 10167 10168 if (allLTypes) return lhs; 10169 if (allRTypes) return rhs; 10170 return getFunctionNoProtoType(retType, einfo); 10171 } 10172 10173 /// Given that we have an enum type and a non-enum type, try to merge them. 10174 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET, 10175 QualType other, bool isBlockReturnType) { 10176 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char, 10177 // a signed integer type, or an unsigned integer type. 10178 // Compatibility is based on the underlying type, not the promotion 10179 // type. 10180 QualType underlyingType = ET->getDecl()->getIntegerType(); 10181 if (underlyingType.isNull()) 10182 return {}; 10183 if (Context.hasSameType(underlyingType, other)) 10184 return other; 10185 10186 // In block return types, we're more permissive and accept any 10187 // integral type of the same size. 10188 if (isBlockReturnType && other->isIntegerType() && 10189 Context.getTypeSize(underlyingType) == Context.getTypeSize(other)) 10190 return other; 10191 10192 return {}; 10193 } 10194 10195 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, 10196 bool OfBlockPointer, 10197 bool Unqualified, bool BlockReturnType) { 10198 // For C++ we will not reach this code with reference types (see below), 10199 // for OpenMP variant call overloading we might. 10200 // 10201 // C++ [expr]: If an expression initially has the type "reference to T", the 10202 // type is adjusted to "T" prior to any further analysis, the expression 10203 // designates the object or function denoted by the reference, and the 10204 // expression is an lvalue unless the reference is an rvalue reference and 10205 // the expression is a function call (possibly inside parentheses). 10206 auto *LHSRefTy = LHS->getAs<ReferenceType>(); 10207 auto *RHSRefTy = RHS->getAs<ReferenceType>(); 10208 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy && 10209 LHS->getTypeClass() == RHS->getTypeClass()) 10210 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(), 10211 OfBlockPointer, Unqualified, BlockReturnType); 10212 if (LHSRefTy || RHSRefTy) 10213 return {}; 10214 10215 if (Unqualified) { 10216 LHS = LHS.getUnqualifiedType(); 10217 RHS = RHS.getUnqualifiedType(); 10218 } 10219 10220 QualType LHSCan = getCanonicalType(LHS), 10221 RHSCan = getCanonicalType(RHS); 10222 10223 // If two types are identical, they are compatible. 10224 if (LHSCan == RHSCan) 10225 return LHS; 10226 10227 // If the qualifiers are different, the types aren't compatible... mostly. 10228 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 10229 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 10230 if (LQuals != RQuals) { 10231 // If any of these qualifiers are different, we have a type 10232 // mismatch. 10233 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 10234 LQuals.getAddressSpace() != RQuals.getAddressSpace() || 10235 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() || 10236 LQuals.hasUnaligned() != RQuals.hasUnaligned()) 10237 return {}; 10238 10239 // Exactly one GC qualifier difference is allowed: __strong is 10240 // okay if the other type has no GC qualifier but is an Objective 10241 // C object pointer (i.e. implicitly strong by default). We fix 10242 // this by pretending that the unqualified type was actually 10243 // qualified __strong. 10244 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 10245 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 10246 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 10247 10248 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 10249 return {}; 10250 10251 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) { 10252 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong)); 10253 } 10254 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) { 10255 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS); 10256 } 10257 return {}; 10258 } 10259 10260 // Okay, qualifiers are equal. 10261 10262 Type::TypeClass LHSClass = LHSCan->getTypeClass(); 10263 Type::TypeClass RHSClass = RHSCan->getTypeClass(); 10264 10265 // We want to consider the two function types to be the same for these 10266 // comparisons, just force one to the other. 10267 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto; 10268 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto; 10269 10270 // Same as above for arrays 10271 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray) 10272 LHSClass = Type::ConstantArray; 10273 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray) 10274 RHSClass = Type::ConstantArray; 10275 10276 // ObjCInterfaces are just specialized ObjCObjects. 10277 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject; 10278 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject; 10279 10280 // Canonicalize ExtVector -> Vector. 10281 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector; 10282 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector; 10283 10284 // If the canonical type classes don't match. 10285 if (LHSClass != RHSClass) { 10286 // Note that we only have special rules for turning block enum 10287 // returns into block int returns, not vice-versa. 10288 if (const auto *ETy = LHS->getAs<EnumType>()) { 10289 return mergeEnumWithInteger(*this, ETy, RHS, false); 10290 } 10291 if (const EnumType* ETy = RHS->getAs<EnumType>()) { 10292 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType); 10293 } 10294 // allow block pointer type to match an 'id' type. 10295 if (OfBlockPointer && !BlockReturnType) { 10296 if (LHS->isObjCIdType() && RHS->isBlockPointerType()) 10297 return LHS; 10298 if (RHS->isObjCIdType() && LHS->isBlockPointerType()) 10299 return RHS; 10300 } 10301 10302 return {}; 10303 } 10304 10305 // The canonical type classes match. 10306 switch (LHSClass) { 10307 #define TYPE(Class, Base) 10308 #define ABSTRACT_TYPE(Class, Base) 10309 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 10310 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 10311 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 10312 #include "clang/AST/TypeNodes.inc" 10313 llvm_unreachable("Non-canonical and dependent types shouldn't get here"); 10314 10315 case Type::Auto: 10316 case Type::DeducedTemplateSpecialization: 10317 case Type::LValueReference: 10318 case Type::RValueReference: 10319 case Type::MemberPointer: 10320 llvm_unreachable("C++ should never be in mergeTypes"); 10321 10322 case Type::ObjCInterface: 10323 case Type::IncompleteArray: 10324 case Type::VariableArray: 10325 case Type::FunctionProto: 10326 case Type::ExtVector: 10327 llvm_unreachable("Types are eliminated above"); 10328 10329 case Type::Pointer: 10330 { 10331 // Merge two pointer types, while trying to preserve typedef info 10332 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType(); 10333 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType(); 10334 if (Unqualified) { 10335 LHSPointee = LHSPointee.getUnqualifiedType(); 10336 RHSPointee = RHSPointee.getUnqualifiedType(); 10337 } 10338 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false, 10339 Unqualified); 10340 if (ResultType.isNull()) 10341 return {}; 10342 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 10343 return LHS; 10344 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 10345 return RHS; 10346 return getPointerType(ResultType); 10347 } 10348 case Type::BlockPointer: 10349 { 10350 // Merge two block pointer types, while trying to preserve typedef info 10351 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType(); 10352 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType(); 10353 if (Unqualified) { 10354 LHSPointee = LHSPointee.getUnqualifiedType(); 10355 RHSPointee = RHSPointee.getUnqualifiedType(); 10356 } 10357 if (getLangOpts().OpenCL) { 10358 Qualifiers LHSPteeQual = LHSPointee.getQualifiers(); 10359 Qualifiers RHSPteeQual = RHSPointee.getQualifiers(); 10360 // Blocks can't be an expression in a ternary operator (OpenCL v2.0 10361 // 6.12.5) thus the following check is asymmetric. 10362 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual)) 10363 return {}; 10364 LHSPteeQual.removeAddressSpace(); 10365 RHSPteeQual.removeAddressSpace(); 10366 LHSPointee = 10367 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue()); 10368 RHSPointee = 10369 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue()); 10370 } 10371 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer, 10372 Unqualified); 10373 if (ResultType.isNull()) 10374 return {}; 10375 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 10376 return LHS; 10377 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 10378 return RHS; 10379 return getBlockPointerType(ResultType); 10380 } 10381 case Type::Atomic: 10382 { 10383 // Merge two pointer types, while trying to preserve typedef info 10384 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType(); 10385 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType(); 10386 if (Unqualified) { 10387 LHSValue = LHSValue.getUnqualifiedType(); 10388 RHSValue = RHSValue.getUnqualifiedType(); 10389 } 10390 QualType ResultType = mergeTypes(LHSValue, RHSValue, false, 10391 Unqualified); 10392 if (ResultType.isNull()) 10393 return {}; 10394 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType)) 10395 return LHS; 10396 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType)) 10397 return RHS; 10398 return getAtomicType(ResultType); 10399 } 10400 case Type::ConstantArray: 10401 { 10402 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS); 10403 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS); 10404 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize()) 10405 return {}; 10406 10407 QualType LHSElem = getAsArrayType(LHS)->getElementType(); 10408 QualType RHSElem = getAsArrayType(RHS)->getElementType(); 10409 if (Unqualified) { 10410 LHSElem = LHSElem.getUnqualifiedType(); 10411 RHSElem = RHSElem.getUnqualifiedType(); 10412 } 10413 10414 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified); 10415 if (ResultType.isNull()) 10416 return {}; 10417 10418 const VariableArrayType* LVAT = getAsVariableArrayType(LHS); 10419 const VariableArrayType* RVAT = getAsVariableArrayType(RHS); 10420 10421 // If either side is a variable array, and both are complete, check whether 10422 // the current dimension is definite. 10423 if (LVAT || RVAT) { 10424 auto SizeFetch = [this](const VariableArrayType* VAT, 10425 const ConstantArrayType* CAT) 10426 -> std::pair<bool,llvm::APInt> { 10427 if (VAT) { 10428 Optional<llvm::APSInt> TheInt; 10429 Expr *E = VAT->getSizeExpr(); 10430 if (E && (TheInt = E->getIntegerConstantExpr(*this))) 10431 return std::make_pair(true, *TheInt); 10432 return std::make_pair(false, llvm::APSInt()); 10433 } 10434 if (CAT) 10435 return std::make_pair(true, CAT->getSize()); 10436 return std::make_pair(false, llvm::APInt()); 10437 }; 10438 10439 bool HaveLSize, HaveRSize; 10440 llvm::APInt LSize, RSize; 10441 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT); 10442 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT); 10443 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize)) 10444 return {}; // Definite, but unequal, array dimension 10445 } 10446 10447 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 10448 return LHS; 10449 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 10450 return RHS; 10451 if (LCAT) 10452 return getConstantArrayType(ResultType, LCAT->getSize(), 10453 LCAT->getSizeExpr(), 10454 ArrayType::ArraySizeModifier(), 0); 10455 if (RCAT) 10456 return getConstantArrayType(ResultType, RCAT->getSize(), 10457 RCAT->getSizeExpr(), 10458 ArrayType::ArraySizeModifier(), 0); 10459 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 10460 return LHS; 10461 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 10462 return RHS; 10463 if (LVAT) { 10464 // FIXME: This isn't correct! But tricky to implement because 10465 // the array's size has to be the size of LHS, but the type 10466 // has to be different. 10467 return LHS; 10468 } 10469 if (RVAT) { 10470 // FIXME: This isn't correct! But tricky to implement because 10471 // the array's size has to be the size of RHS, but the type 10472 // has to be different. 10473 return RHS; 10474 } 10475 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS; 10476 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS; 10477 return getIncompleteArrayType(ResultType, 10478 ArrayType::ArraySizeModifier(), 0); 10479 } 10480 case Type::FunctionNoProto: 10481 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified); 10482 case Type::Record: 10483 case Type::Enum: 10484 return {}; 10485 case Type::Builtin: 10486 // Only exactly equal builtin types are compatible, which is tested above. 10487 return {}; 10488 case Type::Complex: 10489 // Distinct complex types are incompatible. 10490 return {}; 10491 case Type::Vector: 10492 // FIXME: The merged type should be an ExtVector! 10493 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(), 10494 RHSCan->castAs<VectorType>())) 10495 return LHS; 10496 return {}; 10497 case Type::ConstantMatrix: 10498 if (areCompatMatrixTypes(LHSCan->castAs<ConstantMatrixType>(), 10499 RHSCan->castAs<ConstantMatrixType>())) 10500 return LHS; 10501 return {}; 10502 case Type::ObjCObject: { 10503 // Check if the types are assignment compatible. 10504 // FIXME: This should be type compatibility, e.g. whether 10505 // "LHS x; RHS x;" at global scope is legal. 10506 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectType>(), 10507 RHS->castAs<ObjCObjectType>())) 10508 return LHS; 10509 return {}; 10510 } 10511 case Type::ObjCObjectPointer: 10512 if (OfBlockPointer) { 10513 if (canAssignObjCInterfacesInBlockPointer( 10514 LHS->castAs<ObjCObjectPointerType>(), 10515 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType)) 10516 return LHS; 10517 return {}; 10518 } 10519 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectPointerType>(), 10520 RHS->castAs<ObjCObjectPointerType>())) 10521 return LHS; 10522 return {}; 10523 case Type::Pipe: 10524 assert(LHS != RHS && 10525 "Equivalent pipe types should have already been handled!"); 10526 return {}; 10527 case Type::BitInt: { 10528 // Merge two bit-precise int types, while trying to preserve typedef info. 10529 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned(); 10530 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned(); 10531 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits(); 10532 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits(); 10533 10534 // Like unsigned/int, shouldn't have a type if they don't match. 10535 if (LHSUnsigned != RHSUnsigned) 10536 return {}; 10537 10538 if (LHSBits != RHSBits) 10539 return {}; 10540 return LHS; 10541 } 10542 } 10543 10544 llvm_unreachable("Invalid Type::Class!"); 10545 } 10546 10547 bool ASTContext::mergeExtParameterInfo( 10548 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType, 10549 bool &CanUseFirst, bool &CanUseSecond, 10550 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) { 10551 assert(NewParamInfos.empty() && "param info list not empty"); 10552 CanUseFirst = CanUseSecond = true; 10553 bool FirstHasInfo = FirstFnType->hasExtParameterInfos(); 10554 bool SecondHasInfo = SecondFnType->hasExtParameterInfos(); 10555 10556 // Fast path: if the first type doesn't have ext parameter infos, 10557 // we match if and only if the second type also doesn't have them. 10558 if (!FirstHasInfo && !SecondHasInfo) 10559 return true; 10560 10561 bool NeedParamInfo = false; 10562 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size() 10563 : SecondFnType->getExtParameterInfos().size(); 10564 10565 for (size_t I = 0; I < E; ++I) { 10566 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam; 10567 if (FirstHasInfo) 10568 FirstParam = FirstFnType->getExtParameterInfo(I); 10569 if (SecondHasInfo) 10570 SecondParam = SecondFnType->getExtParameterInfo(I); 10571 10572 // Cannot merge unless everything except the noescape flag matches. 10573 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false)) 10574 return false; 10575 10576 bool FirstNoEscape = FirstParam.isNoEscape(); 10577 bool SecondNoEscape = SecondParam.isNoEscape(); 10578 bool IsNoEscape = FirstNoEscape && SecondNoEscape; 10579 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape)); 10580 if (NewParamInfos.back().getOpaqueValue()) 10581 NeedParamInfo = true; 10582 if (FirstNoEscape != IsNoEscape) 10583 CanUseFirst = false; 10584 if (SecondNoEscape != IsNoEscape) 10585 CanUseSecond = false; 10586 } 10587 10588 if (!NeedParamInfo) 10589 NewParamInfos.clear(); 10590 10591 return true; 10592 } 10593 10594 void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) { 10595 ObjCLayouts[CD] = nullptr; 10596 } 10597 10598 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 10599 /// 'RHS' attributes and returns the merged version; including for function 10600 /// return types. 10601 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) { 10602 QualType LHSCan = getCanonicalType(LHS), 10603 RHSCan = getCanonicalType(RHS); 10604 // If two types are identical, they are compatible. 10605 if (LHSCan == RHSCan) 10606 return LHS; 10607 if (RHSCan->isFunctionType()) { 10608 if (!LHSCan->isFunctionType()) 10609 return {}; 10610 QualType OldReturnType = 10611 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType(); 10612 QualType NewReturnType = 10613 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType(); 10614 QualType ResReturnType = 10615 mergeObjCGCQualifiers(NewReturnType, OldReturnType); 10616 if (ResReturnType.isNull()) 10617 return {}; 10618 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) { 10619 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo(); 10620 // In either case, use OldReturnType to build the new function type. 10621 const auto *F = LHS->castAs<FunctionType>(); 10622 if (const auto *FPT = cast<FunctionProtoType>(F)) { 10623 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10624 EPI.ExtInfo = getFunctionExtInfo(LHS); 10625 QualType ResultType = 10626 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI); 10627 return ResultType; 10628 } 10629 } 10630 return {}; 10631 } 10632 10633 // If the qualifiers are different, the types can still be merged. 10634 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 10635 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 10636 if (LQuals != RQuals) { 10637 // If any of these qualifiers are different, we have a type mismatch. 10638 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 10639 LQuals.getAddressSpace() != RQuals.getAddressSpace()) 10640 return {}; 10641 10642 // Exactly one GC qualifier difference is allowed: __strong is 10643 // okay if the other type has no GC qualifier but is an Objective 10644 // C object pointer (i.e. implicitly strong by default). We fix 10645 // this by pretending that the unqualified type was actually 10646 // qualified __strong. 10647 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 10648 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 10649 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 10650 10651 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 10652 return {}; 10653 10654 if (GC_L == Qualifiers::Strong) 10655 return LHS; 10656 if (GC_R == Qualifiers::Strong) 10657 return RHS; 10658 return {}; 10659 } 10660 10661 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) { 10662 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType(); 10663 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType(); 10664 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT); 10665 if (ResQT == LHSBaseQT) 10666 return LHS; 10667 if (ResQT == RHSBaseQT) 10668 return RHS; 10669 } 10670 return {}; 10671 } 10672 10673 //===----------------------------------------------------------------------===// 10674 // Integer Predicates 10675 //===----------------------------------------------------------------------===// 10676 10677 unsigned ASTContext::getIntWidth(QualType T) const { 10678 if (const auto *ET = T->getAs<EnumType>()) 10679 T = ET->getDecl()->getIntegerType(); 10680 if (T->isBooleanType()) 10681 return 1; 10682 if (const auto *EIT = T->getAs<BitIntType>()) 10683 return EIT->getNumBits(); 10684 // For builtin types, just use the standard type sizing method 10685 return (unsigned)getTypeSize(T); 10686 } 10687 10688 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const { 10689 assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) && 10690 "Unexpected type"); 10691 10692 // Turn <4 x signed int> -> <4 x unsigned int> 10693 if (const auto *VTy = T->getAs<VectorType>()) 10694 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()), 10695 VTy->getNumElements(), VTy->getVectorKind()); 10696 10697 // For _BitInt, return an unsigned _BitInt with same width. 10698 if (const auto *EITy = T->getAs<BitIntType>()) 10699 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits()); 10700 10701 // For enums, get the underlying integer type of the enum, and let the general 10702 // integer type signchanging code handle it. 10703 if (const auto *ETy = T->getAs<EnumType>()) 10704 T = ETy->getDecl()->getIntegerType(); 10705 10706 switch (T->castAs<BuiltinType>()->getKind()) { 10707 case BuiltinType::Char_S: 10708 case BuiltinType::SChar: 10709 return UnsignedCharTy; 10710 case BuiltinType::Short: 10711 return UnsignedShortTy; 10712 case BuiltinType::Int: 10713 return UnsignedIntTy; 10714 case BuiltinType::Long: 10715 return UnsignedLongTy; 10716 case BuiltinType::LongLong: 10717 return UnsignedLongLongTy; 10718 case BuiltinType::Int128: 10719 return UnsignedInt128Ty; 10720 // wchar_t is special. It is either signed or not, but when it's signed, 10721 // there's no matching "unsigned wchar_t". Therefore we return the unsigned 10722 // version of it's underlying type instead. 10723 case BuiltinType::WChar_S: 10724 return getUnsignedWCharType(); 10725 10726 case BuiltinType::ShortAccum: 10727 return UnsignedShortAccumTy; 10728 case BuiltinType::Accum: 10729 return UnsignedAccumTy; 10730 case BuiltinType::LongAccum: 10731 return UnsignedLongAccumTy; 10732 case BuiltinType::SatShortAccum: 10733 return SatUnsignedShortAccumTy; 10734 case BuiltinType::SatAccum: 10735 return SatUnsignedAccumTy; 10736 case BuiltinType::SatLongAccum: 10737 return SatUnsignedLongAccumTy; 10738 case BuiltinType::ShortFract: 10739 return UnsignedShortFractTy; 10740 case BuiltinType::Fract: 10741 return UnsignedFractTy; 10742 case BuiltinType::LongFract: 10743 return UnsignedLongFractTy; 10744 case BuiltinType::SatShortFract: 10745 return SatUnsignedShortFractTy; 10746 case BuiltinType::SatFract: 10747 return SatUnsignedFractTy; 10748 case BuiltinType::SatLongFract: 10749 return SatUnsignedLongFractTy; 10750 default: 10751 llvm_unreachable("Unexpected signed integer or fixed point type"); 10752 } 10753 } 10754 10755 QualType ASTContext::getCorrespondingSignedType(QualType T) const { 10756 assert((T->hasUnsignedIntegerRepresentation() || 10757 T->isUnsignedFixedPointType()) && 10758 "Unexpected type"); 10759 10760 // Turn <4 x unsigned int> -> <4 x signed int> 10761 if (const auto *VTy = T->getAs<VectorType>()) 10762 return getVectorType(getCorrespondingSignedType(VTy->getElementType()), 10763 VTy->getNumElements(), VTy->getVectorKind()); 10764 10765 // For _BitInt, return a signed _BitInt with same width. 10766 if (const auto *EITy = T->getAs<BitIntType>()) 10767 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits()); 10768 10769 // For enums, get the underlying integer type of the enum, and let the general 10770 // integer type signchanging code handle it. 10771 if (const auto *ETy = T->getAs<EnumType>()) 10772 T = ETy->getDecl()->getIntegerType(); 10773 10774 switch (T->castAs<BuiltinType>()->getKind()) { 10775 case BuiltinType::Char_U: 10776 case BuiltinType::UChar: 10777 return SignedCharTy; 10778 case BuiltinType::UShort: 10779 return ShortTy; 10780 case BuiltinType::UInt: 10781 return IntTy; 10782 case BuiltinType::ULong: 10783 return LongTy; 10784 case BuiltinType::ULongLong: 10785 return LongLongTy; 10786 case BuiltinType::UInt128: 10787 return Int128Ty; 10788 // wchar_t is special. It is either unsigned or not, but when it's unsigned, 10789 // there's no matching "signed wchar_t". Therefore we return the signed 10790 // version of it's underlying type instead. 10791 case BuiltinType::WChar_U: 10792 return getSignedWCharType(); 10793 10794 case BuiltinType::UShortAccum: 10795 return ShortAccumTy; 10796 case BuiltinType::UAccum: 10797 return AccumTy; 10798 case BuiltinType::ULongAccum: 10799 return LongAccumTy; 10800 case BuiltinType::SatUShortAccum: 10801 return SatShortAccumTy; 10802 case BuiltinType::SatUAccum: 10803 return SatAccumTy; 10804 case BuiltinType::SatULongAccum: 10805 return SatLongAccumTy; 10806 case BuiltinType::UShortFract: 10807 return ShortFractTy; 10808 case BuiltinType::UFract: 10809 return FractTy; 10810 case BuiltinType::ULongFract: 10811 return LongFractTy; 10812 case BuiltinType::SatUShortFract: 10813 return SatShortFractTy; 10814 case BuiltinType::SatUFract: 10815 return SatFractTy; 10816 case BuiltinType::SatULongFract: 10817 return SatLongFractTy; 10818 default: 10819 llvm_unreachable("Unexpected unsigned integer or fixed point type"); 10820 } 10821 } 10822 10823 ASTMutationListener::~ASTMutationListener() = default; 10824 10825 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD, 10826 QualType ReturnType) {} 10827 10828 //===----------------------------------------------------------------------===// 10829 // Builtin Type Computation 10830 //===----------------------------------------------------------------------===// 10831 10832 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the 10833 /// pointer over the consumed characters. This returns the resultant type. If 10834 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic 10835 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of 10836 /// a vector of "i*". 10837 /// 10838 /// RequiresICE is filled in on return to indicate whether the value is required 10839 /// to be an Integer Constant Expression. 10840 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, 10841 ASTContext::GetBuiltinTypeError &Error, 10842 bool &RequiresICE, 10843 bool AllowTypeModifiers) { 10844 // Modifiers. 10845 int HowLong = 0; 10846 bool Signed = false, Unsigned = false; 10847 RequiresICE = false; 10848 10849 // Read the prefixed modifiers first. 10850 bool Done = false; 10851 #ifndef NDEBUG 10852 bool IsSpecial = false; 10853 #endif 10854 while (!Done) { 10855 switch (*Str++) { 10856 default: Done = true; --Str; break; 10857 case 'I': 10858 RequiresICE = true; 10859 break; 10860 case 'S': 10861 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!"); 10862 assert(!Signed && "Can't use 'S' modifier multiple times!"); 10863 Signed = true; 10864 break; 10865 case 'U': 10866 assert(!Signed && "Can't use both 'S' and 'U' modifiers!"); 10867 assert(!Unsigned && "Can't use 'U' modifier multiple times!"); 10868 Unsigned = true; 10869 break; 10870 case 'L': 10871 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers"); 10872 assert(HowLong <= 2 && "Can't have LLLL modifier"); 10873 ++HowLong; 10874 break; 10875 case 'N': 10876 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise. 10877 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10878 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!"); 10879 #ifndef NDEBUG 10880 IsSpecial = true; 10881 #endif 10882 if (Context.getTargetInfo().getLongWidth() == 32) 10883 ++HowLong; 10884 break; 10885 case 'W': 10886 // This modifier represents int64 type. 10887 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10888 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!"); 10889 #ifndef NDEBUG 10890 IsSpecial = true; 10891 #endif 10892 switch (Context.getTargetInfo().getInt64Type()) { 10893 default: 10894 llvm_unreachable("Unexpected integer type"); 10895 case TargetInfo::SignedLong: 10896 HowLong = 1; 10897 break; 10898 case TargetInfo::SignedLongLong: 10899 HowLong = 2; 10900 break; 10901 } 10902 break; 10903 case 'Z': 10904 // This modifier represents int32 type. 10905 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10906 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!"); 10907 #ifndef NDEBUG 10908 IsSpecial = true; 10909 #endif 10910 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) { 10911 default: 10912 llvm_unreachable("Unexpected integer type"); 10913 case TargetInfo::SignedInt: 10914 HowLong = 0; 10915 break; 10916 case TargetInfo::SignedLong: 10917 HowLong = 1; 10918 break; 10919 case TargetInfo::SignedLongLong: 10920 HowLong = 2; 10921 break; 10922 } 10923 break; 10924 case 'O': 10925 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10926 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!"); 10927 #ifndef NDEBUG 10928 IsSpecial = true; 10929 #endif 10930 if (Context.getLangOpts().OpenCL) 10931 HowLong = 1; 10932 else 10933 HowLong = 2; 10934 break; 10935 } 10936 } 10937 10938 QualType Type; 10939 10940 // Read the base type. 10941 switch (*Str++) { 10942 default: llvm_unreachable("Unknown builtin type letter!"); 10943 case 'x': 10944 assert(HowLong == 0 && !Signed && !Unsigned && 10945 "Bad modifiers used with 'x'!"); 10946 Type = Context.Float16Ty; 10947 break; 10948 case 'y': 10949 assert(HowLong == 0 && !Signed && !Unsigned && 10950 "Bad modifiers used with 'y'!"); 10951 Type = Context.BFloat16Ty; 10952 break; 10953 case 'v': 10954 assert(HowLong == 0 && !Signed && !Unsigned && 10955 "Bad modifiers used with 'v'!"); 10956 Type = Context.VoidTy; 10957 break; 10958 case 'h': 10959 assert(HowLong == 0 && !Signed && !Unsigned && 10960 "Bad modifiers used with 'h'!"); 10961 Type = Context.HalfTy; 10962 break; 10963 case 'f': 10964 assert(HowLong == 0 && !Signed && !Unsigned && 10965 "Bad modifiers used with 'f'!"); 10966 Type = Context.FloatTy; 10967 break; 10968 case 'd': 10969 assert(HowLong < 3 && !Signed && !Unsigned && 10970 "Bad modifiers used with 'd'!"); 10971 if (HowLong == 1) 10972 Type = Context.LongDoubleTy; 10973 else if (HowLong == 2) 10974 Type = Context.Float128Ty; 10975 else 10976 Type = Context.DoubleTy; 10977 break; 10978 case 's': 10979 assert(HowLong == 0 && "Bad modifiers used with 's'!"); 10980 if (Unsigned) 10981 Type = Context.UnsignedShortTy; 10982 else 10983 Type = Context.ShortTy; 10984 break; 10985 case 'i': 10986 if (HowLong == 3) 10987 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty; 10988 else if (HowLong == 2) 10989 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy; 10990 else if (HowLong == 1) 10991 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy; 10992 else 10993 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy; 10994 break; 10995 case 'c': 10996 assert(HowLong == 0 && "Bad modifiers used with 'c'!"); 10997 if (Signed) 10998 Type = Context.SignedCharTy; 10999 else if (Unsigned) 11000 Type = Context.UnsignedCharTy; 11001 else 11002 Type = Context.CharTy; 11003 break; 11004 case 'b': // boolean 11005 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!"); 11006 Type = Context.BoolTy; 11007 break; 11008 case 'z': // size_t. 11009 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!"); 11010 Type = Context.getSizeType(); 11011 break; 11012 case 'w': // wchar_t. 11013 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!"); 11014 Type = Context.getWideCharType(); 11015 break; 11016 case 'F': 11017 Type = Context.getCFConstantStringType(); 11018 break; 11019 case 'G': 11020 Type = Context.getObjCIdType(); 11021 break; 11022 case 'H': 11023 Type = Context.getObjCSelType(); 11024 break; 11025 case 'M': 11026 Type = Context.getObjCSuperType(); 11027 break; 11028 case 'a': 11029 Type = Context.getBuiltinVaListType(); 11030 assert(!Type.isNull() && "builtin va list type not initialized!"); 11031 break; 11032 case 'A': 11033 // This is a "reference" to a va_list; however, what exactly 11034 // this means depends on how va_list is defined. There are two 11035 // different kinds of va_list: ones passed by value, and ones 11036 // passed by reference. An example of a by-value va_list is 11037 // x86, where va_list is a char*. An example of by-ref va_list 11038 // is x86-64, where va_list is a __va_list_tag[1]. For x86, 11039 // we want this argument to be a char*&; for x86-64, we want 11040 // it to be a __va_list_tag*. 11041 Type = Context.getBuiltinVaListType(); 11042 assert(!Type.isNull() && "builtin va list type not initialized!"); 11043 if (Type->isArrayType()) 11044 Type = Context.getArrayDecayedType(Type); 11045 else 11046 Type = Context.getLValueReferenceType(Type); 11047 break; 11048 case 'q': { 11049 char *End; 11050 unsigned NumElements = strtoul(Str, &End, 10); 11051 assert(End != Str && "Missing vector size"); 11052 Str = End; 11053 11054 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 11055 RequiresICE, false); 11056 assert(!RequiresICE && "Can't require vector ICE"); 11057 11058 Type = Context.getScalableVectorType(ElementType, NumElements); 11059 break; 11060 } 11061 case 'V': { 11062 char *End; 11063 unsigned NumElements = strtoul(Str, &End, 10); 11064 assert(End != Str && "Missing vector size"); 11065 Str = End; 11066 11067 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 11068 RequiresICE, false); 11069 assert(!RequiresICE && "Can't require vector ICE"); 11070 11071 // TODO: No way to make AltiVec vectors in builtins yet. 11072 Type = Context.getVectorType(ElementType, NumElements, 11073 VectorType::GenericVector); 11074 break; 11075 } 11076 case 'E': { 11077 char *End; 11078 11079 unsigned NumElements = strtoul(Str, &End, 10); 11080 assert(End != Str && "Missing vector size"); 11081 11082 Str = End; 11083 11084 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 11085 false); 11086 Type = Context.getExtVectorType(ElementType, NumElements); 11087 break; 11088 } 11089 case 'X': { 11090 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 11091 false); 11092 assert(!RequiresICE && "Can't require complex ICE"); 11093 Type = Context.getComplexType(ElementType); 11094 break; 11095 } 11096 case 'Y': 11097 Type = Context.getPointerDiffType(); 11098 break; 11099 case 'P': 11100 Type = Context.getFILEType(); 11101 if (Type.isNull()) { 11102 Error = ASTContext::GE_Missing_stdio; 11103 return {}; 11104 } 11105 break; 11106 case 'J': 11107 if (Signed) 11108 Type = Context.getsigjmp_bufType(); 11109 else 11110 Type = Context.getjmp_bufType(); 11111 11112 if (Type.isNull()) { 11113 Error = ASTContext::GE_Missing_setjmp; 11114 return {}; 11115 } 11116 break; 11117 case 'K': 11118 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!"); 11119 Type = Context.getucontext_tType(); 11120 11121 if (Type.isNull()) { 11122 Error = ASTContext::GE_Missing_ucontext; 11123 return {}; 11124 } 11125 break; 11126 case 'p': 11127 Type = Context.getProcessIDType(); 11128 break; 11129 } 11130 11131 // If there are modifiers and if we're allowed to parse them, go for it. 11132 Done = !AllowTypeModifiers; 11133 while (!Done) { 11134 switch (char c = *Str++) { 11135 default: Done = true; --Str; break; 11136 case '*': 11137 case '&': { 11138 // Both pointers and references can have their pointee types 11139 // qualified with an address space. 11140 char *End; 11141 unsigned AddrSpace = strtoul(Str, &End, 10); 11142 if (End != Str) { 11143 // Note AddrSpace == 0 is not the same as an unspecified address space. 11144 Type = Context.getAddrSpaceQualType( 11145 Type, 11146 Context.getLangASForBuiltinAddressSpace(AddrSpace)); 11147 Str = End; 11148 } 11149 if (c == '*') 11150 Type = Context.getPointerType(Type); 11151 else 11152 Type = Context.getLValueReferenceType(Type); 11153 break; 11154 } 11155 // FIXME: There's no way to have a built-in with an rvalue ref arg. 11156 case 'C': 11157 Type = Type.withConst(); 11158 break; 11159 case 'D': 11160 Type = Context.getVolatileType(Type); 11161 break; 11162 case 'R': 11163 Type = Type.withRestrict(); 11164 break; 11165 } 11166 } 11167 11168 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) && 11169 "Integer constant 'I' type must be an integer"); 11170 11171 return Type; 11172 } 11173 11174 // On some targets such as PowerPC, some of the builtins are defined with custom 11175 // type descriptors for target-dependent types. These descriptors are decoded in 11176 // other functions, but it may be useful to be able to fall back to default 11177 // descriptor decoding to define builtins mixing target-dependent and target- 11178 // independent types. This function allows decoding one type descriptor with 11179 // default decoding. 11180 QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context, 11181 GetBuiltinTypeError &Error, bool &RequireICE, 11182 bool AllowTypeModifiers) const { 11183 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers); 11184 } 11185 11186 /// GetBuiltinType - Return the type for the specified builtin. 11187 QualType ASTContext::GetBuiltinType(unsigned Id, 11188 GetBuiltinTypeError &Error, 11189 unsigned *IntegerConstantArgs) const { 11190 const char *TypeStr = BuiltinInfo.getTypeString(Id); 11191 if (TypeStr[0] == '\0') { 11192 Error = GE_Missing_type; 11193 return {}; 11194 } 11195 11196 SmallVector<QualType, 8> ArgTypes; 11197 11198 bool RequiresICE = false; 11199 Error = GE_None; 11200 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error, 11201 RequiresICE, true); 11202 if (Error != GE_None) 11203 return {}; 11204 11205 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE"); 11206 11207 while (TypeStr[0] && TypeStr[0] != '.') { 11208 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true); 11209 if (Error != GE_None) 11210 return {}; 11211 11212 // If this argument is required to be an IntegerConstantExpression and the 11213 // caller cares, fill in the bitmask we return. 11214 if (RequiresICE && IntegerConstantArgs) 11215 *IntegerConstantArgs |= 1 << ArgTypes.size(); 11216 11217 // Do array -> pointer decay. The builtin should use the decayed type. 11218 if (Ty->isArrayType()) 11219 Ty = getArrayDecayedType(Ty); 11220 11221 ArgTypes.push_back(Ty); 11222 } 11223 11224 if (Id == Builtin::BI__GetExceptionInfo) 11225 return {}; 11226 11227 assert((TypeStr[0] != '.' || TypeStr[1] == 0) && 11228 "'.' should only occur at end of builtin type list!"); 11229 11230 bool Variadic = (TypeStr[0] == '.'); 11231 11232 FunctionType::ExtInfo EI(getDefaultCallingConvention( 11233 Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true)); 11234 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true); 11235 11236 11237 // We really shouldn't be making a no-proto type here. 11238 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus) 11239 return getFunctionNoProtoType(ResType, EI); 11240 11241 FunctionProtoType::ExtProtoInfo EPI; 11242 EPI.ExtInfo = EI; 11243 EPI.Variadic = Variadic; 11244 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id)) 11245 EPI.ExceptionSpec.Type = 11246 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone; 11247 11248 return getFunctionType(ResType, ArgTypes, EPI); 11249 } 11250 11251 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, 11252 const FunctionDecl *FD) { 11253 if (!FD->isExternallyVisible()) 11254 return GVA_Internal; 11255 11256 // Non-user-provided functions get emitted as weak definitions with every 11257 // use, no matter whether they've been explicitly instantiated etc. 11258 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 11259 if (!MD->isUserProvided()) 11260 return GVA_DiscardableODR; 11261 11262 GVALinkage External; 11263 switch (FD->getTemplateSpecializationKind()) { 11264 case TSK_Undeclared: 11265 case TSK_ExplicitSpecialization: 11266 External = GVA_StrongExternal; 11267 break; 11268 11269 case TSK_ExplicitInstantiationDefinition: 11270 return GVA_StrongODR; 11271 11272 // C++11 [temp.explicit]p10: 11273 // [ Note: The intent is that an inline function that is the subject of 11274 // an explicit instantiation declaration will still be implicitly 11275 // instantiated when used so that the body can be considered for 11276 // inlining, but that no out-of-line copy of the inline function would be 11277 // generated in the translation unit. -- end note ] 11278 case TSK_ExplicitInstantiationDeclaration: 11279 return GVA_AvailableExternally; 11280 11281 case TSK_ImplicitInstantiation: 11282 External = GVA_DiscardableODR; 11283 break; 11284 } 11285 11286 if (!FD->isInlined()) 11287 return External; 11288 11289 if ((!Context.getLangOpts().CPlusPlus && 11290 !Context.getTargetInfo().getCXXABI().isMicrosoft() && 11291 !FD->hasAttr<DLLExportAttr>()) || 11292 FD->hasAttr<GNUInlineAttr>()) { 11293 // FIXME: This doesn't match gcc's behavior for dllexport inline functions. 11294 11295 // GNU or C99 inline semantics. Determine whether this symbol should be 11296 // externally visible. 11297 if (FD->isInlineDefinitionExternallyVisible()) 11298 return External; 11299 11300 // C99 inline semantics, where the symbol is not externally visible. 11301 return GVA_AvailableExternally; 11302 } 11303 11304 // Functions specified with extern and inline in -fms-compatibility mode 11305 // forcibly get emitted. While the body of the function cannot be later 11306 // replaced, the function definition cannot be discarded. 11307 if (FD->isMSExternInline()) 11308 return GVA_StrongODR; 11309 11310 return GVA_DiscardableODR; 11311 } 11312 11313 static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context, 11314 const Decl *D, GVALinkage L) { 11315 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx 11316 // dllexport/dllimport on inline functions. 11317 if (D->hasAttr<DLLImportAttr>()) { 11318 if (L == GVA_DiscardableODR || L == GVA_StrongODR) 11319 return GVA_AvailableExternally; 11320 } else if (D->hasAttr<DLLExportAttr>()) { 11321 if (L == GVA_DiscardableODR) 11322 return GVA_StrongODR; 11323 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) { 11324 // Device-side functions with __global__ attribute must always be 11325 // visible externally so they can be launched from host. 11326 if (D->hasAttr<CUDAGlobalAttr>() && 11327 (L == GVA_DiscardableODR || L == GVA_Internal)) 11328 return GVA_StrongODR; 11329 // Single source offloading languages like CUDA/HIP need to be able to 11330 // access static device variables from host code of the same compilation 11331 // unit. This is done by externalizing the static variable with a shared 11332 // name between the host and device compilation which is the same for the 11333 // same compilation unit whereas different among different compilation 11334 // units. 11335 if (Context.shouldExternalizeStaticVar(D)) 11336 return GVA_StrongExternal; 11337 } 11338 return L; 11339 } 11340 11341 /// Adjust the GVALinkage for a declaration based on what an external AST source 11342 /// knows about whether there can be other definitions of this declaration. 11343 static GVALinkage 11344 adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D, 11345 GVALinkage L) { 11346 ExternalASTSource *Source = Ctx.getExternalSource(); 11347 if (!Source) 11348 return L; 11349 11350 switch (Source->hasExternalDefinitions(D)) { 11351 case ExternalASTSource::EK_Never: 11352 // Other translation units rely on us to provide the definition. 11353 if (L == GVA_DiscardableODR) 11354 return GVA_StrongODR; 11355 break; 11356 11357 case ExternalASTSource::EK_Always: 11358 return GVA_AvailableExternally; 11359 11360 case ExternalASTSource::EK_ReplyHazy: 11361 break; 11362 } 11363 return L; 11364 } 11365 11366 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const { 11367 return adjustGVALinkageForExternalDefinitionKind(*this, FD, 11368 adjustGVALinkageForAttributes(*this, FD, 11369 basicGVALinkageForFunction(*this, FD))); 11370 } 11371 11372 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context, 11373 const VarDecl *VD) { 11374 if (!VD->isExternallyVisible()) 11375 return GVA_Internal; 11376 11377 if (VD->isStaticLocal()) { 11378 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod(); 11379 while (LexicalContext && !isa<FunctionDecl>(LexicalContext)) 11380 LexicalContext = LexicalContext->getLexicalParent(); 11381 11382 // ObjC Blocks can create local variables that don't have a FunctionDecl 11383 // LexicalContext. 11384 if (!LexicalContext) 11385 return GVA_DiscardableODR; 11386 11387 // Otherwise, let the static local variable inherit its linkage from the 11388 // nearest enclosing function. 11389 auto StaticLocalLinkage = 11390 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext)); 11391 11392 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must 11393 // be emitted in any object with references to the symbol for the object it 11394 // contains, whether inline or out-of-line." 11395 // Similar behavior is observed with MSVC. An alternative ABI could use 11396 // StrongODR/AvailableExternally to match the function, but none are 11397 // known/supported currently. 11398 if (StaticLocalLinkage == GVA_StrongODR || 11399 StaticLocalLinkage == GVA_AvailableExternally) 11400 return GVA_DiscardableODR; 11401 return StaticLocalLinkage; 11402 } 11403 11404 // MSVC treats in-class initialized static data members as definitions. 11405 // By giving them non-strong linkage, out-of-line definitions won't 11406 // cause link errors. 11407 if (Context.isMSStaticDataMemberInlineDefinition(VD)) 11408 return GVA_DiscardableODR; 11409 11410 // Most non-template variables have strong linkage; inline variables are 11411 // linkonce_odr or (occasionally, for compatibility) weak_odr. 11412 GVALinkage StrongLinkage; 11413 switch (Context.getInlineVariableDefinitionKind(VD)) { 11414 case ASTContext::InlineVariableDefinitionKind::None: 11415 StrongLinkage = GVA_StrongExternal; 11416 break; 11417 case ASTContext::InlineVariableDefinitionKind::Weak: 11418 case ASTContext::InlineVariableDefinitionKind::WeakUnknown: 11419 StrongLinkage = GVA_DiscardableODR; 11420 break; 11421 case ASTContext::InlineVariableDefinitionKind::Strong: 11422 StrongLinkage = GVA_StrongODR; 11423 break; 11424 } 11425 11426 switch (VD->getTemplateSpecializationKind()) { 11427 case TSK_Undeclared: 11428 return StrongLinkage; 11429 11430 case TSK_ExplicitSpecialization: 11431 return Context.getTargetInfo().getCXXABI().isMicrosoft() && 11432 VD->isStaticDataMember() 11433 ? GVA_StrongODR 11434 : StrongLinkage; 11435 11436 case TSK_ExplicitInstantiationDefinition: 11437 return GVA_StrongODR; 11438 11439 case TSK_ExplicitInstantiationDeclaration: 11440 return GVA_AvailableExternally; 11441 11442 case TSK_ImplicitInstantiation: 11443 return GVA_DiscardableODR; 11444 } 11445 11446 llvm_unreachable("Invalid Linkage!"); 11447 } 11448 11449 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) { 11450 return adjustGVALinkageForExternalDefinitionKind(*this, VD, 11451 adjustGVALinkageForAttributes(*this, VD, 11452 basicGVALinkageForVariable(*this, VD))); 11453 } 11454 11455 bool ASTContext::DeclMustBeEmitted(const Decl *D) { 11456 if (const auto *VD = dyn_cast<VarDecl>(D)) { 11457 if (!VD->isFileVarDecl()) 11458 return false; 11459 // Global named register variables (GNU extension) are never emitted. 11460 if (VD->getStorageClass() == SC_Register) 11461 return false; 11462 if (VD->getDescribedVarTemplate() || 11463 isa<VarTemplatePartialSpecializationDecl>(VD)) 11464 return false; 11465 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 11466 // We never need to emit an uninstantiated function template. 11467 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 11468 return false; 11469 } else if (isa<PragmaCommentDecl>(D)) 11470 return true; 11471 else if (isa<PragmaDetectMismatchDecl>(D)) 11472 return true; 11473 else if (isa<OMPRequiresDecl>(D)) 11474 return true; 11475 else if (isa<OMPThreadPrivateDecl>(D)) 11476 return !D->getDeclContext()->isDependentContext(); 11477 else if (isa<OMPAllocateDecl>(D)) 11478 return !D->getDeclContext()->isDependentContext(); 11479 else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D)) 11480 return !D->getDeclContext()->isDependentContext(); 11481 else if (isa<ImportDecl>(D)) 11482 return true; 11483 else 11484 return false; 11485 11486 // If this is a member of a class template, we do not need to emit it. 11487 if (D->getDeclContext()->isDependentContext()) 11488 return false; 11489 11490 // Weak references don't produce any output by themselves. 11491 if (D->hasAttr<WeakRefAttr>()) 11492 return false; 11493 11494 // Aliases and used decls are required. 11495 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>()) 11496 return true; 11497 11498 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 11499 // Forward declarations aren't required. 11500 if (!FD->doesThisDeclarationHaveABody()) 11501 return FD->doesDeclarationForceExternallyVisibleDefinition(); 11502 11503 // Constructors and destructors are required. 11504 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>()) 11505 return true; 11506 11507 // The key function for a class is required. This rule only comes 11508 // into play when inline functions can be key functions, though. 11509 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 11510 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 11511 const CXXRecordDecl *RD = MD->getParent(); 11512 if (MD->isOutOfLine() && RD->isDynamicClass()) { 11513 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD); 11514 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl()) 11515 return true; 11516 } 11517 } 11518 } 11519 11520 GVALinkage Linkage = GetGVALinkageForFunction(FD); 11521 11522 // static, static inline, always_inline, and extern inline functions can 11523 // always be deferred. Normal inline functions can be deferred in C99/C++. 11524 // Implicit template instantiations can also be deferred in C++. 11525 return !isDiscardableGVALinkage(Linkage); 11526 } 11527 11528 const auto *VD = cast<VarDecl>(D); 11529 assert(VD->isFileVarDecl() && "Expected file scoped var"); 11530 11531 // If the decl is marked as `declare target to`, it should be emitted for the 11532 // host and for the device. 11533 if (LangOpts.OpenMP && 11534 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 11535 return true; 11536 11537 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly && 11538 !isMSStaticDataMemberInlineDefinition(VD)) 11539 return false; 11540 11541 // Variables that can be needed in other TUs are required. 11542 auto Linkage = GetGVALinkageForVariable(VD); 11543 if (!isDiscardableGVALinkage(Linkage)) 11544 return true; 11545 11546 // We never need to emit a variable that is available in another TU. 11547 if (Linkage == GVA_AvailableExternally) 11548 return false; 11549 11550 // Variables that have destruction with side-effects are required. 11551 if (VD->needsDestruction(*this)) 11552 return true; 11553 11554 // Variables that have initialization with side-effects are required. 11555 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) && 11556 // We can get a value-dependent initializer during error recovery. 11557 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 11558 return true; 11559 11560 // Likewise, variables with tuple-like bindings are required if their 11561 // bindings have side-effects. 11562 if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) 11563 for (const auto *BD : DD->bindings()) 11564 if (const auto *BindingVD = BD->getHoldingVar()) 11565 if (DeclMustBeEmitted(BindingVD)) 11566 return true; 11567 11568 return false; 11569 } 11570 11571 void ASTContext::forEachMultiversionedFunctionVersion( 11572 const FunctionDecl *FD, 11573 llvm::function_ref<void(FunctionDecl *)> Pred) const { 11574 assert(FD->isMultiVersion() && "Only valid for multiversioned functions"); 11575 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls; 11576 FD = FD->getMostRecentDecl(); 11577 // FIXME: The order of traversal here matters and depends on the order of 11578 // lookup results, which happens to be (mostly) oldest-to-newest, but we 11579 // shouldn't rely on that. 11580 for (auto *CurDecl : 11581 FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) { 11582 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl(); 11583 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) && 11584 std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) { 11585 SeenDecls.insert(CurFD); 11586 Pred(CurFD); 11587 } 11588 } 11589 } 11590 11591 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic, 11592 bool IsCXXMethod, 11593 bool IsBuiltin) const { 11594 // Pass through to the C++ ABI object 11595 if (IsCXXMethod) 11596 return ABI->getDefaultMethodCallConv(IsVariadic); 11597 11598 // Builtins ignore user-specified default calling convention and remain the 11599 // Target's default calling convention. 11600 if (!IsBuiltin) { 11601 switch (LangOpts.getDefaultCallingConv()) { 11602 case LangOptions::DCC_None: 11603 break; 11604 case LangOptions::DCC_CDecl: 11605 return CC_C; 11606 case LangOptions::DCC_FastCall: 11607 if (getTargetInfo().hasFeature("sse2") && !IsVariadic) 11608 return CC_X86FastCall; 11609 break; 11610 case LangOptions::DCC_StdCall: 11611 if (!IsVariadic) 11612 return CC_X86StdCall; 11613 break; 11614 case LangOptions::DCC_VectorCall: 11615 // __vectorcall cannot be applied to variadic functions. 11616 if (!IsVariadic) 11617 return CC_X86VectorCall; 11618 break; 11619 case LangOptions::DCC_RegCall: 11620 // __regcall cannot be applied to variadic functions. 11621 if (!IsVariadic) 11622 return CC_X86RegCall; 11623 break; 11624 } 11625 } 11626 return Target->getDefaultCallingConv(); 11627 } 11628 11629 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const { 11630 // Pass through to the C++ ABI object 11631 return ABI->isNearlyEmpty(RD); 11632 } 11633 11634 VTableContextBase *ASTContext::getVTableContext() { 11635 if (!VTContext.get()) { 11636 auto ABI = Target->getCXXABI(); 11637 if (ABI.isMicrosoft()) 11638 VTContext.reset(new MicrosoftVTableContext(*this)); 11639 else { 11640 auto ComponentLayout = getLangOpts().RelativeCXXABIVTables 11641 ? ItaniumVTableContext::Relative 11642 : ItaniumVTableContext::Pointer; 11643 VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout)); 11644 } 11645 } 11646 return VTContext.get(); 11647 } 11648 11649 MangleContext *ASTContext::createMangleContext(const TargetInfo *T) { 11650 if (!T) 11651 T = Target; 11652 switch (T->getCXXABI().getKind()) { 11653 case TargetCXXABI::AppleARM64: 11654 case TargetCXXABI::Fuchsia: 11655 case TargetCXXABI::GenericAArch64: 11656 case TargetCXXABI::GenericItanium: 11657 case TargetCXXABI::GenericARM: 11658 case TargetCXXABI::GenericMIPS: 11659 case TargetCXXABI::iOS: 11660 case TargetCXXABI::WebAssembly: 11661 case TargetCXXABI::WatchOS: 11662 case TargetCXXABI::XL: 11663 return ItaniumMangleContext::create(*this, getDiagnostics()); 11664 case TargetCXXABI::Microsoft: 11665 return MicrosoftMangleContext::create(*this, getDiagnostics()); 11666 } 11667 llvm_unreachable("Unsupported ABI"); 11668 } 11669 11670 MangleContext *ASTContext::createDeviceMangleContext(const TargetInfo &T) { 11671 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft && 11672 "Device mangle context does not support Microsoft mangling."); 11673 switch (T.getCXXABI().getKind()) { 11674 case TargetCXXABI::AppleARM64: 11675 case TargetCXXABI::Fuchsia: 11676 case TargetCXXABI::GenericAArch64: 11677 case TargetCXXABI::GenericItanium: 11678 case TargetCXXABI::GenericARM: 11679 case TargetCXXABI::GenericMIPS: 11680 case TargetCXXABI::iOS: 11681 case TargetCXXABI::WebAssembly: 11682 case TargetCXXABI::WatchOS: 11683 case TargetCXXABI::XL: 11684 return ItaniumMangleContext::create( 11685 *this, getDiagnostics(), 11686 [](ASTContext &, const NamedDecl *ND) -> llvm::Optional<unsigned> { 11687 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) 11688 return RD->getDeviceLambdaManglingNumber(); 11689 return llvm::None; 11690 }); 11691 case TargetCXXABI::Microsoft: 11692 return MicrosoftMangleContext::create(*this, getDiagnostics()); 11693 } 11694 llvm_unreachable("Unsupported ABI"); 11695 } 11696 11697 CXXABI::~CXXABI() = default; 11698 11699 size_t ASTContext::getSideTableAllocatedMemory() const { 11700 return ASTRecordLayouts.getMemorySize() + 11701 llvm::capacity_in_bytes(ObjCLayouts) + 11702 llvm::capacity_in_bytes(KeyFunctions) + 11703 llvm::capacity_in_bytes(ObjCImpls) + 11704 llvm::capacity_in_bytes(BlockVarCopyInits) + 11705 llvm::capacity_in_bytes(DeclAttrs) + 11706 llvm::capacity_in_bytes(TemplateOrInstantiation) + 11707 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) + 11708 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) + 11709 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) + 11710 llvm::capacity_in_bytes(OverriddenMethods) + 11711 llvm::capacity_in_bytes(Types) + 11712 llvm::capacity_in_bytes(VariableArrayTypes); 11713 } 11714 11715 /// getIntTypeForBitwidth - 11716 /// sets integer QualTy according to specified details: 11717 /// bitwidth, signed/unsigned. 11718 /// Returns empty type if there is no appropriate target types. 11719 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth, 11720 unsigned Signed) const { 11721 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed); 11722 CanQualType QualTy = getFromTargetType(Ty); 11723 if (!QualTy && DestWidth == 128) 11724 return Signed ? Int128Ty : UnsignedInt128Ty; 11725 return QualTy; 11726 } 11727 11728 /// getRealTypeForBitwidth - 11729 /// sets floating point QualTy according to specified bitwidth. 11730 /// Returns empty type if there is no appropriate target types. 11731 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth, 11732 FloatModeKind ExplicitType) const { 11733 FloatModeKind Ty = 11734 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType); 11735 switch (Ty) { 11736 case FloatModeKind::Float: 11737 return FloatTy; 11738 case FloatModeKind::Double: 11739 return DoubleTy; 11740 case FloatModeKind::LongDouble: 11741 return LongDoubleTy; 11742 case FloatModeKind::Float128: 11743 return Float128Ty; 11744 case FloatModeKind::Ibm128: 11745 return Ibm128Ty; 11746 case FloatModeKind::NoFloat: 11747 return {}; 11748 } 11749 11750 llvm_unreachable("Unhandled TargetInfo::RealType value"); 11751 } 11752 11753 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) { 11754 if (Number > 1) 11755 MangleNumbers[ND] = Number; 11756 } 11757 11758 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const { 11759 auto I = MangleNumbers.find(ND); 11760 return I != MangleNumbers.end() ? I->second : 1; 11761 } 11762 11763 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) { 11764 if (Number > 1) 11765 StaticLocalNumbers[VD] = Number; 11766 } 11767 11768 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const { 11769 auto I = StaticLocalNumbers.find(VD); 11770 return I != StaticLocalNumbers.end() ? I->second : 1; 11771 } 11772 11773 MangleNumberingContext & 11774 ASTContext::getManglingNumberContext(const DeclContext *DC) { 11775 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C. 11776 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC]; 11777 if (!MCtx) 11778 MCtx = createMangleNumberingContext(); 11779 return *MCtx; 11780 } 11781 11782 MangleNumberingContext & 11783 ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) { 11784 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C. 11785 std::unique_ptr<MangleNumberingContext> &MCtx = 11786 ExtraMangleNumberingContexts[D]; 11787 if (!MCtx) 11788 MCtx = createMangleNumberingContext(); 11789 return *MCtx; 11790 } 11791 11792 std::unique_ptr<MangleNumberingContext> 11793 ASTContext::createMangleNumberingContext() const { 11794 return ABI->createMangleNumberingContext(); 11795 } 11796 11797 const CXXConstructorDecl * 11798 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) { 11799 return ABI->getCopyConstructorForExceptionObject( 11800 cast<CXXRecordDecl>(RD->getFirstDecl())); 11801 } 11802 11803 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD, 11804 CXXConstructorDecl *CD) { 11805 return ABI->addCopyConstructorForExceptionObject( 11806 cast<CXXRecordDecl>(RD->getFirstDecl()), 11807 cast<CXXConstructorDecl>(CD->getFirstDecl())); 11808 } 11809 11810 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD, 11811 TypedefNameDecl *DD) { 11812 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD); 11813 } 11814 11815 TypedefNameDecl * 11816 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) { 11817 return ABI->getTypedefNameForUnnamedTagDecl(TD); 11818 } 11819 11820 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD, 11821 DeclaratorDecl *DD) { 11822 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD); 11823 } 11824 11825 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) { 11826 return ABI->getDeclaratorForUnnamedTagDecl(TD); 11827 } 11828 11829 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) { 11830 ParamIndices[D] = index; 11831 } 11832 11833 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const { 11834 ParameterIndexTable::const_iterator I = ParamIndices.find(D); 11835 assert(I != ParamIndices.end() && 11836 "ParmIndices lacks entry set by ParmVarDecl"); 11837 return I->second; 11838 } 11839 11840 QualType ASTContext::getStringLiteralArrayType(QualType EltTy, 11841 unsigned Length) const { 11842 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 11843 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 11844 EltTy = EltTy.withConst(); 11845 11846 EltTy = adjustStringLiteralBaseType(EltTy); 11847 11848 // Get an array type for the string, according to C99 6.4.5. This includes 11849 // the null terminator character. 11850 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr, 11851 ArrayType::Normal, /*IndexTypeQuals*/ 0); 11852 } 11853 11854 StringLiteral * 11855 ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const { 11856 StringLiteral *&Result = StringLiteralCache[Key]; 11857 if (!Result) 11858 Result = StringLiteral::Create( 11859 *this, Key, StringLiteral::Ascii, 11860 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()), 11861 SourceLocation()); 11862 return Result; 11863 } 11864 11865 MSGuidDecl * 11866 ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const { 11867 assert(MSGuidTagDecl && "building MS GUID without MS extensions?"); 11868 11869 llvm::FoldingSetNodeID ID; 11870 MSGuidDecl::Profile(ID, Parts); 11871 11872 void *InsertPos; 11873 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos)) 11874 return Existing; 11875 11876 QualType GUIDType = getMSGuidType().withConst(); 11877 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts); 11878 MSGuidDecls.InsertNode(New, InsertPos); 11879 return New; 11880 } 11881 11882 TemplateParamObjectDecl * 11883 ASTContext::getTemplateParamObjectDecl(QualType T, const APValue &V) const { 11884 assert(T->isRecordType() && "template param object of unexpected type"); 11885 11886 // C++ [temp.param]p8: 11887 // [...] a static storage duration object of type 'const T' [...] 11888 T.addConst(); 11889 11890 llvm::FoldingSetNodeID ID; 11891 TemplateParamObjectDecl::Profile(ID, T, V); 11892 11893 void *InsertPos; 11894 if (TemplateParamObjectDecl *Existing = 11895 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos)) 11896 return Existing; 11897 11898 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V); 11899 TemplateParamObjectDecls.InsertNode(New, InsertPos); 11900 return New; 11901 } 11902 11903 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const { 11904 const llvm::Triple &T = getTargetInfo().getTriple(); 11905 if (!T.isOSDarwin()) 11906 return false; 11907 11908 if (!(T.isiOS() && T.isOSVersionLT(7)) && 11909 !(T.isMacOSX() && T.isOSVersionLT(10, 9))) 11910 return false; 11911 11912 QualType AtomicTy = E->getPtr()->getType()->getPointeeType(); 11913 CharUnits sizeChars = getTypeSizeInChars(AtomicTy); 11914 uint64_t Size = sizeChars.getQuantity(); 11915 CharUnits alignChars = getTypeAlignInChars(AtomicTy); 11916 unsigned Align = alignChars.getQuantity(); 11917 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth(); 11918 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits); 11919 } 11920 11921 bool 11922 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, 11923 const ObjCMethodDecl *MethodImpl) { 11924 // No point trying to match an unavailable/deprecated mothod. 11925 if (MethodDecl->hasAttr<UnavailableAttr>() 11926 || MethodDecl->hasAttr<DeprecatedAttr>()) 11927 return false; 11928 if (MethodDecl->getObjCDeclQualifier() != 11929 MethodImpl->getObjCDeclQualifier()) 11930 return false; 11931 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType())) 11932 return false; 11933 11934 if (MethodDecl->param_size() != MethodImpl->param_size()) 11935 return false; 11936 11937 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(), 11938 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(), 11939 EF = MethodDecl->param_end(); 11940 IM != EM && IF != EF; ++IM, ++IF) { 11941 const ParmVarDecl *DeclVar = (*IF); 11942 const ParmVarDecl *ImplVar = (*IM); 11943 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier()) 11944 return false; 11945 if (!hasSameType(DeclVar->getType(), ImplVar->getType())) 11946 return false; 11947 } 11948 11949 return (MethodDecl->isVariadic() == MethodImpl->isVariadic()); 11950 } 11951 11952 uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const { 11953 LangAS AS; 11954 if (QT->getUnqualifiedDesugaredType()->isNullPtrType()) 11955 AS = LangAS::Default; 11956 else 11957 AS = QT->getPointeeType().getAddressSpace(); 11958 11959 return getTargetInfo().getNullPointerValue(AS); 11960 } 11961 11962 unsigned ASTContext::getTargetAddressSpace(QualType T) const { 11963 // Return the address space for the type. If the type is a 11964 // function type without an address space qualifier, the 11965 // program address space is used. Otherwise, the target picks 11966 // the best address space based on the type information 11967 return T->isFunctionType() && !T.hasAddressSpace() 11968 ? getTargetInfo().getProgramAddressSpace() 11969 : getTargetAddressSpace(T.getQualifiers()); 11970 } 11971 11972 unsigned ASTContext::getTargetAddressSpace(Qualifiers Q) const { 11973 return getTargetAddressSpace(Q.getAddressSpace()); 11974 } 11975 11976 unsigned ASTContext::getTargetAddressSpace(LangAS AS) const { 11977 if (isTargetAddressSpace(AS)) 11978 return toTargetAddressSpace(AS); 11979 else 11980 return (*AddrSpaceMap)[(unsigned)AS]; 11981 } 11982 11983 QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const { 11984 assert(Ty->isFixedPointType()); 11985 11986 if (Ty->isSaturatedFixedPointType()) return Ty; 11987 11988 switch (Ty->castAs<BuiltinType>()->getKind()) { 11989 default: 11990 llvm_unreachable("Not a fixed point type!"); 11991 case BuiltinType::ShortAccum: 11992 return SatShortAccumTy; 11993 case BuiltinType::Accum: 11994 return SatAccumTy; 11995 case BuiltinType::LongAccum: 11996 return SatLongAccumTy; 11997 case BuiltinType::UShortAccum: 11998 return SatUnsignedShortAccumTy; 11999 case BuiltinType::UAccum: 12000 return SatUnsignedAccumTy; 12001 case BuiltinType::ULongAccum: 12002 return SatUnsignedLongAccumTy; 12003 case BuiltinType::ShortFract: 12004 return SatShortFractTy; 12005 case BuiltinType::Fract: 12006 return SatFractTy; 12007 case BuiltinType::LongFract: 12008 return SatLongFractTy; 12009 case BuiltinType::UShortFract: 12010 return SatUnsignedShortFractTy; 12011 case BuiltinType::UFract: 12012 return SatUnsignedFractTy; 12013 case BuiltinType::ULongFract: 12014 return SatUnsignedLongFractTy; 12015 } 12016 } 12017 12018 LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const { 12019 if (LangOpts.OpenCL) 12020 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS); 12021 12022 if (LangOpts.CUDA) 12023 return getTargetInfo().getCUDABuiltinAddressSpace(AS); 12024 12025 return getLangASFromTargetAS(AS); 12026 } 12027 12028 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that 12029 // doesn't include ASTContext.h 12030 template 12031 clang::LazyGenerationalUpdatePtr< 12032 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType 12033 clang::LazyGenerationalUpdatePtr< 12034 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue( 12035 const clang::ASTContext &Ctx, Decl *Value); 12036 12037 unsigned char ASTContext::getFixedPointScale(QualType Ty) const { 12038 assert(Ty->isFixedPointType()); 12039 12040 const TargetInfo &Target = getTargetInfo(); 12041 switch (Ty->castAs<BuiltinType>()->getKind()) { 12042 default: 12043 llvm_unreachable("Not a fixed point type!"); 12044 case BuiltinType::ShortAccum: 12045 case BuiltinType::SatShortAccum: 12046 return Target.getShortAccumScale(); 12047 case BuiltinType::Accum: 12048 case BuiltinType::SatAccum: 12049 return Target.getAccumScale(); 12050 case BuiltinType::LongAccum: 12051 case BuiltinType::SatLongAccum: 12052 return Target.getLongAccumScale(); 12053 case BuiltinType::UShortAccum: 12054 case BuiltinType::SatUShortAccum: 12055 return Target.getUnsignedShortAccumScale(); 12056 case BuiltinType::UAccum: 12057 case BuiltinType::SatUAccum: 12058 return Target.getUnsignedAccumScale(); 12059 case BuiltinType::ULongAccum: 12060 case BuiltinType::SatULongAccum: 12061 return Target.getUnsignedLongAccumScale(); 12062 case BuiltinType::ShortFract: 12063 case BuiltinType::SatShortFract: 12064 return Target.getShortFractScale(); 12065 case BuiltinType::Fract: 12066 case BuiltinType::SatFract: 12067 return Target.getFractScale(); 12068 case BuiltinType::LongFract: 12069 case BuiltinType::SatLongFract: 12070 return Target.getLongFractScale(); 12071 case BuiltinType::UShortFract: 12072 case BuiltinType::SatUShortFract: 12073 return Target.getUnsignedShortFractScale(); 12074 case BuiltinType::UFract: 12075 case BuiltinType::SatUFract: 12076 return Target.getUnsignedFractScale(); 12077 case BuiltinType::ULongFract: 12078 case BuiltinType::SatULongFract: 12079 return Target.getUnsignedLongFractScale(); 12080 } 12081 } 12082 12083 unsigned char ASTContext::getFixedPointIBits(QualType Ty) const { 12084 assert(Ty->isFixedPointType()); 12085 12086 const TargetInfo &Target = getTargetInfo(); 12087 switch (Ty->castAs<BuiltinType>()->getKind()) { 12088 default: 12089 llvm_unreachable("Not a fixed point type!"); 12090 case BuiltinType::ShortAccum: 12091 case BuiltinType::SatShortAccum: 12092 return Target.getShortAccumIBits(); 12093 case BuiltinType::Accum: 12094 case BuiltinType::SatAccum: 12095 return Target.getAccumIBits(); 12096 case BuiltinType::LongAccum: 12097 case BuiltinType::SatLongAccum: 12098 return Target.getLongAccumIBits(); 12099 case BuiltinType::UShortAccum: 12100 case BuiltinType::SatUShortAccum: 12101 return Target.getUnsignedShortAccumIBits(); 12102 case BuiltinType::UAccum: 12103 case BuiltinType::SatUAccum: 12104 return Target.getUnsignedAccumIBits(); 12105 case BuiltinType::ULongAccum: 12106 case BuiltinType::SatULongAccum: 12107 return Target.getUnsignedLongAccumIBits(); 12108 case BuiltinType::ShortFract: 12109 case BuiltinType::SatShortFract: 12110 case BuiltinType::Fract: 12111 case BuiltinType::SatFract: 12112 case BuiltinType::LongFract: 12113 case BuiltinType::SatLongFract: 12114 case BuiltinType::UShortFract: 12115 case BuiltinType::SatUShortFract: 12116 case BuiltinType::UFract: 12117 case BuiltinType::SatUFract: 12118 case BuiltinType::ULongFract: 12119 case BuiltinType::SatULongFract: 12120 return 0; 12121 } 12122 } 12123 12124 llvm::FixedPointSemantics 12125 ASTContext::getFixedPointSemantics(QualType Ty) const { 12126 assert((Ty->isFixedPointType() || Ty->isIntegerType()) && 12127 "Can only get the fixed point semantics for a " 12128 "fixed point or integer type."); 12129 if (Ty->isIntegerType()) 12130 return llvm::FixedPointSemantics::GetIntegerSemantics( 12131 getIntWidth(Ty), Ty->isSignedIntegerType()); 12132 12133 bool isSigned = Ty->isSignedFixedPointType(); 12134 return llvm::FixedPointSemantics( 12135 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned, 12136 Ty->isSaturatedFixedPointType(), 12137 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding()); 12138 } 12139 12140 llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const { 12141 assert(Ty->isFixedPointType()); 12142 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty)); 12143 } 12144 12145 llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const { 12146 assert(Ty->isFixedPointType()); 12147 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty)); 12148 } 12149 12150 QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const { 12151 assert(Ty->isUnsignedFixedPointType() && 12152 "Expected unsigned fixed point type"); 12153 12154 switch (Ty->castAs<BuiltinType>()->getKind()) { 12155 case BuiltinType::UShortAccum: 12156 return ShortAccumTy; 12157 case BuiltinType::UAccum: 12158 return AccumTy; 12159 case BuiltinType::ULongAccum: 12160 return LongAccumTy; 12161 case BuiltinType::SatUShortAccum: 12162 return SatShortAccumTy; 12163 case BuiltinType::SatUAccum: 12164 return SatAccumTy; 12165 case BuiltinType::SatULongAccum: 12166 return SatLongAccumTy; 12167 case BuiltinType::UShortFract: 12168 return ShortFractTy; 12169 case BuiltinType::UFract: 12170 return FractTy; 12171 case BuiltinType::ULongFract: 12172 return LongFractTy; 12173 case BuiltinType::SatUShortFract: 12174 return SatShortFractTy; 12175 case BuiltinType::SatUFract: 12176 return SatFractTy; 12177 case BuiltinType::SatULongFract: 12178 return SatLongFractTy; 12179 default: 12180 llvm_unreachable("Unexpected unsigned fixed point type"); 12181 } 12182 } 12183 12184 ParsedTargetAttr 12185 ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const { 12186 assert(TD != nullptr); 12187 ParsedTargetAttr ParsedAttr = TD->parse(); 12188 12189 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) { 12190 return !Target->isValidFeatureName(StringRef{Feat}.substr(1)); 12191 }); 12192 return ParsedAttr; 12193 } 12194 12195 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 12196 const FunctionDecl *FD) const { 12197 if (FD) 12198 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD)); 12199 else 12200 Target->initFeatureMap(FeatureMap, getDiagnostics(), 12201 Target->getTargetOpts().CPU, 12202 Target->getTargetOpts().Features); 12203 } 12204 12205 // Fills in the supplied string map with the set of target features for the 12206 // passed in function. 12207 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 12208 GlobalDecl GD) const { 12209 StringRef TargetCPU = Target->getTargetOpts().CPU; 12210 const FunctionDecl *FD = GD.getDecl()->getAsFunction(); 12211 if (const auto *TD = FD->getAttr<TargetAttr>()) { 12212 ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD); 12213 12214 // Make a copy of the features as passed on the command line into the 12215 // beginning of the additional features from the function to override. 12216 ParsedAttr.Features.insert( 12217 ParsedAttr.Features.begin(), 12218 Target->getTargetOpts().FeaturesAsWritten.begin(), 12219 Target->getTargetOpts().FeaturesAsWritten.end()); 12220 12221 if (ParsedAttr.Architecture != "" && 12222 Target->isValidCPUName(ParsedAttr.Architecture)) 12223 TargetCPU = ParsedAttr.Architecture; 12224 12225 // Now populate the feature map, first with the TargetCPU which is either 12226 // the default or a new one from the target attribute string. Then we'll use 12227 // the passed in features (FeaturesAsWritten) along with the new ones from 12228 // the attribute. 12229 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, 12230 ParsedAttr.Features); 12231 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) { 12232 llvm::SmallVector<StringRef, 32> FeaturesTmp; 12233 Target->getCPUSpecificCPUDispatchFeatures( 12234 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp); 12235 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end()); 12236 Features.insert(Features.begin(), 12237 Target->getTargetOpts().FeaturesAsWritten.begin(), 12238 Target->getTargetOpts().FeaturesAsWritten.end()); 12239 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features); 12240 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) { 12241 std::vector<std::string> Features; 12242 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex()); 12243 if (VersionStr.startswith("arch=")) 12244 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1); 12245 else if (VersionStr != "default") 12246 Features.push_back((StringRef{"+"} + VersionStr).str()); 12247 12248 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features); 12249 } else { 12250 FeatureMap = Target->getTargetOpts().FeatureMap; 12251 } 12252 } 12253 12254 OMPTraitInfo &ASTContext::getNewOMPTraitInfo() { 12255 OMPTraitInfoVector.emplace_back(new OMPTraitInfo()); 12256 return *OMPTraitInfoVector.back(); 12257 } 12258 12259 const StreamingDiagnostic &clang:: 12260 operator<<(const StreamingDiagnostic &DB, 12261 const ASTContext::SectionInfo &Section) { 12262 if (Section.Decl) 12263 return DB << Section.Decl; 12264 return DB << "a prior #pragma section"; 12265 } 12266 12267 bool ASTContext::mayExternalizeStaticVar(const Decl *D) const { 12268 bool IsStaticVar = 12269 isa<VarDecl>(D) && cast<VarDecl>(D)->getStorageClass() == SC_Static; 12270 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() && 12271 !D->getAttr<CUDADeviceAttr>()->isImplicit()) || 12272 (D->hasAttr<CUDAConstantAttr>() && 12273 !D->getAttr<CUDAConstantAttr>()->isImplicit()); 12274 // CUDA/HIP: static managed variables need to be externalized since it is 12275 // a declaration in IR, therefore cannot have internal linkage. 12276 return IsStaticVar && 12277 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar); 12278 } 12279 12280 bool ASTContext::shouldExternalizeStaticVar(const Decl *D) const { 12281 return mayExternalizeStaticVar(D) && 12282 (D->hasAttr<HIPManagedAttr>() || 12283 CUDADeviceVarODRUsedByHost.count(cast<VarDecl>(D))); 12284 } 12285 12286 StringRef ASTContext::getCUIDHash() const { 12287 if (!CUIDHash.empty()) 12288 return CUIDHash; 12289 if (LangOpts.CUID.empty()) 12290 return StringRef(); 12291 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true); 12292 return CUIDHash; 12293 } 12294