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 /// getFloatingTypeOrder - Compare the rank of the two specified floating 6802 /// point types, ignoring the domain of the type (i.e. 'double' == 6803 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If 6804 /// LHS < RHS, return -1. 6805 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const { 6806 FloatingRank LHSR = getFloatingRank(LHS); 6807 FloatingRank RHSR = getFloatingRank(RHS); 6808 6809 if (LHSR == RHSR) 6810 return 0; 6811 if (LHSR > RHSR) 6812 return 1; 6813 return -1; 6814 } 6815 6816 int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const { 6817 if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS)) 6818 return 0; 6819 return getFloatingTypeOrder(LHS, RHS); 6820 } 6821 6822 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This 6823 /// routine will assert if passed a built-in type that isn't an integer or enum, 6824 /// or if it is not canonicalized. 6825 unsigned ASTContext::getIntegerRank(const Type *T) const { 6826 assert(T->isCanonicalUnqualified() && "T should be canonicalized"); 6827 6828 // Results in this 'losing' to any type of the same size, but winning if 6829 // larger. 6830 if (const auto *EIT = dyn_cast<BitIntType>(T)) 6831 return 0 + (EIT->getNumBits() << 3); 6832 6833 switch (cast<BuiltinType>(T)->getKind()) { 6834 default: llvm_unreachable("getIntegerRank(): not a built-in integer"); 6835 case BuiltinType::Bool: 6836 return 1 + (getIntWidth(BoolTy) << 3); 6837 case BuiltinType::Char_S: 6838 case BuiltinType::Char_U: 6839 case BuiltinType::SChar: 6840 case BuiltinType::UChar: 6841 return 2 + (getIntWidth(CharTy) << 3); 6842 case BuiltinType::Short: 6843 case BuiltinType::UShort: 6844 return 3 + (getIntWidth(ShortTy) << 3); 6845 case BuiltinType::Int: 6846 case BuiltinType::UInt: 6847 return 4 + (getIntWidth(IntTy) << 3); 6848 case BuiltinType::Long: 6849 case BuiltinType::ULong: 6850 return 5 + (getIntWidth(LongTy) << 3); 6851 case BuiltinType::LongLong: 6852 case BuiltinType::ULongLong: 6853 return 6 + (getIntWidth(LongLongTy) << 3); 6854 case BuiltinType::Int128: 6855 case BuiltinType::UInt128: 6856 return 7 + (getIntWidth(Int128Ty) << 3); 6857 } 6858 } 6859 6860 /// Whether this is a promotable bitfield reference according 6861 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions). 6862 /// 6863 /// \returns the type this bit-field will promote to, or NULL if no 6864 /// promotion occurs. 6865 QualType ASTContext::isPromotableBitField(Expr *E) const { 6866 if (E->isTypeDependent() || E->isValueDependent()) 6867 return {}; 6868 6869 // C++ [conv.prom]p5: 6870 // If the bit-field has an enumerated type, it is treated as any other 6871 // value of that type for promotion purposes. 6872 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType()) 6873 return {}; 6874 6875 // FIXME: We should not do this unless E->refersToBitField() is true. This 6876 // matters in C where getSourceBitField() will find bit-fields for various 6877 // cases where the source expression is not a bit-field designator. 6878 6879 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields? 6880 if (!Field) 6881 return {}; 6882 6883 QualType FT = Field->getType(); 6884 6885 uint64_t BitWidth = Field->getBitWidthValue(*this); 6886 uint64_t IntSize = getTypeSize(IntTy); 6887 // C++ [conv.prom]p5: 6888 // A prvalue for an integral bit-field can be converted to a prvalue of type 6889 // int if int can represent all the values of the bit-field; otherwise, it 6890 // can be converted to unsigned int if unsigned int can represent all the 6891 // values of the bit-field. If the bit-field is larger yet, no integral 6892 // promotion applies to it. 6893 // C11 6.3.1.1/2: 6894 // [For a bit-field of type _Bool, int, signed int, or unsigned int:] 6895 // If an int can represent all values of the original type (as restricted by 6896 // the width, for a bit-field), the value is converted to an int; otherwise, 6897 // it is converted to an unsigned int. 6898 // 6899 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int. 6900 // We perform that promotion here to match GCC and C++. 6901 // FIXME: C does not permit promotion of an enum bit-field whose rank is 6902 // greater than that of 'int'. We perform that promotion to match GCC. 6903 if (BitWidth < IntSize) 6904 return IntTy; 6905 6906 if (BitWidth == IntSize) 6907 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy; 6908 6909 // Bit-fields wider than int are not subject to promotions, and therefore act 6910 // like the base type. GCC has some weird bugs in this area that we 6911 // deliberately do not follow (GCC follows a pre-standard resolution to 6912 // C's DR315 which treats bit-width as being part of the type, and this leaks 6913 // into their semantics in some cases). 6914 return {}; 6915 } 6916 6917 /// getPromotedIntegerType - Returns the type that Promotable will 6918 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable 6919 /// integer type. 6920 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const { 6921 assert(!Promotable.isNull()); 6922 assert(Promotable->isPromotableIntegerType()); 6923 if (const auto *ET = Promotable->getAs<EnumType>()) 6924 return ET->getDecl()->getPromotionType(); 6925 6926 if (const auto *BT = Promotable->getAs<BuiltinType>()) { 6927 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t 6928 // (3.9.1) can be converted to a prvalue of the first of the following 6929 // types that can represent all the values of its underlying type: 6930 // int, unsigned int, long int, unsigned long int, long long int, or 6931 // unsigned long long int [...] 6932 // FIXME: Is there some better way to compute this? 6933 if (BT->getKind() == BuiltinType::WChar_S || 6934 BT->getKind() == BuiltinType::WChar_U || 6935 BT->getKind() == BuiltinType::Char8 || 6936 BT->getKind() == BuiltinType::Char16 || 6937 BT->getKind() == BuiltinType::Char32) { 6938 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S; 6939 uint64_t FromSize = getTypeSize(BT); 6940 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy, 6941 LongLongTy, UnsignedLongLongTy }; 6942 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) { 6943 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]); 6944 if (FromSize < ToSize || 6945 (FromSize == ToSize && 6946 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) 6947 return PromoteTypes[Idx]; 6948 } 6949 llvm_unreachable("char type should fit into long long"); 6950 } 6951 } 6952 6953 // At this point, we should have a signed or unsigned integer type. 6954 if (Promotable->isSignedIntegerType()) 6955 return IntTy; 6956 uint64_t PromotableSize = getIntWidth(Promotable); 6957 uint64_t IntSize = getIntWidth(IntTy); 6958 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize); 6959 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy; 6960 } 6961 6962 /// Recurses in pointer/array types until it finds an objc retainable 6963 /// type and returns its ownership. 6964 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const { 6965 while (!T.isNull()) { 6966 if (T.getObjCLifetime() != Qualifiers::OCL_None) 6967 return T.getObjCLifetime(); 6968 if (T->isArrayType()) 6969 T = getBaseElementType(T); 6970 else if (const auto *PT = T->getAs<PointerType>()) 6971 T = PT->getPointeeType(); 6972 else if (const auto *RT = T->getAs<ReferenceType>()) 6973 T = RT->getPointeeType(); 6974 else 6975 break; 6976 } 6977 6978 return Qualifiers::OCL_None; 6979 } 6980 6981 static const Type *getIntegerTypeForEnum(const EnumType *ET) { 6982 // Incomplete enum types are not treated as integer types. 6983 // FIXME: In C++, enum types are never integer types. 6984 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped()) 6985 return ET->getDecl()->getIntegerType().getTypePtr(); 6986 return nullptr; 6987 } 6988 6989 /// getIntegerTypeOrder - Returns the highest ranked integer type: 6990 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If 6991 /// LHS < RHS, return -1. 6992 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const { 6993 const Type *LHSC = getCanonicalType(LHS).getTypePtr(); 6994 const Type *RHSC = getCanonicalType(RHS).getTypePtr(); 6995 6996 // Unwrap enums to their underlying type. 6997 if (const auto *ET = dyn_cast<EnumType>(LHSC)) 6998 LHSC = getIntegerTypeForEnum(ET); 6999 if (const auto *ET = dyn_cast<EnumType>(RHSC)) 7000 RHSC = getIntegerTypeForEnum(ET); 7001 7002 if (LHSC == RHSC) return 0; 7003 7004 bool LHSUnsigned = LHSC->isUnsignedIntegerType(); 7005 bool RHSUnsigned = RHSC->isUnsignedIntegerType(); 7006 7007 unsigned LHSRank = getIntegerRank(LHSC); 7008 unsigned RHSRank = getIntegerRank(RHSC); 7009 7010 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned. 7011 if (LHSRank == RHSRank) return 0; 7012 return LHSRank > RHSRank ? 1 : -1; 7013 } 7014 7015 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa. 7016 if (LHSUnsigned) { 7017 // If the unsigned [LHS] type is larger, return it. 7018 if (LHSRank >= RHSRank) 7019 return 1; 7020 7021 // If the signed type can represent all values of the unsigned type, it 7022 // wins. Because we are dealing with 2's complement and types that are 7023 // powers of two larger than each other, this is always safe. 7024 return -1; 7025 } 7026 7027 // If the unsigned [RHS] type is larger, return it. 7028 if (RHSRank >= LHSRank) 7029 return -1; 7030 7031 // If the signed type can represent all values of the unsigned type, it 7032 // wins. Because we are dealing with 2's complement and types that are 7033 // powers of two larger than each other, this is always safe. 7034 return 1; 7035 } 7036 7037 TypedefDecl *ASTContext::getCFConstantStringDecl() const { 7038 if (CFConstantStringTypeDecl) 7039 return CFConstantStringTypeDecl; 7040 7041 assert(!CFConstantStringTagDecl && 7042 "tag and typedef should be initialized together"); 7043 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag"); 7044 CFConstantStringTagDecl->startDefinition(); 7045 7046 struct { 7047 QualType Type; 7048 const char *Name; 7049 } Fields[5]; 7050 unsigned Count = 0; 7051 7052 /// Objective-C ABI 7053 /// 7054 /// typedef struct __NSConstantString_tag { 7055 /// const int *isa; 7056 /// int flags; 7057 /// const char *str; 7058 /// long length; 7059 /// } __NSConstantString; 7060 /// 7061 /// Swift ABI (4.1, 4.2) 7062 /// 7063 /// typedef struct __NSConstantString_tag { 7064 /// uintptr_t _cfisa; 7065 /// uintptr_t _swift_rc; 7066 /// _Atomic(uint64_t) _cfinfoa; 7067 /// const char *_ptr; 7068 /// uint32_t _length; 7069 /// } __NSConstantString; 7070 /// 7071 /// Swift ABI (5.0) 7072 /// 7073 /// typedef struct __NSConstantString_tag { 7074 /// uintptr_t _cfisa; 7075 /// uintptr_t _swift_rc; 7076 /// _Atomic(uint64_t) _cfinfoa; 7077 /// const char *_ptr; 7078 /// uintptr_t _length; 7079 /// } __NSConstantString; 7080 7081 const auto CFRuntime = getLangOpts().CFRuntime; 7082 if (static_cast<unsigned>(CFRuntime) < 7083 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) { 7084 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" }; 7085 Fields[Count++] = { IntTy, "flags" }; 7086 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" }; 7087 Fields[Count++] = { LongTy, "length" }; 7088 } else { 7089 Fields[Count++] = { getUIntPtrType(), "_cfisa" }; 7090 Fields[Count++] = { getUIntPtrType(), "_swift_rc" }; 7091 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" }; 7092 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" }; 7093 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 || 7094 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2) 7095 Fields[Count++] = { IntTy, "_ptr" }; 7096 else 7097 Fields[Count++] = { getUIntPtrType(), "_ptr" }; 7098 } 7099 7100 // Create fields 7101 for (unsigned i = 0; i < Count; ++i) { 7102 FieldDecl *Field = 7103 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(), 7104 SourceLocation(), &Idents.get(Fields[i].Name), 7105 Fields[i].Type, /*TInfo=*/nullptr, 7106 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); 7107 Field->setAccess(AS_public); 7108 CFConstantStringTagDecl->addDecl(Field); 7109 } 7110 7111 CFConstantStringTagDecl->completeDefinition(); 7112 // This type is designed to be compatible with NSConstantString, but cannot 7113 // use the same name, since NSConstantString is an interface. 7114 auto tagType = getTagDeclType(CFConstantStringTagDecl); 7115 CFConstantStringTypeDecl = 7116 buildImplicitTypedef(tagType, "__NSConstantString"); 7117 7118 return CFConstantStringTypeDecl; 7119 } 7120 7121 RecordDecl *ASTContext::getCFConstantStringTagDecl() const { 7122 if (!CFConstantStringTagDecl) 7123 getCFConstantStringDecl(); // Build the tag and the typedef. 7124 return CFConstantStringTagDecl; 7125 } 7126 7127 // getCFConstantStringType - Return the type used for constant CFStrings. 7128 QualType ASTContext::getCFConstantStringType() const { 7129 return getTypedefType(getCFConstantStringDecl()); 7130 } 7131 7132 QualType ASTContext::getObjCSuperType() const { 7133 if (ObjCSuperType.isNull()) { 7134 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super"); 7135 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl); 7136 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl); 7137 } 7138 return ObjCSuperType; 7139 } 7140 7141 void ASTContext::setCFConstantStringType(QualType T) { 7142 const auto *TD = T->castAs<TypedefType>(); 7143 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl()); 7144 const auto *TagType = 7145 CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>(); 7146 CFConstantStringTagDecl = TagType->getDecl(); 7147 } 7148 7149 QualType ASTContext::getBlockDescriptorType() const { 7150 if (BlockDescriptorType) 7151 return getTagDeclType(BlockDescriptorType); 7152 7153 RecordDecl *RD; 7154 // FIXME: Needs the FlagAppleBlock bit. 7155 RD = buildImplicitRecord("__block_descriptor"); 7156 RD->startDefinition(); 7157 7158 QualType FieldTypes[] = { 7159 UnsignedLongTy, 7160 UnsignedLongTy, 7161 }; 7162 7163 static const char *const FieldNames[] = { 7164 "reserved", 7165 "Size" 7166 }; 7167 7168 for (size_t i = 0; i < 2; ++i) { 7169 FieldDecl *Field = FieldDecl::Create( 7170 *this, RD, SourceLocation(), SourceLocation(), 7171 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, 7172 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); 7173 Field->setAccess(AS_public); 7174 RD->addDecl(Field); 7175 } 7176 7177 RD->completeDefinition(); 7178 7179 BlockDescriptorType = RD; 7180 7181 return getTagDeclType(BlockDescriptorType); 7182 } 7183 7184 QualType ASTContext::getBlockDescriptorExtendedType() const { 7185 if (BlockDescriptorExtendedType) 7186 return getTagDeclType(BlockDescriptorExtendedType); 7187 7188 RecordDecl *RD; 7189 // FIXME: Needs the FlagAppleBlock bit. 7190 RD = buildImplicitRecord("__block_descriptor_withcopydispose"); 7191 RD->startDefinition(); 7192 7193 QualType FieldTypes[] = { 7194 UnsignedLongTy, 7195 UnsignedLongTy, 7196 getPointerType(VoidPtrTy), 7197 getPointerType(VoidPtrTy) 7198 }; 7199 7200 static const char *const FieldNames[] = { 7201 "reserved", 7202 "Size", 7203 "CopyFuncPtr", 7204 "DestroyFuncPtr" 7205 }; 7206 7207 for (size_t i = 0; i < 4; ++i) { 7208 FieldDecl *Field = FieldDecl::Create( 7209 *this, RD, SourceLocation(), SourceLocation(), 7210 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, 7211 /*BitWidth=*/nullptr, 7212 /*Mutable=*/false, ICIS_NoInit); 7213 Field->setAccess(AS_public); 7214 RD->addDecl(Field); 7215 } 7216 7217 RD->completeDefinition(); 7218 7219 BlockDescriptorExtendedType = RD; 7220 return getTagDeclType(BlockDescriptorExtendedType); 7221 } 7222 7223 OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const { 7224 const auto *BT = dyn_cast<BuiltinType>(T); 7225 7226 if (!BT) { 7227 if (isa<PipeType>(T)) 7228 return OCLTK_Pipe; 7229 7230 return OCLTK_Default; 7231 } 7232 7233 switch (BT->getKind()) { 7234 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 7235 case BuiltinType::Id: \ 7236 return OCLTK_Image; 7237 #include "clang/Basic/OpenCLImageTypes.def" 7238 7239 case BuiltinType::OCLClkEvent: 7240 return OCLTK_ClkEvent; 7241 7242 case BuiltinType::OCLEvent: 7243 return OCLTK_Event; 7244 7245 case BuiltinType::OCLQueue: 7246 return OCLTK_Queue; 7247 7248 case BuiltinType::OCLReserveID: 7249 return OCLTK_ReserveID; 7250 7251 case BuiltinType::OCLSampler: 7252 return OCLTK_Sampler; 7253 7254 default: 7255 return OCLTK_Default; 7256 } 7257 } 7258 7259 LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const { 7260 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)); 7261 } 7262 7263 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty" 7264 /// requires copy/dispose. Note that this must match the logic 7265 /// in buildByrefHelpers. 7266 bool ASTContext::BlockRequiresCopying(QualType Ty, 7267 const VarDecl *D) { 7268 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) { 7269 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr(); 7270 if (!copyExpr && record->hasTrivialDestructor()) return false; 7271 7272 return true; 7273 } 7274 7275 // The block needs copy/destroy helpers if Ty is non-trivial to destructively 7276 // move or destroy. 7277 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType()) 7278 return true; 7279 7280 if (!Ty->isObjCRetainableType()) return false; 7281 7282 Qualifiers qs = Ty.getQualifiers(); 7283 7284 // If we have lifetime, that dominates. 7285 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) { 7286 switch (lifetime) { 7287 case Qualifiers::OCL_None: llvm_unreachable("impossible"); 7288 7289 // These are just bits as far as the runtime is concerned. 7290 case Qualifiers::OCL_ExplicitNone: 7291 case Qualifiers::OCL_Autoreleasing: 7292 return false; 7293 7294 // These cases should have been taken care of when checking the type's 7295 // non-triviality. 7296 case Qualifiers::OCL_Weak: 7297 case Qualifiers::OCL_Strong: 7298 llvm_unreachable("impossible"); 7299 } 7300 llvm_unreachable("fell out of lifetime switch!"); 7301 } 7302 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) || 7303 Ty->isObjCObjectPointerType()); 7304 } 7305 7306 bool ASTContext::getByrefLifetime(QualType Ty, 7307 Qualifiers::ObjCLifetime &LifeTime, 7308 bool &HasByrefExtendedLayout) const { 7309 if (!getLangOpts().ObjC || 7310 getLangOpts().getGC() != LangOptions::NonGC) 7311 return false; 7312 7313 HasByrefExtendedLayout = false; 7314 if (Ty->isRecordType()) { 7315 HasByrefExtendedLayout = true; 7316 LifeTime = Qualifiers::OCL_None; 7317 } else if ((LifeTime = Ty.getObjCLifetime())) { 7318 // Honor the ARC qualifiers. 7319 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) { 7320 // The MRR rule. 7321 LifeTime = Qualifiers::OCL_ExplicitNone; 7322 } else { 7323 LifeTime = Qualifiers::OCL_None; 7324 } 7325 return true; 7326 } 7327 7328 CanQualType ASTContext::getNSUIntegerType() const { 7329 assert(Target && "Expected target to be initialized"); 7330 const llvm::Triple &T = Target->getTriple(); 7331 // Windows is LLP64 rather than LP64 7332 if (T.isOSWindows() && T.isArch64Bit()) 7333 return UnsignedLongLongTy; 7334 return UnsignedLongTy; 7335 } 7336 7337 CanQualType ASTContext::getNSIntegerType() const { 7338 assert(Target && "Expected target to be initialized"); 7339 const llvm::Triple &T = Target->getTriple(); 7340 // Windows is LLP64 rather than LP64 7341 if (T.isOSWindows() && T.isArch64Bit()) 7342 return LongLongTy; 7343 return LongTy; 7344 } 7345 7346 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() { 7347 if (!ObjCInstanceTypeDecl) 7348 ObjCInstanceTypeDecl = 7349 buildImplicitTypedef(getObjCIdType(), "instancetype"); 7350 return ObjCInstanceTypeDecl; 7351 } 7352 7353 // This returns true if a type has been typedefed to BOOL: 7354 // typedef <type> BOOL; 7355 static bool isTypeTypedefedAsBOOL(QualType T) { 7356 if (const auto *TT = dyn_cast<TypedefType>(T)) 7357 if (IdentifierInfo *II = TT->getDecl()->getIdentifier()) 7358 return II->isStr("BOOL"); 7359 7360 return false; 7361 } 7362 7363 /// getObjCEncodingTypeSize returns size of type for objective-c encoding 7364 /// purpose. 7365 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const { 7366 if (!type->isIncompleteArrayType() && type->isIncompleteType()) 7367 return CharUnits::Zero(); 7368 7369 CharUnits sz = getTypeSizeInChars(type); 7370 7371 // Make all integer and enum types at least as large as an int 7372 if (sz.isPositive() && type->isIntegralOrEnumerationType()) 7373 sz = std::max(sz, getTypeSizeInChars(IntTy)); 7374 // Treat arrays as pointers, since that's how they're passed in. 7375 else if (type->isArrayType()) 7376 sz = getTypeSizeInChars(VoidPtrTy); 7377 return sz; 7378 } 7379 7380 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const { 7381 return getTargetInfo().getCXXABI().isMicrosoft() && 7382 VD->isStaticDataMember() && 7383 VD->getType()->isIntegralOrEnumerationType() && 7384 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit(); 7385 } 7386 7387 ASTContext::InlineVariableDefinitionKind 7388 ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const { 7389 if (!VD->isInline()) 7390 return InlineVariableDefinitionKind::None; 7391 7392 // In almost all cases, it's a weak definition. 7393 auto *First = VD->getFirstDecl(); 7394 if (First->isInlineSpecified() || !First->isStaticDataMember()) 7395 return InlineVariableDefinitionKind::Weak; 7396 7397 // If there's a file-context declaration in this translation unit, it's a 7398 // non-discardable definition. 7399 for (auto *D : VD->redecls()) 7400 if (D->getLexicalDeclContext()->isFileContext() && 7401 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr())) 7402 return InlineVariableDefinitionKind::Strong; 7403 7404 // If we've not seen one yet, we don't know. 7405 return InlineVariableDefinitionKind::WeakUnknown; 7406 } 7407 7408 static std::string charUnitsToString(const CharUnits &CU) { 7409 return llvm::itostr(CU.getQuantity()); 7410 } 7411 7412 /// getObjCEncodingForBlock - Return the encoded type for this block 7413 /// declaration. 7414 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const { 7415 std::string S; 7416 7417 const BlockDecl *Decl = Expr->getBlockDecl(); 7418 QualType BlockTy = 7419 Expr->getType()->castAs<BlockPointerType>()->getPointeeType(); 7420 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType(); 7421 // Encode result type. 7422 if (getLangOpts().EncodeExtendedBlockSig) 7423 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, BlockReturnTy, S, 7424 true /*Extended*/); 7425 else 7426 getObjCEncodingForType(BlockReturnTy, S); 7427 // Compute size of all parameters. 7428 // Start with computing size of a pointer in number of bytes. 7429 // FIXME: There might(should) be a better way of doing this computation! 7430 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 7431 CharUnits ParmOffset = PtrSize; 7432 for (auto PI : Decl->parameters()) { 7433 QualType PType = PI->getType(); 7434 CharUnits sz = getObjCEncodingTypeSize(PType); 7435 if (sz.isZero()) 7436 continue; 7437 assert(sz.isPositive() && "BlockExpr - Incomplete param type"); 7438 ParmOffset += sz; 7439 } 7440 // Size of the argument frame 7441 S += charUnitsToString(ParmOffset); 7442 // Block pointer and offset. 7443 S += "@?0"; 7444 7445 // Argument types. 7446 ParmOffset = PtrSize; 7447 for (auto PVDecl : Decl->parameters()) { 7448 QualType PType = PVDecl->getOriginalType(); 7449 if (const auto *AT = 7450 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 7451 // Use array's original type only if it has known number of 7452 // elements. 7453 if (!isa<ConstantArrayType>(AT)) 7454 PType = PVDecl->getType(); 7455 } else if (PType->isFunctionType()) 7456 PType = PVDecl->getType(); 7457 if (getLangOpts().EncodeExtendedBlockSig) 7458 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType, 7459 S, true /*Extended*/); 7460 else 7461 getObjCEncodingForType(PType, S); 7462 S += charUnitsToString(ParmOffset); 7463 ParmOffset += getObjCEncodingTypeSize(PType); 7464 } 7465 7466 return S; 7467 } 7468 7469 std::string 7470 ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const { 7471 std::string S; 7472 // Encode result type. 7473 getObjCEncodingForType(Decl->getReturnType(), S); 7474 CharUnits ParmOffset; 7475 // Compute size of all parameters. 7476 for (auto PI : Decl->parameters()) { 7477 QualType PType = PI->getType(); 7478 CharUnits sz = getObjCEncodingTypeSize(PType); 7479 if (sz.isZero()) 7480 continue; 7481 7482 assert(sz.isPositive() && 7483 "getObjCEncodingForFunctionDecl - Incomplete param type"); 7484 ParmOffset += sz; 7485 } 7486 S += charUnitsToString(ParmOffset); 7487 ParmOffset = CharUnits::Zero(); 7488 7489 // Argument types. 7490 for (auto PVDecl : Decl->parameters()) { 7491 QualType PType = PVDecl->getOriginalType(); 7492 if (const auto *AT = 7493 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 7494 // Use array's original type only if it has known number of 7495 // elements. 7496 if (!isa<ConstantArrayType>(AT)) 7497 PType = PVDecl->getType(); 7498 } else if (PType->isFunctionType()) 7499 PType = PVDecl->getType(); 7500 getObjCEncodingForType(PType, S); 7501 S += charUnitsToString(ParmOffset); 7502 ParmOffset += getObjCEncodingTypeSize(PType); 7503 } 7504 7505 return S; 7506 } 7507 7508 /// getObjCEncodingForMethodParameter - Return the encoded type for a single 7509 /// method parameter or return type. If Extended, include class names and 7510 /// block object types. 7511 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, 7512 QualType T, std::string& S, 7513 bool Extended) const { 7514 // Encode type qualifier, 'in', 'inout', etc. for the parameter. 7515 getObjCEncodingForTypeQualifier(QT, S); 7516 // Encode parameter type. 7517 ObjCEncOptions Options = ObjCEncOptions() 7518 .setExpandPointedToStructures() 7519 .setExpandStructures() 7520 .setIsOutermostType(); 7521 if (Extended) 7522 Options.setEncodeBlockParameters().setEncodeClassNames(); 7523 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr); 7524 } 7525 7526 /// getObjCEncodingForMethodDecl - Return the encoded type for this method 7527 /// declaration. 7528 std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, 7529 bool Extended) const { 7530 // FIXME: This is not very efficient. 7531 // Encode return type. 7532 std::string S; 7533 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(), 7534 Decl->getReturnType(), S, Extended); 7535 // Compute size of all parameters. 7536 // Start with computing size of a pointer in number of bytes. 7537 // FIXME: There might(should) be a better way of doing this computation! 7538 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 7539 // The first two arguments (self and _cmd) are pointers; account for 7540 // their size. 7541 CharUnits ParmOffset = 2 * PtrSize; 7542 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 7543 E = Decl->sel_param_end(); PI != E; ++PI) { 7544 QualType PType = (*PI)->getType(); 7545 CharUnits sz = getObjCEncodingTypeSize(PType); 7546 if (sz.isZero()) 7547 continue; 7548 7549 assert(sz.isPositive() && 7550 "getObjCEncodingForMethodDecl - Incomplete param type"); 7551 ParmOffset += sz; 7552 } 7553 S += charUnitsToString(ParmOffset); 7554 S += "@0:"; 7555 S += charUnitsToString(PtrSize); 7556 7557 // Argument types. 7558 ParmOffset = 2 * PtrSize; 7559 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 7560 E = Decl->sel_param_end(); PI != E; ++PI) { 7561 const ParmVarDecl *PVDecl = *PI; 7562 QualType PType = PVDecl->getOriginalType(); 7563 if (const auto *AT = 7564 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 7565 // Use array's original type only if it has known number of 7566 // elements. 7567 if (!isa<ConstantArrayType>(AT)) 7568 PType = PVDecl->getType(); 7569 } else if (PType->isFunctionType()) 7570 PType = PVDecl->getType(); 7571 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(), 7572 PType, S, Extended); 7573 S += charUnitsToString(ParmOffset); 7574 ParmOffset += getObjCEncodingTypeSize(PType); 7575 } 7576 7577 return S; 7578 } 7579 7580 ObjCPropertyImplDecl * 7581 ASTContext::getObjCPropertyImplDeclForPropertyDecl( 7582 const ObjCPropertyDecl *PD, 7583 const Decl *Container) const { 7584 if (!Container) 7585 return nullptr; 7586 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) { 7587 for (auto *PID : CID->property_impls()) 7588 if (PID->getPropertyDecl() == PD) 7589 return PID; 7590 } else { 7591 const auto *OID = cast<ObjCImplementationDecl>(Container); 7592 for (auto *PID : OID->property_impls()) 7593 if (PID->getPropertyDecl() == PD) 7594 return PID; 7595 } 7596 return nullptr; 7597 } 7598 7599 /// getObjCEncodingForPropertyDecl - Return the encoded type for this 7600 /// property declaration. If non-NULL, Container must be either an 7601 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be 7602 /// NULL when getting encodings for protocol properties. 7603 /// Property attributes are stored as a comma-delimited C string. The simple 7604 /// attributes readonly and bycopy are encoded as single characters. The 7605 /// parametrized attributes, getter=name, setter=name, and ivar=name, are 7606 /// encoded as single characters, followed by an identifier. Property types 7607 /// are also encoded as a parametrized attribute. The characters used to encode 7608 /// these attributes are defined by the following enumeration: 7609 /// @code 7610 /// enum PropertyAttributes { 7611 /// kPropertyReadOnly = 'R', // property is read-only. 7612 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned 7613 /// kPropertyByref = '&', // property is a reference to the value last assigned 7614 /// kPropertyDynamic = 'D', // property is dynamic 7615 /// kPropertyGetter = 'G', // followed by getter selector name 7616 /// kPropertySetter = 'S', // followed by setter selector name 7617 /// kPropertyInstanceVariable = 'V' // followed by instance variable name 7618 /// kPropertyType = 'T' // followed by old-style type encoding. 7619 /// kPropertyWeak = 'W' // 'weak' property 7620 /// kPropertyStrong = 'P' // property GC'able 7621 /// kPropertyNonAtomic = 'N' // property non-atomic 7622 /// }; 7623 /// @endcode 7624 std::string 7625 ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, 7626 const Decl *Container) const { 7627 // Collect information from the property implementation decl(s). 7628 bool Dynamic = false; 7629 ObjCPropertyImplDecl *SynthesizePID = nullptr; 7630 7631 if (ObjCPropertyImplDecl *PropertyImpDecl = 7632 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) { 7633 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) 7634 Dynamic = true; 7635 else 7636 SynthesizePID = PropertyImpDecl; 7637 } 7638 7639 // FIXME: This is not very efficient. 7640 std::string S = "T"; 7641 7642 // Encode result type. 7643 // GCC has some special rules regarding encoding of properties which 7644 // closely resembles encoding of ivars. 7645 getObjCEncodingForPropertyType(PD->getType(), S); 7646 7647 if (PD->isReadOnly()) { 7648 S += ",R"; 7649 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy) 7650 S += ",C"; 7651 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain) 7652 S += ",&"; 7653 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak) 7654 S += ",W"; 7655 } else { 7656 switch (PD->getSetterKind()) { 7657 case ObjCPropertyDecl::Assign: break; 7658 case ObjCPropertyDecl::Copy: S += ",C"; break; 7659 case ObjCPropertyDecl::Retain: S += ",&"; break; 7660 case ObjCPropertyDecl::Weak: S += ",W"; break; 7661 } 7662 } 7663 7664 // It really isn't clear at all what this means, since properties 7665 // are "dynamic by default". 7666 if (Dynamic) 7667 S += ",D"; 7668 7669 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_nonatomic) 7670 S += ",N"; 7671 7672 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) { 7673 S += ",G"; 7674 S += PD->getGetterName().getAsString(); 7675 } 7676 7677 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) { 7678 S += ",S"; 7679 S += PD->getSetterName().getAsString(); 7680 } 7681 7682 if (SynthesizePID) { 7683 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl(); 7684 S += ",V"; 7685 S += OID->getNameAsString(); 7686 } 7687 7688 // FIXME: OBJCGC: weak & strong 7689 return S; 7690 } 7691 7692 /// getLegacyIntegralTypeEncoding - 7693 /// Another legacy compatibility encoding: 32-bit longs are encoded as 7694 /// 'l' or 'L' , but not always. For typedefs, we need to use 7695 /// 'i' or 'I' instead if encoding a struct field, or a pointer! 7696 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const { 7697 if (isa<TypedefType>(PointeeTy.getTypePtr())) { 7698 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) { 7699 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32) 7700 PointeeTy = UnsignedIntTy; 7701 else 7702 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32) 7703 PointeeTy = IntTy; 7704 } 7705 } 7706 } 7707 7708 void ASTContext::getObjCEncodingForType(QualType T, std::string& S, 7709 const FieldDecl *Field, 7710 QualType *NotEncodedT) const { 7711 // We follow the behavior of gcc, expanding structures which are 7712 // directly pointed to, and expanding embedded structures. Note that 7713 // these rules are sufficient to prevent recursive encoding of the 7714 // same type. 7715 getObjCEncodingForTypeImpl(T, S, 7716 ObjCEncOptions() 7717 .setExpandPointedToStructures() 7718 .setExpandStructures() 7719 .setIsOutermostType(), 7720 Field, NotEncodedT); 7721 } 7722 7723 void ASTContext::getObjCEncodingForPropertyType(QualType T, 7724 std::string& S) const { 7725 // Encode result type. 7726 // GCC has some special rules regarding encoding of properties which 7727 // closely resembles encoding of ivars. 7728 getObjCEncodingForTypeImpl(T, S, 7729 ObjCEncOptions() 7730 .setExpandPointedToStructures() 7731 .setExpandStructures() 7732 .setIsOutermostType() 7733 .setEncodingProperty(), 7734 /*Field=*/nullptr); 7735 } 7736 7737 static char getObjCEncodingForPrimitiveType(const ASTContext *C, 7738 const BuiltinType *BT) { 7739 BuiltinType::Kind kind = BT->getKind(); 7740 switch (kind) { 7741 case BuiltinType::Void: return 'v'; 7742 case BuiltinType::Bool: return 'B'; 7743 case BuiltinType::Char8: 7744 case BuiltinType::Char_U: 7745 case BuiltinType::UChar: return 'C'; 7746 case BuiltinType::Char16: 7747 case BuiltinType::UShort: return 'S'; 7748 case BuiltinType::Char32: 7749 case BuiltinType::UInt: return 'I'; 7750 case BuiltinType::ULong: 7751 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q'; 7752 case BuiltinType::UInt128: return 'T'; 7753 case BuiltinType::ULongLong: return 'Q'; 7754 case BuiltinType::Char_S: 7755 case BuiltinType::SChar: return 'c'; 7756 case BuiltinType::Short: return 's'; 7757 case BuiltinType::WChar_S: 7758 case BuiltinType::WChar_U: 7759 case BuiltinType::Int: return 'i'; 7760 case BuiltinType::Long: 7761 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q'; 7762 case BuiltinType::LongLong: return 'q'; 7763 case BuiltinType::Int128: return 't'; 7764 case BuiltinType::Float: return 'f'; 7765 case BuiltinType::Double: return 'd'; 7766 case BuiltinType::LongDouble: return 'D'; 7767 case BuiltinType::NullPtr: return '*'; // like char* 7768 7769 case BuiltinType::BFloat16: 7770 case BuiltinType::Float16: 7771 case BuiltinType::Float128: 7772 case BuiltinType::Ibm128: 7773 case BuiltinType::Half: 7774 case BuiltinType::ShortAccum: 7775 case BuiltinType::Accum: 7776 case BuiltinType::LongAccum: 7777 case BuiltinType::UShortAccum: 7778 case BuiltinType::UAccum: 7779 case BuiltinType::ULongAccum: 7780 case BuiltinType::ShortFract: 7781 case BuiltinType::Fract: 7782 case BuiltinType::LongFract: 7783 case BuiltinType::UShortFract: 7784 case BuiltinType::UFract: 7785 case BuiltinType::ULongFract: 7786 case BuiltinType::SatShortAccum: 7787 case BuiltinType::SatAccum: 7788 case BuiltinType::SatLongAccum: 7789 case BuiltinType::SatUShortAccum: 7790 case BuiltinType::SatUAccum: 7791 case BuiltinType::SatULongAccum: 7792 case BuiltinType::SatShortFract: 7793 case BuiltinType::SatFract: 7794 case BuiltinType::SatLongFract: 7795 case BuiltinType::SatUShortFract: 7796 case BuiltinType::SatUFract: 7797 case BuiltinType::SatULongFract: 7798 // FIXME: potentially need @encodes for these! 7799 return ' '; 7800 7801 #define SVE_TYPE(Name, Id, SingletonId) \ 7802 case BuiltinType::Id: 7803 #include "clang/Basic/AArch64SVEACLETypes.def" 7804 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 7805 #include "clang/Basic/RISCVVTypes.def" 7806 { 7807 DiagnosticsEngine &Diags = C->getDiagnostics(); 7808 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 7809 "cannot yet @encode type %0"); 7810 Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy()); 7811 return ' '; 7812 } 7813 7814 case BuiltinType::ObjCId: 7815 case BuiltinType::ObjCClass: 7816 case BuiltinType::ObjCSel: 7817 llvm_unreachable("@encoding ObjC primitive type"); 7818 7819 // OpenCL and placeholder types don't need @encodings. 7820 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 7821 case BuiltinType::Id: 7822 #include "clang/Basic/OpenCLImageTypes.def" 7823 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 7824 case BuiltinType::Id: 7825 #include "clang/Basic/OpenCLExtensionTypes.def" 7826 case BuiltinType::OCLEvent: 7827 case BuiltinType::OCLClkEvent: 7828 case BuiltinType::OCLQueue: 7829 case BuiltinType::OCLReserveID: 7830 case BuiltinType::OCLSampler: 7831 case BuiltinType::Dependent: 7832 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 7833 case BuiltinType::Id: 7834 #include "clang/Basic/PPCTypes.def" 7835 #define BUILTIN_TYPE(KIND, ID) 7836 #define PLACEHOLDER_TYPE(KIND, ID) \ 7837 case BuiltinType::KIND: 7838 #include "clang/AST/BuiltinTypes.def" 7839 llvm_unreachable("invalid builtin type for @encode"); 7840 } 7841 llvm_unreachable("invalid BuiltinType::Kind value"); 7842 } 7843 7844 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) { 7845 EnumDecl *Enum = ET->getDecl(); 7846 7847 // The encoding of an non-fixed enum type is always 'i', regardless of size. 7848 if (!Enum->isFixed()) 7849 return 'i'; 7850 7851 // The encoding of a fixed enum type matches its fixed underlying type. 7852 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>(); 7853 return getObjCEncodingForPrimitiveType(C, BT); 7854 } 7855 7856 static void EncodeBitField(const ASTContext *Ctx, std::string& S, 7857 QualType T, const FieldDecl *FD) { 7858 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl"); 7859 S += 'b'; 7860 // The NeXT runtime encodes bit fields as b followed by the number of bits. 7861 // The GNU runtime requires more information; bitfields are encoded as b, 7862 // then the offset (in bits) of the first element, then the type of the 7863 // bitfield, then the size in bits. For example, in this structure: 7864 // 7865 // struct 7866 // { 7867 // int integer; 7868 // int flags:2; 7869 // }; 7870 // On a 32-bit system, the encoding for flags would be b2 for the NeXT 7871 // runtime, but b32i2 for the GNU runtime. The reason for this extra 7872 // information is not especially sensible, but we're stuck with it for 7873 // compatibility with GCC, although providing it breaks anything that 7874 // actually uses runtime introspection and wants to work on both runtimes... 7875 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) { 7876 uint64_t Offset; 7877 7878 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) { 7879 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr, 7880 IVD); 7881 } else { 7882 const RecordDecl *RD = FD->getParent(); 7883 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD); 7884 Offset = RL.getFieldOffset(FD->getFieldIndex()); 7885 } 7886 7887 S += llvm::utostr(Offset); 7888 7889 if (const auto *ET = T->getAs<EnumType>()) 7890 S += ObjCEncodingForEnumType(Ctx, ET); 7891 else { 7892 const auto *BT = T->castAs<BuiltinType>(); 7893 S += getObjCEncodingForPrimitiveType(Ctx, BT); 7894 } 7895 } 7896 S += llvm::utostr(FD->getBitWidthValue(*Ctx)); 7897 } 7898 7899 // Helper function for determining whether the encoded type string would include 7900 // a template specialization type. 7901 static bool hasTemplateSpecializationInEncodedString(const Type *T, 7902 bool VisitBasesAndFields) { 7903 T = T->getBaseElementTypeUnsafe(); 7904 7905 if (auto *PT = T->getAs<PointerType>()) 7906 return hasTemplateSpecializationInEncodedString( 7907 PT->getPointeeType().getTypePtr(), false); 7908 7909 auto *CXXRD = T->getAsCXXRecordDecl(); 7910 7911 if (!CXXRD) 7912 return false; 7913 7914 if (isa<ClassTemplateSpecializationDecl>(CXXRD)) 7915 return true; 7916 7917 if (!CXXRD->hasDefinition() || !VisitBasesAndFields) 7918 return false; 7919 7920 for (auto B : CXXRD->bases()) 7921 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(), 7922 true)) 7923 return true; 7924 7925 for (auto *FD : CXXRD->fields()) 7926 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(), 7927 true)) 7928 return true; 7929 7930 return false; 7931 } 7932 7933 // FIXME: Use SmallString for accumulating string. 7934 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S, 7935 const ObjCEncOptions Options, 7936 const FieldDecl *FD, 7937 QualType *NotEncodedT) const { 7938 CanQualType CT = getCanonicalType(T); 7939 switch (CT->getTypeClass()) { 7940 case Type::Builtin: 7941 case Type::Enum: 7942 if (FD && FD->isBitField()) 7943 return EncodeBitField(this, S, T, FD); 7944 if (const auto *BT = dyn_cast<BuiltinType>(CT)) 7945 S += getObjCEncodingForPrimitiveType(this, BT); 7946 else 7947 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT)); 7948 return; 7949 7950 case Type::Complex: 7951 S += 'j'; 7952 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S, 7953 ObjCEncOptions(), 7954 /*Field=*/nullptr); 7955 return; 7956 7957 case Type::Atomic: 7958 S += 'A'; 7959 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S, 7960 ObjCEncOptions(), 7961 /*Field=*/nullptr); 7962 return; 7963 7964 // encoding for pointer or reference types. 7965 case Type::Pointer: 7966 case Type::LValueReference: 7967 case Type::RValueReference: { 7968 QualType PointeeTy; 7969 if (isa<PointerType>(CT)) { 7970 const auto *PT = T->castAs<PointerType>(); 7971 if (PT->isObjCSelType()) { 7972 S += ':'; 7973 return; 7974 } 7975 PointeeTy = PT->getPointeeType(); 7976 } else { 7977 PointeeTy = T->castAs<ReferenceType>()->getPointeeType(); 7978 } 7979 7980 bool isReadOnly = false; 7981 // For historical/compatibility reasons, the read-only qualifier of the 7982 // pointee gets emitted _before_ the '^'. The read-only qualifier of 7983 // the pointer itself gets ignored, _unless_ we are looking at a typedef! 7984 // Also, do not emit the 'r' for anything but the outermost type! 7985 if (isa<TypedefType>(T.getTypePtr())) { 7986 if (Options.IsOutermostType() && T.isConstQualified()) { 7987 isReadOnly = true; 7988 S += 'r'; 7989 } 7990 } else if (Options.IsOutermostType()) { 7991 QualType P = PointeeTy; 7992 while (auto PT = P->getAs<PointerType>()) 7993 P = PT->getPointeeType(); 7994 if (P.isConstQualified()) { 7995 isReadOnly = true; 7996 S += 'r'; 7997 } 7998 } 7999 if (isReadOnly) { 8000 // Another legacy compatibility encoding. Some ObjC qualifier and type 8001 // combinations need to be rearranged. 8002 // Rewrite "in const" from "nr" to "rn" 8003 if (StringRef(S).endswith("nr")) 8004 S.replace(S.end()-2, S.end(), "rn"); 8005 } 8006 8007 if (PointeeTy->isCharType()) { 8008 // char pointer types should be encoded as '*' unless it is a 8009 // type that has been typedef'd to 'BOOL'. 8010 if (!isTypeTypedefedAsBOOL(PointeeTy)) { 8011 S += '*'; 8012 return; 8013 } 8014 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) { 8015 // GCC binary compat: Need to convert "struct objc_class *" to "#". 8016 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) { 8017 S += '#'; 8018 return; 8019 } 8020 // GCC binary compat: Need to convert "struct objc_object *" to "@". 8021 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) { 8022 S += '@'; 8023 return; 8024 } 8025 // If the encoded string for the class includes template names, just emit 8026 // "^v" for pointers to the class. 8027 if (getLangOpts().CPlusPlus && 8028 (!getLangOpts().EncodeCXXClassTemplateSpec && 8029 hasTemplateSpecializationInEncodedString( 8030 RTy, Options.ExpandPointedToStructures()))) { 8031 S += "^v"; 8032 return; 8033 } 8034 // fall through... 8035 } 8036 S += '^'; 8037 getLegacyIntegralTypeEncoding(PointeeTy); 8038 8039 ObjCEncOptions NewOptions; 8040 if (Options.ExpandPointedToStructures()) 8041 NewOptions.setExpandStructures(); 8042 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions, 8043 /*Field=*/nullptr, NotEncodedT); 8044 return; 8045 } 8046 8047 case Type::ConstantArray: 8048 case Type::IncompleteArray: 8049 case Type::VariableArray: { 8050 const auto *AT = cast<ArrayType>(CT); 8051 8052 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) { 8053 // Incomplete arrays are encoded as a pointer to the array element. 8054 S += '^'; 8055 8056 getObjCEncodingForTypeImpl( 8057 AT->getElementType(), S, 8058 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD); 8059 } else { 8060 S += '['; 8061 8062 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) 8063 S += llvm::utostr(CAT->getSize().getZExtValue()); 8064 else { 8065 //Variable length arrays are encoded as a regular array with 0 elements. 8066 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) && 8067 "Unknown array type!"); 8068 S += '0'; 8069 } 8070 8071 getObjCEncodingForTypeImpl( 8072 AT->getElementType(), S, 8073 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD, 8074 NotEncodedT); 8075 S += ']'; 8076 } 8077 return; 8078 } 8079 8080 case Type::FunctionNoProto: 8081 case Type::FunctionProto: 8082 S += '?'; 8083 return; 8084 8085 case Type::Record: { 8086 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl(); 8087 S += RDecl->isUnion() ? '(' : '{'; 8088 // Anonymous structures print as '?' 8089 if (const IdentifierInfo *II = RDecl->getIdentifier()) { 8090 S += II->getName(); 8091 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) { 8092 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 8093 llvm::raw_string_ostream OS(S); 8094 printTemplateArgumentList(OS, TemplateArgs.asArray(), 8095 getPrintingPolicy()); 8096 } 8097 } else { 8098 S += '?'; 8099 } 8100 if (Options.ExpandStructures()) { 8101 S += '='; 8102 if (!RDecl->isUnion()) { 8103 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT); 8104 } else { 8105 for (const auto *Field : RDecl->fields()) { 8106 if (FD) { 8107 S += '"'; 8108 S += Field->getNameAsString(); 8109 S += '"'; 8110 } 8111 8112 // Special case bit-fields. 8113 if (Field->isBitField()) { 8114 getObjCEncodingForTypeImpl(Field->getType(), S, 8115 ObjCEncOptions().setExpandStructures(), 8116 Field); 8117 } else { 8118 QualType qt = Field->getType(); 8119 getLegacyIntegralTypeEncoding(qt); 8120 getObjCEncodingForTypeImpl( 8121 qt, S, 8122 ObjCEncOptions().setExpandStructures().setIsStructField(), FD, 8123 NotEncodedT); 8124 } 8125 } 8126 } 8127 } 8128 S += RDecl->isUnion() ? ')' : '}'; 8129 return; 8130 } 8131 8132 case Type::BlockPointer: { 8133 const auto *BT = T->castAs<BlockPointerType>(); 8134 S += "@?"; // Unlike a pointer-to-function, which is "^?". 8135 if (Options.EncodeBlockParameters()) { 8136 const auto *FT = BT->getPointeeType()->castAs<FunctionType>(); 8137 8138 S += '<'; 8139 // Block return type 8140 getObjCEncodingForTypeImpl(FT->getReturnType(), S, 8141 Options.forComponentType(), FD, NotEncodedT); 8142 // Block self 8143 S += "@?"; 8144 // Block parameters 8145 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) { 8146 for (const auto &I : FPT->param_types()) 8147 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD, 8148 NotEncodedT); 8149 } 8150 S += '>'; 8151 } 8152 return; 8153 } 8154 8155 case Type::ObjCObject: { 8156 // hack to match legacy encoding of *id and *Class 8157 QualType Ty = getObjCObjectPointerType(CT); 8158 if (Ty->isObjCIdType()) { 8159 S += "{objc_object=}"; 8160 return; 8161 } 8162 else if (Ty->isObjCClassType()) { 8163 S += "{objc_class=}"; 8164 return; 8165 } 8166 // TODO: Double check to make sure this intentionally falls through. 8167 LLVM_FALLTHROUGH; 8168 } 8169 8170 case Type::ObjCInterface: { 8171 // Ignore protocol qualifiers when mangling at this level. 8172 // @encode(class_name) 8173 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface(); 8174 S += '{'; 8175 S += OI->getObjCRuntimeNameAsString(); 8176 if (Options.ExpandStructures()) { 8177 S += '='; 8178 SmallVector<const ObjCIvarDecl*, 32> Ivars; 8179 DeepCollectObjCIvars(OI, true, Ivars); 8180 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) { 8181 const FieldDecl *Field = Ivars[i]; 8182 if (Field->isBitField()) 8183 getObjCEncodingForTypeImpl(Field->getType(), S, 8184 ObjCEncOptions().setExpandStructures(), 8185 Field); 8186 else 8187 getObjCEncodingForTypeImpl(Field->getType(), S, 8188 ObjCEncOptions().setExpandStructures(), FD, 8189 NotEncodedT); 8190 } 8191 } 8192 S += '}'; 8193 return; 8194 } 8195 8196 case Type::ObjCObjectPointer: { 8197 const auto *OPT = T->castAs<ObjCObjectPointerType>(); 8198 if (OPT->isObjCIdType()) { 8199 S += '@'; 8200 return; 8201 } 8202 8203 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) { 8204 // FIXME: Consider if we need to output qualifiers for 'Class<p>'. 8205 // Since this is a binary compatibility issue, need to consult with 8206 // runtime folks. Fortunately, this is a *very* obscure construct. 8207 S += '#'; 8208 return; 8209 } 8210 8211 if (OPT->isObjCQualifiedIdType()) { 8212 getObjCEncodingForTypeImpl( 8213 getObjCIdType(), S, 8214 Options.keepingOnly(ObjCEncOptions() 8215 .setExpandPointedToStructures() 8216 .setExpandStructures()), 8217 FD); 8218 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) { 8219 // Note that we do extended encoding of protocol qualifier list 8220 // Only when doing ivar or property encoding. 8221 S += '"'; 8222 for (const auto *I : OPT->quals()) { 8223 S += '<'; 8224 S += I->getObjCRuntimeNameAsString(); 8225 S += '>'; 8226 } 8227 S += '"'; 8228 } 8229 return; 8230 } 8231 8232 S += '@'; 8233 if (OPT->getInterfaceDecl() && 8234 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) { 8235 S += '"'; 8236 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString(); 8237 for (const auto *I : OPT->quals()) { 8238 S += '<'; 8239 S += I->getObjCRuntimeNameAsString(); 8240 S += '>'; 8241 } 8242 S += '"'; 8243 } 8244 return; 8245 } 8246 8247 // gcc just blithely ignores member pointers. 8248 // FIXME: we should do better than that. 'M' is available. 8249 case Type::MemberPointer: 8250 // This matches gcc's encoding, even though technically it is insufficient. 8251 //FIXME. We should do a better job than gcc. 8252 case Type::Vector: 8253 case Type::ExtVector: 8254 // Until we have a coherent encoding of these three types, issue warning. 8255 if (NotEncodedT) 8256 *NotEncodedT = T; 8257 return; 8258 8259 case Type::ConstantMatrix: 8260 if (NotEncodedT) 8261 *NotEncodedT = T; 8262 return; 8263 8264 case Type::BitInt: 8265 if (NotEncodedT) 8266 *NotEncodedT = T; 8267 return; 8268 8269 // We could see an undeduced auto type here during error recovery. 8270 // Just ignore it. 8271 case Type::Auto: 8272 case Type::DeducedTemplateSpecialization: 8273 return; 8274 8275 case Type::Pipe: 8276 #define ABSTRACT_TYPE(KIND, BASE) 8277 #define TYPE(KIND, BASE) 8278 #define DEPENDENT_TYPE(KIND, BASE) \ 8279 case Type::KIND: 8280 #define NON_CANONICAL_TYPE(KIND, BASE) \ 8281 case Type::KIND: 8282 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \ 8283 case Type::KIND: 8284 #include "clang/AST/TypeNodes.inc" 8285 llvm_unreachable("@encode for dependent type!"); 8286 } 8287 llvm_unreachable("bad type kind!"); 8288 } 8289 8290 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl, 8291 std::string &S, 8292 const FieldDecl *FD, 8293 bool includeVBases, 8294 QualType *NotEncodedT) const { 8295 assert(RDecl && "Expected non-null RecordDecl"); 8296 assert(!RDecl->isUnion() && "Should not be called for unions"); 8297 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl()) 8298 return; 8299 8300 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl); 8301 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets; 8302 const ASTRecordLayout &layout = getASTRecordLayout(RDecl); 8303 8304 if (CXXRec) { 8305 for (const auto &BI : CXXRec->bases()) { 8306 if (!BI.isVirtual()) { 8307 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); 8308 if (base->isEmpty()) 8309 continue; 8310 uint64_t offs = toBits(layout.getBaseClassOffset(base)); 8311 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 8312 std::make_pair(offs, base)); 8313 } 8314 } 8315 } 8316 8317 unsigned i = 0; 8318 for (FieldDecl *Field : RDecl->fields()) { 8319 if (!Field->isZeroLengthBitField(*this) && Field->isZeroSize(*this)) 8320 continue; 8321 uint64_t offs = layout.getFieldOffset(i); 8322 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 8323 std::make_pair(offs, Field)); 8324 ++i; 8325 } 8326 8327 if (CXXRec && includeVBases) { 8328 for (const auto &BI : CXXRec->vbases()) { 8329 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); 8330 if (base->isEmpty()) 8331 continue; 8332 uint64_t offs = toBits(layout.getVBaseClassOffset(base)); 8333 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) && 8334 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end()) 8335 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(), 8336 std::make_pair(offs, base)); 8337 } 8338 } 8339 8340 CharUnits size; 8341 if (CXXRec) { 8342 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize(); 8343 } else { 8344 size = layout.getSize(); 8345 } 8346 8347 #ifndef NDEBUG 8348 uint64_t CurOffs = 0; 8349 #endif 8350 std::multimap<uint64_t, NamedDecl *>::iterator 8351 CurLayObj = FieldOrBaseOffsets.begin(); 8352 8353 if (CXXRec && CXXRec->isDynamicClass() && 8354 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) { 8355 if (FD) { 8356 S += "\"_vptr$"; 8357 std::string recname = CXXRec->getNameAsString(); 8358 if (recname.empty()) recname = "?"; 8359 S += recname; 8360 S += '"'; 8361 } 8362 S += "^^?"; 8363 #ifndef NDEBUG 8364 CurOffs += getTypeSize(VoidPtrTy); 8365 #endif 8366 } 8367 8368 if (!RDecl->hasFlexibleArrayMember()) { 8369 // Mark the end of the structure. 8370 uint64_t offs = toBits(size); 8371 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 8372 std::make_pair(offs, nullptr)); 8373 } 8374 8375 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) { 8376 #ifndef NDEBUG 8377 assert(CurOffs <= CurLayObj->first); 8378 if (CurOffs < CurLayObj->first) { 8379 uint64_t padding = CurLayObj->first - CurOffs; 8380 // FIXME: There doesn't seem to be a way to indicate in the encoding that 8381 // packing/alignment of members is different that normal, in which case 8382 // the encoding will be out-of-sync with the real layout. 8383 // If the runtime switches to just consider the size of types without 8384 // taking into account alignment, we could make padding explicit in the 8385 // encoding (e.g. using arrays of chars). The encoding strings would be 8386 // longer then though. 8387 CurOffs += padding; 8388 } 8389 #endif 8390 8391 NamedDecl *dcl = CurLayObj->second; 8392 if (!dcl) 8393 break; // reached end of structure. 8394 8395 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) { 8396 // We expand the bases without their virtual bases since those are going 8397 // in the initial structure. Note that this differs from gcc which 8398 // expands virtual bases each time one is encountered in the hierarchy, 8399 // making the encoding type bigger than it really is. 8400 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false, 8401 NotEncodedT); 8402 assert(!base->isEmpty()); 8403 #ifndef NDEBUG 8404 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize()); 8405 #endif 8406 } else { 8407 const auto *field = cast<FieldDecl>(dcl); 8408 if (FD) { 8409 S += '"'; 8410 S += field->getNameAsString(); 8411 S += '"'; 8412 } 8413 8414 if (field->isBitField()) { 8415 EncodeBitField(this, S, field->getType(), field); 8416 #ifndef NDEBUG 8417 CurOffs += field->getBitWidthValue(*this); 8418 #endif 8419 } else { 8420 QualType qt = field->getType(); 8421 getLegacyIntegralTypeEncoding(qt); 8422 getObjCEncodingForTypeImpl( 8423 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(), 8424 FD, NotEncodedT); 8425 #ifndef NDEBUG 8426 CurOffs += getTypeSize(field->getType()); 8427 #endif 8428 } 8429 } 8430 } 8431 } 8432 8433 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, 8434 std::string& S) const { 8435 if (QT & Decl::OBJC_TQ_In) 8436 S += 'n'; 8437 if (QT & Decl::OBJC_TQ_Inout) 8438 S += 'N'; 8439 if (QT & Decl::OBJC_TQ_Out) 8440 S += 'o'; 8441 if (QT & Decl::OBJC_TQ_Bycopy) 8442 S += 'O'; 8443 if (QT & Decl::OBJC_TQ_Byref) 8444 S += 'R'; 8445 if (QT & Decl::OBJC_TQ_Oneway) 8446 S += 'V'; 8447 } 8448 8449 TypedefDecl *ASTContext::getObjCIdDecl() const { 8450 if (!ObjCIdDecl) { 8451 QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {}); 8452 T = getObjCObjectPointerType(T); 8453 ObjCIdDecl = buildImplicitTypedef(T, "id"); 8454 } 8455 return ObjCIdDecl; 8456 } 8457 8458 TypedefDecl *ASTContext::getObjCSelDecl() const { 8459 if (!ObjCSelDecl) { 8460 QualType T = getPointerType(ObjCBuiltinSelTy); 8461 ObjCSelDecl = buildImplicitTypedef(T, "SEL"); 8462 } 8463 return ObjCSelDecl; 8464 } 8465 8466 TypedefDecl *ASTContext::getObjCClassDecl() const { 8467 if (!ObjCClassDecl) { 8468 QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {}); 8469 T = getObjCObjectPointerType(T); 8470 ObjCClassDecl = buildImplicitTypedef(T, "Class"); 8471 } 8472 return ObjCClassDecl; 8473 } 8474 8475 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const { 8476 if (!ObjCProtocolClassDecl) { 8477 ObjCProtocolClassDecl 8478 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(), 8479 SourceLocation(), 8480 &Idents.get("Protocol"), 8481 /*typeParamList=*/nullptr, 8482 /*PrevDecl=*/nullptr, 8483 SourceLocation(), true); 8484 } 8485 8486 return ObjCProtocolClassDecl; 8487 } 8488 8489 //===----------------------------------------------------------------------===// 8490 // __builtin_va_list Construction Functions 8491 //===----------------------------------------------------------------------===// 8492 8493 static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context, 8494 StringRef Name) { 8495 // typedef char* __builtin[_ms]_va_list; 8496 QualType T = Context->getPointerType(Context->CharTy); 8497 return Context->buildImplicitTypedef(T, Name); 8498 } 8499 8500 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) { 8501 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list"); 8502 } 8503 8504 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) { 8505 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list"); 8506 } 8507 8508 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) { 8509 // typedef void* __builtin_va_list; 8510 QualType T = Context->getPointerType(Context->VoidTy); 8511 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 8512 } 8513 8514 static TypedefDecl * 8515 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) { 8516 // struct __va_list 8517 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list"); 8518 if (Context->getLangOpts().CPlusPlus) { 8519 // namespace std { struct __va_list { 8520 auto *NS = NamespaceDecl::Create( 8521 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(), 8522 /*Inline*/ false, SourceLocation(), SourceLocation(), 8523 &Context->Idents.get("std"), 8524 /*PrevDecl*/ nullptr); 8525 NS->setImplicit(); 8526 VaListTagDecl->setDeclContext(NS); 8527 } 8528 8529 VaListTagDecl->startDefinition(); 8530 8531 const size_t NumFields = 5; 8532 QualType FieldTypes[NumFields]; 8533 const char *FieldNames[NumFields]; 8534 8535 // void *__stack; 8536 FieldTypes[0] = Context->getPointerType(Context->VoidTy); 8537 FieldNames[0] = "__stack"; 8538 8539 // void *__gr_top; 8540 FieldTypes[1] = Context->getPointerType(Context->VoidTy); 8541 FieldNames[1] = "__gr_top"; 8542 8543 // void *__vr_top; 8544 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8545 FieldNames[2] = "__vr_top"; 8546 8547 // int __gr_offs; 8548 FieldTypes[3] = Context->IntTy; 8549 FieldNames[3] = "__gr_offs"; 8550 8551 // int __vr_offs; 8552 FieldTypes[4] = Context->IntTy; 8553 FieldNames[4] = "__vr_offs"; 8554 8555 // Create fields 8556 for (unsigned i = 0; i < NumFields; ++i) { 8557 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8558 VaListTagDecl, 8559 SourceLocation(), 8560 SourceLocation(), 8561 &Context->Idents.get(FieldNames[i]), 8562 FieldTypes[i], /*TInfo=*/nullptr, 8563 /*BitWidth=*/nullptr, 8564 /*Mutable=*/false, 8565 ICIS_NoInit); 8566 Field->setAccess(AS_public); 8567 VaListTagDecl->addDecl(Field); 8568 } 8569 VaListTagDecl->completeDefinition(); 8570 Context->VaListTagDecl = VaListTagDecl; 8571 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8572 8573 // } __builtin_va_list; 8574 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list"); 8575 } 8576 8577 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) { 8578 // typedef struct __va_list_tag { 8579 RecordDecl *VaListTagDecl; 8580 8581 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8582 VaListTagDecl->startDefinition(); 8583 8584 const size_t NumFields = 5; 8585 QualType FieldTypes[NumFields]; 8586 const char *FieldNames[NumFields]; 8587 8588 // unsigned char gpr; 8589 FieldTypes[0] = Context->UnsignedCharTy; 8590 FieldNames[0] = "gpr"; 8591 8592 // unsigned char fpr; 8593 FieldTypes[1] = Context->UnsignedCharTy; 8594 FieldNames[1] = "fpr"; 8595 8596 // unsigned short reserved; 8597 FieldTypes[2] = Context->UnsignedShortTy; 8598 FieldNames[2] = "reserved"; 8599 8600 // void* overflow_arg_area; 8601 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 8602 FieldNames[3] = "overflow_arg_area"; 8603 8604 // void* reg_save_area; 8605 FieldTypes[4] = Context->getPointerType(Context->VoidTy); 8606 FieldNames[4] = "reg_save_area"; 8607 8608 // Create fields 8609 for (unsigned i = 0; i < NumFields; ++i) { 8610 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl, 8611 SourceLocation(), 8612 SourceLocation(), 8613 &Context->Idents.get(FieldNames[i]), 8614 FieldTypes[i], /*TInfo=*/nullptr, 8615 /*BitWidth=*/nullptr, 8616 /*Mutable=*/false, 8617 ICIS_NoInit); 8618 Field->setAccess(AS_public); 8619 VaListTagDecl->addDecl(Field); 8620 } 8621 VaListTagDecl->completeDefinition(); 8622 Context->VaListTagDecl = VaListTagDecl; 8623 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8624 8625 // } __va_list_tag; 8626 TypedefDecl *VaListTagTypedefDecl = 8627 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); 8628 8629 QualType VaListTagTypedefType = 8630 Context->getTypedefType(VaListTagTypedefDecl); 8631 8632 // typedef __va_list_tag __builtin_va_list[1]; 8633 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8634 QualType VaListTagArrayType 8635 = Context->getConstantArrayType(VaListTagTypedefType, 8636 Size, nullptr, ArrayType::Normal, 0); 8637 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8638 } 8639 8640 static TypedefDecl * 8641 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) { 8642 // struct __va_list_tag { 8643 RecordDecl *VaListTagDecl; 8644 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8645 VaListTagDecl->startDefinition(); 8646 8647 const size_t NumFields = 4; 8648 QualType FieldTypes[NumFields]; 8649 const char *FieldNames[NumFields]; 8650 8651 // unsigned gp_offset; 8652 FieldTypes[0] = Context->UnsignedIntTy; 8653 FieldNames[0] = "gp_offset"; 8654 8655 // unsigned fp_offset; 8656 FieldTypes[1] = Context->UnsignedIntTy; 8657 FieldNames[1] = "fp_offset"; 8658 8659 // void* overflow_arg_area; 8660 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8661 FieldNames[2] = "overflow_arg_area"; 8662 8663 // void* reg_save_area; 8664 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 8665 FieldNames[3] = "reg_save_area"; 8666 8667 // Create fields 8668 for (unsigned i = 0; i < NumFields; ++i) { 8669 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8670 VaListTagDecl, 8671 SourceLocation(), 8672 SourceLocation(), 8673 &Context->Idents.get(FieldNames[i]), 8674 FieldTypes[i], /*TInfo=*/nullptr, 8675 /*BitWidth=*/nullptr, 8676 /*Mutable=*/false, 8677 ICIS_NoInit); 8678 Field->setAccess(AS_public); 8679 VaListTagDecl->addDecl(Field); 8680 } 8681 VaListTagDecl->completeDefinition(); 8682 Context->VaListTagDecl = VaListTagDecl; 8683 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8684 8685 // }; 8686 8687 // typedef struct __va_list_tag __builtin_va_list[1]; 8688 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8689 QualType VaListTagArrayType = Context->getConstantArrayType( 8690 VaListTagType, Size, nullptr, ArrayType::Normal, 0); 8691 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8692 } 8693 8694 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) { 8695 // typedef int __builtin_va_list[4]; 8696 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4); 8697 QualType IntArrayType = Context->getConstantArrayType( 8698 Context->IntTy, Size, nullptr, ArrayType::Normal, 0); 8699 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list"); 8700 } 8701 8702 static TypedefDecl * 8703 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) { 8704 // struct __va_list 8705 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list"); 8706 if (Context->getLangOpts().CPlusPlus) { 8707 // namespace std { struct __va_list { 8708 NamespaceDecl *NS; 8709 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context), 8710 Context->getTranslationUnitDecl(), 8711 /*Inline*/false, SourceLocation(), 8712 SourceLocation(), &Context->Idents.get("std"), 8713 /*PrevDecl*/ nullptr); 8714 NS->setImplicit(); 8715 VaListDecl->setDeclContext(NS); 8716 } 8717 8718 VaListDecl->startDefinition(); 8719 8720 // void * __ap; 8721 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8722 VaListDecl, 8723 SourceLocation(), 8724 SourceLocation(), 8725 &Context->Idents.get("__ap"), 8726 Context->getPointerType(Context->VoidTy), 8727 /*TInfo=*/nullptr, 8728 /*BitWidth=*/nullptr, 8729 /*Mutable=*/false, 8730 ICIS_NoInit); 8731 Field->setAccess(AS_public); 8732 VaListDecl->addDecl(Field); 8733 8734 // }; 8735 VaListDecl->completeDefinition(); 8736 Context->VaListTagDecl = VaListDecl; 8737 8738 // typedef struct __va_list __builtin_va_list; 8739 QualType T = Context->getRecordType(VaListDecl); 8740 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 8741 } 8742 8743 static TypedefDecl * 8744 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) { 8745 // struct __va_list_tag { 8746 RecordDecl *VaListTagDecl; 8747 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8748 VaListTagDecl->startDefinition(); 8749 8750 const size_t NumFields = 4; 8751 QualType FieldTypes[NumFields]; 8752 const char *FieldNames[NumFields]; 8753 8754 // long __gpr; 8755 FieldTypes[0] = Context->LongTy; 8756 FieldNames[0] = "__gpr"; 8757 8758 // long __fpr; 8759 FieldTypes[1] = Context->LongTy; 8760 FieldNames[1] = "__fpr"; 8761 8762 // void *__overflow_arg_area; 8763 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8764 FieldNames[2] = "__overflow_arg_area"; 8765 8766 // void *__reg_save_area; 8767 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 8768 FieldNames[3] = "__reg_save_area"; 8769 8770 // Create fields 8771 for (unsigned i = 0; i < NumFields; ++i) { 8772 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8773 VaListTagDecl, 8774 SourceLocation(), 8775 SourceLocation(), 8776 &Context->Idents.get(FieldNames[i]), 8777 FieldTypes[i], /*TInfo=*/nullptr, 8778 /*BitWidth=*/nullptr, 8779 /*Mutable=*/false, 8780 ICIS_NoInit); 8781 Field->setAccess(AS_public); 8782 VaListTagDecl->addDecl(Field); 8783 } 8784 VaListTagDecl->completeDefinition(); 8785 Context->VaListTagDecl = VaListTagDecl; 8786 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8787 8788 // }; 8789 8790 // typedef __va_list_tag __builtin_va_list[1]; 8791 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8792 QualType VaListTagArrayType = Context->getConstantArrayType( 8793 VaListTagType, Size, nullptr, ArrayType::Normal, 0); 8794 8795 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8796 } 8797 8798 static TypedefDecl *CreateHexagonBuiltinVaListDecl(const ASTContext *Context) { 8799 // typedef struct __va_list_tag { 8800 RecordDecl *VaListTagDecl; 8801 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8802 VaListTagDecl->startDefinition(); 8803 8804 const size_t NumFields = 3; 8805 QualType FieldTypes[NumFields]; 8806 const char *FieldNames[NumFields]; 8807 8808 // void *CurrentSavedRegisterArea; 8809 FieldTypes[0] = Context->getPointerType(Context->VoidTy); 8810 FieldNames[0] = "__current_saved_reg_area_pointer"; 8811 8812 // void *SavedRegAreaEnd; 8813 FieldTypes[1] = Context->getPointerType(Context->VoidTy); 8814 FieldNames[1] = "__saved_reg_area_end_pointer"; 8815 8816 // void *OverflowArea; 8817 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8818 FieldNames[2] = "__overflow_area_pointer"; 8819 8820 // Create fields 8821 for (unsigned i = 0; i < NumFields; ++i) { 8822 FieldDecl *Field = FieldDecl::Create( 8823 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(), 8824 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i], 8825 /*TInfo=*/nullptr, 8826 /*BitWidth=*/nullptr, 8827 /*Mutable=*/false, ICIS_NoInit); 8828 Field->setAccess(AS_public); 8829 VaListTagDecl->addDecl(Field); 8830 } 8831 VaListTagDecl->completeDefinition(); 8832 Context->VaListTagDecl = VaListTagDecl; 8833 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8834 8835 // } __va_list_tag; 8836 TypedefDecl *VaListTagTypedefDecl = 8837 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); 8838 8839 QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl); 8840 8841 // typedef __va_list_tag __builtin_va_list[1]; 8842 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8843 QualType VaListTagArrayType = Context->getConstantArrayType( 8844 VaListTagTypedefType, Size, nullptr, ArrayType::Normal, 0); 8845 8846 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8847 } 8848 8849 static TypedefDecl *CreateVaListDecl(const ASTContext *Context, 8850 TargetInfo::BuiltinVaListKind Kind) { 8851 switch (Kind) { 8852 case TargetInfo::CharPtrBuiltinVaList: 8853 return CreateCharPtrBuiltinVaListDecl(Context); 8854 case TargetInfo::VoidPtrBuiltinVaList: 8855 return CreateVoidPtrBuiltinVaListDecl(Context); 8856 case TargetInfo::AArch64ABIBuiltinVaList: 8857 return CreateAArch64ABIBuiltinVaListDecl(Context); 8858 case TargetInfo::PowerABIBuiltinVaList: 8859 return CreatePowerABIBuiltinVaListDecl(Context); 8860 case TargetInfo::X86_64ABIBuiltinVaList: 8861 return CreateX86_64ABIBuiltinVaListDecl(Context); 8862 case TargetInfo::PNaClABIBuiltinVaList: 8863 return CreatePNaClABIBuiltinVaListDecl(Context); 8864 case TargetInfo::AAPCSABIBuiltinVaList: 8865 return CreateAAPCSABIBuiltinVaListDecl(Context); 8866 case TargetInfo::SystemZBuiltinVaList: 8867 return CreateSystemZBuiltinVaListDecl(Context); 8868 case TargetInfo::HexagonBuiltinVaList: 8869 return CreateHexagonBuiltinVaListDecl(Context); 8870 } 8871 8872 llvm_unreachable("Unhandled __builtin_va_list type kind"); 8873 } 8874 8875 TypedefDecl *ASTContext::getBuiltinVaListDecl() const { 8876 if (!BuiltinVaListDecl) { 8877 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind()); 8878 assert(BuiltinVaListDecl->isImplicit()); 8879 } 8880 8881 return BuiltinVaListDecl; 8882 } 8883 8884 Decl *ASTContext::getVaListTagDecl() const { 8885 // Force the creation of VaListTagDecl by building the __builtin_va_list 8886 // declaration. 8887 if (!VaListTagDecl) 8888 (void)getBuiltinVaListDecl(); 8889 8890 return VaListTagDecl; 8891 } 8892 8893 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const { 8894 if (!BuiltinMSVaListDecl) 8895 BuiltinMSVaListDecl = CreateMSVaListDecl(this); 8896 8897 return BuiltinMSVaListDecl; 8898 } 8899 8900 bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const { 8901 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID()); 8902 } 8903 8904 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) { 8905 assert(ObjCConstantStringType.isNull() && 8906 "'NSConstantString' type already set!"); 8907 8908 ObjCConstantStringType = getObjCInterfaceType(Decl); 8909 } 8910 8911 /// Retrieve the template name that corresponds to a non-empty 8912 /// lookup. 8913 TemplateName 8914 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin, 8915 UnresolvedSetIterator End) const { 8916 unsigned size = End - Begin; 8917 assert(size > 1 && "set is not overloaded!"); 8918 8919 void *memory = Allocate(sizeof(OverloadedTemplateStorage) + 8920 size * sizeof(FunctionTemplateDecl*)); 8921 auto *OT = new (memory) OverloadedTemplateStorage(size); 8922 8923 NamedDecl **Storage = OT->getStorage(); 8924 for (UnresolvedSetIterator I = Begin; I != End; ++I) { 8925 NamedDecl *D = *I; 8926 assert(isa<FunctionTemplateDecl>(D) || 8927 isa<UnresolvedUsingValueDecl>(D) || 8928 (isa<UsingShadowDecl>(D) && 8929 isa<FunctionTemplateDecl>(D->getUnderlyingDecl()))); 8930 *Storage++ = D; 8931 } 8932 8933 return TemplateName(OT); 8934 } 8935 8936 /// Retrieve a template name representing an unqualified-id that has been 8937 /// assumed to name a template for ADL purposes. 8938 TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const { 8939 auto *OT = new (*this) AssumedTemplateStorage(Name); 8940 return TemplateName(OT); 8941 } 8942 8943 /// Retrieve the template name that represents a qualified 8944 /// template name such as \c std::vector. 8945 TemplateName 8946 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, 8947 bool TemplateKeyword, 8948 TemplateDecl *Template) const { 8949 assert(NNS && "Missing nested-name-specifier in qualified template name"); 8950 8951 // FIXME: Canonicalization? 8952 llvm::FoldingSetNodeID ID; 8953 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template); 8954 8955 void *InsertPos = nullptr; 8956 QualifiedTemplateName *QTN = 8957 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 8958 if (!QTN) { 8959 QTN = new (*this, alignof(QualifiedTemplateName)) 8960 QualifiedTemplateName(NNS, TemplateKeyword, Template); 8961 QualifiedTemplateNames.InsertNode(QTN, InsertPos); 8962 } 8963 8964 return TemplateName(QTN); 8965 } 8966 8967 /// Retrieve the template name that represents a dependent 8968 /// template name such as \c MetaFun::template apply. 8969 TemplateName 8970 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 8971 const IdentifierInfo *Name) const { 8972 assert((!NNS || NNS->isDependent()) && 8973 "Nested name specifier must be dependent"); 8974 8975 llvm::FoldingSetNodeID ID; 8976 DependentTemplateName::Profile(ID, NNS, Name); 8977 8978 void *InsertPos = nullptr; 8979 DependentTemplateName *QTN = 8980 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 8981 8982 if (QTN) 8983 return TemplateName(QTN); 8984 8985 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 8986 if (CanonNNS == NNS) { 8987 QTN = new (*this, alignof(DependentTemplateName)) 8988 DependentTemplateName(NNS, Name); 8989 } else { 8990 TemplateName Canon = getDependentTemplateName(CanonNNS, Name); 8991 QTN = new (*this, alignof(DependentTemplateName)) 8992 DependentTemplateName(NNS, Name, Canon); 8993 DependentTemplateName *CheckQTN = 8994 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 8995 assert(!CheckQTN && "Dependent type name canonicalization broken"); 8996 (void)CheckQTN; 8997 } 8998 8999 DependentTemplateNames.InsertNode(QTN, InsertPos); 9000 return TemplateName(QTN); 9001 } 9002 9003 /// Retrieve the template name that represents a dependent 9004 /// template name such as \c MetaFun::template operator+. 9005 TemplateName 9006 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 9007 OverloadedOperatorKind Operator) const { 9008 assert((!NNS || NNS->isDependent()) && 9009 "Nested name specifier must be dependent"); 9010 9011 llvm::FoldingSetNodeID ID; 9012 DependentTemplateName::Profile(ID, NNS, Operator); 9013 9014 void *InsertPos = nullptr; 9015 DependentTemplateName *QTN 9016 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 9017 9018 if (QTN) 9019 return TemplateName(QTN); 9020 9021 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 9022 if (CanonNNS == NNS) { 9023 QTN = new (*this, alignof(DependentTemplateName)) 9024 DependentTemplateName(NNS, Operator); 9025 } else { 9026 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator); 9027 QTN = new (*this, alignof(DependentTemplateName)) 9028 DependentTemplateName(NNS, Operator, Canon); 9029 9030 DependentTemplateName *CheckQTN 9031 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 9032 assert(!CheckQTN && "Dependent template name canonicalization broken"); 9033 (void)CheckQTN; 9034 } 9035 9036 DependentTemplateNames.InsertNode(QTN, InsertPos); 9037 return TemplateName(QTN); 9038 } 9039 9040 TemplateName 9041 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param, 9042 TemplateName replacement) const { 9043 llvm::FoldingSetNodeID ID; 9044 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement); 9045 9046 void *insertPos = nullptr; 9047 SubstTemplateTemplateParmStorage *subst 9048 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos); 9049 9050 if (!subst) { 9051 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement); 9052 SubstTemplateTemplateParms.InsertNode(subst, insertPos); 9053 } 9054 9055 return TemplateName(subst); 9056 } 9057 9058 TemplateName 9059 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param, 9060 const TemplateArgument &ArgPack) const { 9061 auto &Self = const_cast<ASTContext &>(*this); 9062 llvm::FoldingSetNodeID ID; 9063 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack); 9064 9065 void *InsertPos = nullptr; 9066 SubstTemplateTemplateParmPackStorage *Subst 9067 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos); 9068 9069 if (!Subst) { 9070 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param, 9071 ArgPack.pack_size(), 9072 ArgPack.pack_begin()); 9073 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos); 9074 } 9075 9076 return TemplateName(Subst); 9077 } 9078 9079 /// getFromTargetType - Given one of the integer types provided by 9080 /// TargetInfo, produce the corresponding type. The unsigned @p Type 9081 /// is actually a value of type @c TargetInfo::IntType. 9082 CanQualType ASTContext::getFromTargetType(unsigned Type) const { 9083 switch (Type) { 9084 case TargetInfo::NoInt: return {}; 9085 case TargetInfo::SignedChar: return SignedCharTy; 9086 case TargetInfo::UnsignedChar: return UnsignedCharTy; 9087 case TargetInfo::SignedShort: return ShortTy; 9088 case TargetInfo::UnsignedShort: return UnsignedShortTy; 9089 case TargetInfo::SignedInt: return IntTy; 9090 case TargetInfo::UnsignedInt: return UnsignedIntTy; 9091 case TargetInfo::SignedLong: return LongTy; 9092 case TargetInfo::UnsignedLong: return UnsignedLongTy; 9093 case TargetInfo::SignedLongLong: return LongLongTy; 9094 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy; 9095 } 9096 9097 llvm_unreachable("Unhandled TargetInfo::IntType value"); 9098 } 9099 9100 //===----------------------------------------------------------------------===// 9101 // Type Predicates. 9102 //===----------------------------------------------------------------------===// 9103 9104 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's 9105 /// garbage collection attribute. 9106 /// 9107 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const { 9108 if (getLangOpts().getGC() == LangOptions::NonGC) 9109 return Qualifiers::GCNone; 9110 9111 assert(getLangOpts().ObjC); 9112 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr(); 9113 9114 // Default behaviour under objective-C's gc is for ObjC pointers 9115 // (or pointers to them) be treated as though they were declared 9116 // as __strong. 9117 if (GCAttrs == Qualifiers::GCNone) { 9118 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) 9119 return Qualifiers::Strong; 9120 else if (Ty->isPointerType()) 9121 return getObjCGCAttrKind(Ty->castAs<PointerType>()->getPointeeType()); 9122 } else { 9123 // It's not valid to set GC attributes on anything that isn't a 9124 // pointer. 9125 #ifndef NDEBUG 9126 QualType CT = Ty->getCanonicalTypeInternal(); 9127 while (const auto *AT = dyn_cast<ArrayType>(CT)) 9128 CT = AT->getElementType(); 9129 assert(CT->isAnyPointerType() || CT->isBlockPointerType()); 9130 #endif 9131 } 9132 return GCAttrs; 9133 } 9134 9135 //===----------------------------------------------------------------------===// 9136 // Type Compatibility Testing 9137 //===----------------------------------------------------------------------===// 9138 9139 /// areCompatVectorTypes - Return true if the two specified vector types are 9140 /// compatible. 9141 static bool areCompatVectorTypes(const VectorType *LHS, 9142 const VectorType *RHS) { 9143 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 9144 return LHS->getElementType() == RHS->getElementType() && 9145 LHS->getNumElements() == RHS->getNumElements(); 9146 } 9147 9148 /// areCompatMatrixTypes - Return true if the two specified matrix types are 9149 /// compatible. 9150 static bool areCompatMatrixTypes(const ConstantMatrixType *LHS, 9151 const ConstantMatrixType *RHS) { 9152 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 9153 return LHS->getElementType() == RHS->getElementType() && 9154 LHS->getNumRows() == RHS->getNumRows() && 9155 LHS->getNumColumns() == RHS->getNumColumns(); 9156 } 9157 9158 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec, 9159 QualType SecondVec) { 9160 assert(FirstVec->isVectorType() && "FirstVec should be a vector type"); 9161 assert(SecondVec->isVectorType() && "SecondVec should be a vector type"); 9162 9163 if (hasSameUnqualifiedType(FirstVec, SecondVec)) 9164 return true; 9165 9166 // Treat Neon vector types and most AltiVec vector types as if they are the 9167 // equivalent GCC vector types. 9168 const auto *First = FirstVec->castAs<VectorType>(); 9169 const auto *Second = SecondVec->castAs<VectorType>(); 9170 if (First->getNumElements() == Second->getNumElements() && 9171 hasSameType(First->getElementType(), Second->getElementType()) && 9172 First->getVectorKind() != VectorType::AltiVecPixel && 9173 First->getVectorKind() != VectorType::AltiVecBool && 9174 Second->getVectorKind() != VectorType::AltiVecPixel && 9175 Second->getVectorKind() != VectorType::AltiVecBool && 9176 First->getVectorKind() != VectorType::SveFixedLengthDataVector && 9177 First->getVectorKind() != VectorType::SveFixedLengthPredicateVector && 9178 Second->getVectorKind() != VectorType::SveFixedLengthDataVector && 9179 Second->getVectorKind() != VectorType::SveFixedLengthPredicateVector) 9180 return true; 9181 9182 return false; 9183 } 9184 9185 /// getSVETypeSize - Return SVE vector or predicate register size. 9186 static uint64_t getSVETypeSize(ASTContext &Context, const BuiltinType *Ty) { 9187 assert(Ty->isVLSTBuiltinType() && "Invalid SVE Type"); 9188 return Ty->getKind() == BuiltinType::SveBool 9189 ? (Context.getLangOpts().VScaleMin * 128) / Context.getCharWidth() 9190 : Context.getLangOpts().VScaleMin * 128; 9191 } 9192 9193 bool ASTContext::areCompatibleSveTypes(QualType FirstType, 9194 QualType SecondType) { 9195 assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) || 9196 (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) && 9197 "Expected SVE builtin type and vector type!"); 9198 9199 auto IsValidCast = [this](QualType FirstType, QualType SecondType) { 9200 if (const auto *BT = FirstType->getAs<BuiltinType>()) { 9201 if (const auto *VT = SecondType->getAs<VectorType>()) { 9202 // Predicates have the same representation as uint8 so we also have to 9203 // check the kind to make these types incompatible. 9204 if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 9205 return BT->getKind() == BuiltinType::SveBool; 9206 else if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) 9207 return VT->getElementType().getCanonicalType() == 9208 FirstType->getSveEltType(*this); 9209 else if (VT->getVectorKind() == VectorType::GenericVector) 9210 return getTypeSize(SecondType) == getSVETypeSize(*this, BT) && 9211 hasSameType(VT->getElementType(), 9212 getBuiltinVectorTypeInfo(BT).ElementType); 9213 } 9214 } 9215 return false; 9216 }; 9217 9218 return IsValidCast(FirstType, SecondType) || 9219 IsValidCast(SecondType, FirstType); 9220 } 9221 9222 bool ASTContext::areLaxCompatibleSveTypes(QualType FirstType, 9223 QualType SecondType) { 9224 assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) || 9225 (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) && 9226 "Expected SVE builtin type and vector type!"); 9227 9228 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) { 9229 const auto *BT = FirstType->getAs<BuiltinType>(); 9230 if (!BT) 9231 return false; 9232 9233 const auto *VecTy = SecondType->getAs<VectorType>(); 9234 if (VecTy && 9235 (VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector || 9236 VecTy->getVectorKind() == VectorType::GenericVector)) { 9237 const LangOptions::LaxVectorConversionKind LVCKind = 9238 getLangOpts().getLaxVectorConversions(); 9239 9240 // Can not convert between sve predicates and sve vectors because of 9241 // different size. 9242 if (BT->getKind() == BuiltinType::SveBool && 9243 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector) 9244 return false; 9245 9246 // If __ARM_FEATURE_SVE_BITS != N do not allow GNU vector lax conversion. 9247 // "Whenever __ARM_FEATURE_SVE_BITS==N, GNUT implicitly 9248 // converts to VLAT and VLAT implicitly converts to GNUT." 9249 // ACLE Spec Version 00bet6, 3.7.3.2. Behavior common to vectors and 9250 // predicates. 9251 if (VecTy->getVectorKind() == VectorType::GenericVector && 9252 getTypeSize(SecondType) != getSVETypeSize(*this, BT)) 9253 return false; 9254 9255 // If -flax-vector-conversions=all is specified, the types are 9256 // certainly compatible. 9257 if (LVCKind == LangOptions::LaxVectorConversionKind::All) 9258 return true; 9259 9260 // If -flax-vector-conversions=integer is specified, the types are 9261 // compatible if the elements are integer types. 9262 if (LVCKind == LangOptions::LaxVectorConversionKind::Integer) 9263 return VecTy->getElementType().getCanonicalType()->isIntegerType() && 9264 FirstType->getSveEltType(*this)->isIntegerType(); 9265 } 9266 9267 return false; 9268 }; 9269 9270 return IsLaxCompatible(FirstType, SecondType) || 9271 IsLaxCompatible(SecondType, FirstType); 9272 } 9273 9274 bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const { 9275 while (true) { 9276 // __strong id 9277 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) { 9278 if (Attr->getAttrKind() == attr::ObjCOwnership) 9279 return true; 9280 9281 Ty = Attr->getModifiedType(); 9282 9283 // X *__strong (...) 9284 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) { 9285 Ty = Paren->getInnerType(); 9286 9287 // We do not want to look through typedefs, typeof(expr), 9288 // typeof(type), or any other way that the type is somehow 9289 // abstracted. 9290 } else { 9291 return false; 9292 } 9293 } 9294 } 9295 9296 //===----------------------------------------------------------------------===// 9297 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's. 9298 //===----------------------------------------------------------------------===// 9299 9300 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the 9301 /// inheritance hierarchy of 'rProto'. 9302 bool 9303 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, 9304 ObjCProtocolDecl *rProto) const { 9305 if (declaresSameEntity(lProto, rProto)) 9306 return true; 9307 for (auto *PI : rProto->protocols()) 9308 if (ProtocolCompatibleWithProtocol(lProto, PI)) 9309 return true; 9310 return false; 9311 } 9312 9313 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and 9314 /// Class<pr1, ...>. 9315 bool ASTContext::ObjCQualifiedClassTypesAreCompatible( 9316 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) { 9317 for (auto *lhsProto : lhs->quals()) { 9318 bool match = false; 9319 for (auto *rhsProto : rhs->quals()) { 9320 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) { 9321 match = true; 9322 break; 9323 } 9324 } 9325 if (!match) 9326 return false; 9327 } 9328 return true; 9329 } 9330 9331 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an 9332 /// ObjCQualifiedIDType. 9333 bool ASTContext::ObjCQualifiedIdTypesAreCompatible( 9334 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs, 9335 bool compare) { 9336 // Allow id<P..> and an 'id' in all cases. 9337 if (lhs->isObjCIdType() || rhs->isObjCIdType()) 9338 return true; 9339 9340 // Don't allow id<P..> to convert to Class or Class<P..> in either direction. 9341 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() || 9342 rhs->isObjCClassType() || rhs->isObjCQualifiedClassType()) 9343 return false; 9344 9345 if (lhs->isObjCQualifiedIdType()) { 9346 if (rhs->qual_empty()) { 9347 // If the RHS is a unqualified interface pointer "NSString*", 9348 // make sure we check the class hierarchy. 9349 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) { 9350 for (auto *I : lhs->quals()) { 9351 // when comparing an id<P> on lhs with a static type on rhs, 9352 // see if static class implements all of id's protocols, directly or 9353 // through its super class and categories. 9354 if (!rhsID->ClassImplementsProtocol(I, true)) 9355 return false; 9356 } 9357 } 9358 // If there are no qualifiers and no interface, we have an 'id'. 9359 return true; 9360 } 9361 // Both the right and left sides have qualifiers. 9362 for (auto *lhsProto : lhs->quals()) { 9363 bool match = false; 9364 9365 // when comparing an id<P> on lhs with a static type on rhs, 9366 // see if static class implements all of id's protocols, directly or 9367 // through its super class and categories. 9368 for (auto *rhsProto : rhs->quals()) { 9369 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 9370 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 9371 match = true; 9372 break; 9373 } 9374 } 9375 // If the RHS is a qualified interface pointer "NSString<P>*", 9376 // make sure we check the class hierarchy. 9377 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) { 9378 for (auto *I : lhs->quals()) { 9379 // when comparing an id<P> on lhs with a static type on rhs, 9380 // see if static class implements all of id's protocols, directly or 9381 // through its super class and categories. 9382 if (rhsID->ClassImplementsProtocol(I, true)) { 9383 match = true; 9384 break; 9385 } 9386 } 9387 } 9388 if (!match) 9389 return false; 9390 } 9391 9392 return true; 9393 } 9394 9395 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>"); 9396 9397 if (lhs->getInterfaceType()) { 9398 // If both the right and left sides have qualifiers. 9399 for (auto *lhsProto : lhs->quals()) { 9400 bool match = false; 9401 9402 // when comparing an id<P> on rhs with a static type on lhs, 9403 // see if static class implements all of id's protocols, directly or 9404 // through its super class and categories. 9405 // First, lhs protocols in the qualifier list must be found, direct 9406 // or indirect in rhs's qualifier list or it is a mismatch. 9407 for (auto *rhsProto : rhs->quals()) { 9408 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 9409 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 9410 match = true; 9411 break; 9412 } 9413 } 9414 if (!match) 9415 return false; 9416 } 9417 9418 // Static class's protocols, or its super class or category protocols 9419 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch. 9420 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) { 9421 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols; 9422 CollectInheritedProtocols(lhsID, LHSInheritedProtocols); 9423 // This is rather dubious but matches gcc's behavior. If lhs has 9424 // no type qualifier and its class has no static protocol(s) 9425 // assume that it is mismatch. 9426 if (LHSInheritedProtocols.empty() && lhs->qual_empty()) 9427 return false; 9428 for (auto *lhsProto : LHSInheritedProtocols) { 9429 bool match = false; 9430 for (auto *rhsProto : rhs->quals()) { 9431 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 9432 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 9433 match = true; 9434 break; 9435 } 9436 } 9437 if (!match) 9438 return false; 9439 } 9440 } 9441 return true; 9442 } 9443 return false; 9444 } 9445 9446 /// canAssignObjCInterfaces - Return true if the two interface types are 9447 /// compatible for assignment from RHS to LHS. This handles validation of any 9448 /// protocol qualifiers on the LHS or RHS. 9449 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, 9450 const ObjCObjectPointerType *RHSOPT) { 9451 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 9452 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 9453 9454 // If either type represents the built-in 'id' type, return true. 9455 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId()) 9456 return true; 9457 9458 // Function object that propagates a successful result or handles 9459 // __kindof types. 9460 auto finish = [&](bool succeeded) -> bool { 9461 if (succeeded) 9462 return true; 9463 9464 if (!RHS->isKindOfType()) 9465 return false; 9466 9467 // Strip off __kindof and protocol qualifiers, then check whether 9468 // we can assign the other way. 9469 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this), 9470 LHSOPT->stripObjCKindOfTypeAndQuals(*this)); 9471 }; 9472 9473 // Casts from or to id<P> are allowed when the other side has compatible 9474 // protocols. 9475 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) { 9476 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false)); 9477 } 9478 9479 // Verify protocol compatibility for casts from Class<P1> to Class<P2>. 9480 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) { 9481 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT)); 9482 } 9483 9484 // Casts from Class to Class<Foo>, or vice-versa, are allowed. 9485 if (LHS->isObjCClass() && RHS->isObjCClass()) { 9486 return true; 9487 } 9488 9489 // If we have 2 user-defined types, fall into that path. 9490 if (LHS->getInterface() && RHS->getInterface()) { 9491 return finish(canAssignObjCInterfaces(LHS, RHS)); 9492 } 9493 9494 return false; 9495 } 9496 9497 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written 9498 /// for providing type-safety for objective-c pointers used to pass/return 9499 /// arguments in block literals. When passed as arguments, passing 'A*' where 9500 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is 9501 /// not OK. For the return type, the opposite is not OK. 9502 bool ASTContext::canAssignObjCInterfacesInBlockPointer( 9503 const ObjCObjectPointerType *LHSOPT, 9504 const ObjCObjectPointerType *RHSOPT, 9505 bool BlockReturnType) { 9506 9507 // Function object that propagates a successful result or handles 9508 // __kindof types. 9509 auto finish = [&](bool succeeded) -> bool { 9510 if (succeeded) 9511 return true; 9512 9513 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT; 9514 if (!Expected->isKindOfType()) 9515 return false; 9516 9517 // Strip off __kindof and protocol qualifiers, then check whether 9518 // we can assign the other way. 9519 return canAssignObjCInterfacesInBlockPointer( 9520 RHSOPT->stripObjCKindOfTypeAndQuals(*this), 9521 LHSOPT->stripObjCKindOfTypeAndQuals(*this), 9522 BlockReturnType); 9523 }; 9524 9525 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType()) 9526 return true; 9527 9528 if (LHSOPT->isObjCBuiltinType()) { 9529 return finish(RHSOPT->isObjCBuiltinType() || 9530 RHSOPT->isObjCQualifiedIdType()); 9531 } 9532 9533 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) { 9534 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking) 9535 // Use for block parameters previous type checking for compatibility. 9536 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) || 9537 // Or corrected type checking as in non-compat mode. 9538 (!BlockReturnType && 9539 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false))); 9540 else 9541 return finish(ObjCQualifiedIdTypesAreCompatible( 9542 (BlockReturnType ? LHSOPT : RHSOPT), 9543 (BlockReturnType ? RHSOPT : LHSOPT), false)); 9544 } 9545 9546 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType(); 9547 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType(); 9548 if (LHS && RHS) { // We have 2 user-defined types. 9549 if (LHS != RHS) { 9550 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl())) 9551 return finish(BlockReturnType); 9552 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl())) 9553 return finish(!BlockReturnType); 9554 } 9555 else 9556 return true; 9557 } 9558 return false; 9559 } 9560 9561 /// Comparison routine for Objective-C protocols to be used with 9562 /// llvm::array_pod_sort. 9563 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs, 9564 ObjCProtocolDecl * const *rhs) { 9565 return (*lhs)->getName().compare((*rhs)->getName()); 9566 } 9567 9568 /// getIntersectionOfProtocols - This routine finds the intersection of set 9569 /// of protocols inherited from two distinct objective-c pointer objects with 9570 /// the given common base. 9571 /// It is used to build composite qualifier list of the composite type of 9572 /// the conditional expression involving two objective-c pointer objects. 9573 static 9574 void getIntersectionOfProtocols(ASTContext &Context, 9575 const ObjCInterfaceDecl *CommonBase, 9576 const ObjCObjectPointerType *LHSOPT, 9577 const ObjCObjectPointerType *RHSOPT, 9578 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) { 9579 9580 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 9581 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 9582 assert(LHS->getInterface() && "LHS must have an interface base"); 9583 assert(RHS->getInterface() && "RHS must have an interface base"); 9584 9585 // Add all of the protocols for the LHS. 9586 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet; 9587 9588 // Start with the protocol qualifiers. 9589 for (auto proto : LHS->quals()) { 9590 Context.CollectInheritedProtocols(proto, LHSProtocolSet); 9591 } 9592 9593 // Also add the protocols associated with the LHS interface. 9594 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet); 9595 9596 // Add all of the protocols for the RHS. 9597 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet; 9598 9599 // Start with the protocol qualifiers. 9600 for (auto proto : RHS->quals()) { 9601 Context.CollectInheritedProtocols(proto, RHSProtocolSet); 9602 } 9603 9604 // Also add the protocols associated with the RHS interface. 9605 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet); 9606 9607 // Compute the intersection of the collected protocol sets. 9608 for (auto proto : LHSProtocolSet) { 9609 if (RHSProtocolSet.count(proto)) 9610 IntersectionSet.push_back(proto); 9611 } 9612 9613 // Compute the set of protocols that is implied by either the common type or 9614 // the protocols within the intersection. 9615 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols; 9616 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols); 9617 9618 // Remove any implied protocols from the list of inherited protocols. 9619 if (!ImpliedProtocols.empty()) { 9620 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool { 9621 return ImpliedProtocols.contains(proto); 9622 }); 9623 } 9624 9625 // Sort the remaining protocols by name. 9626 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(), 9627 compareObjCProtocolsByName); 9628 } 9629 9630 /// Determine whether the first type is a subtype of the second. 9631 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs, 9632 QualType rhs) { 9633 // Common case: two object pointers. 9634 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>(); 9635 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 9636 if (lhsOPT && rhsOPT) 9637 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT); 9638 9639 // Two block pointers. 9640 const auto *lhsBlock = lhs->getAs<BlockPointerType>(); 9641 const auto *rhsBlock = rhs->getAs<BlockPointerType>(); 9642 if (lhsBlock && rhsBlock) 9643 return ctx.typesAreBlockPointerCompatible(lhs, rhs); 9644 9645 // If either is an unqualified 'id' and the other is a block, it's 9646 // acceptable. 9647 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) || 9648 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock)) 9649 return true; 9650 9651 return false; 9652 } 9653 9654 // Check that the given Objective-C type argument lists are equivalent. 9655 static bool sameObjCTypeArgs(ASTContext &ctx, 9656 const ObjCInterfaceDecl *iface, 9657 ArrayRef<QualType> lhsArgs, 9658 ArrayRef<QualType> rhsArgs, 9659 bool stripKindOf) { 9660 if (lhsArgs.size() != rhsArgs.size()) 9661 return false; 9662 9663 ObjCTypeParamList *typeParams = iface->getTypeParamList(); 9664 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) { 9665 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i])) 9666 continue; 9667 9668 switch (typeParams->begin()[i]->getVariance()) { 9669 case ObjCTypeParamVariance::Invariant: 9670 if (!stripKindOf || 9671 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx), 9672 rhsArgs[i].stripObjCKindOfType(ctx))) { 9673 return false; 9674 } 9675 break; 9676 9677 case ObjCTypeParamVariance::Covariant: 9678 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i])) 9679 return false; 9680 break; 9681 9682 case ObjCTypeParamVariance::Contravariant: 9683 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i])) 9684 return false; 9685 break; 9686 } 9687 } 9688 9689 return true; 9690 } 9691 9692 QualType ASTContext::areCommonBaseCompatible( 9693 const ObjCObjectPointerType *Lptr, 9694 const ObjCObjectPointerType *Rptr) { 9695 const ObjCObjectType *LHS = Lptr->getObjectType(); 9696 const ObjCObjectType *RHS = Rptr->getObjectType(); 9697 const ObjCInterfaceDecl* LDecl = LHS->getInterface(); 9698 const ObjCInterfaceDecl* RDecl = RHS->getInterface(); 9699 9700 if (!LDecl || !RDecl) 9701 return {}; 9702 9703 // When either LHS or RHS is a kindof type, we should return a kindof type. 9704 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return 9705 // kindof(A). 9706 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType(); 9707 9708 // Follow the left-hand side up the class hierarchy until we either hit a 9709 // root or find the RHS. Record the ancestors in case we don't find it. 9710 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4> 9711 LHSAncestors; 9712 while (true) { 9713 // Record this ancestor. We'll need this if the common type isn't in the 9714 // path from the LHS to the root. 9715 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS; 9716 9717 if (declaresSameEntity(LHS->getInterface(), RDecl)) { 9718 // Get the type arguments. 9719 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten(); 9720 bool anyChanges = false; 9721 if (LHS->isSpecialized() && RHS->isSpecialized()) { 9722 // Both have type arguments, compare them. 9723 if (!sameObjCTypeArgs(*this, LHS->getInterface(), 9724 LHS->getTypeArgs(), RHS->getTypeArgs(), 9725 /*stripKindOf=*/true)) 9726 return {}; 9727 } else if (LHS->isSpecialized() != RHS->isSpecialized()) { 9728 // If only one has type arguments, the result will not have type 9729 // arguments. 9730 LHSTypeArgs = {}; 9731 anyChanges = true; 9732 } 9733 9734 // Compute the intersection of protocols. 9735 SmallVector<ObjCProtocolDecl *, 8> Protocols; 9736 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr, 9737 Protocols); 9738 if (!Protocols.empty()) 9739 anyChanges = true; 9740 9741 // If anything in the LHS will have changed, build a new result type. 9742 // If we need to return a kindof type but LHS is not a kindof type, we 9743 // build a new result type. 9744 if (anyChanges || LHS->isKindOfType() != anyKindOf) { 9745 QualType Result = getObjCInterfaceType(LHS->getInterface()); 9746 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols, 9747 anyKindOf || LHS->isKindOfType()); 9748 return getObjCObjectPointerType(Result); 9749 } 9750 9751 return getObjCObjectPointerType(QualType(LHS, 0)); 9752 } 9753 9754 // Find the superclass. 9755 QualType LHSSuperType = LHS->getSuperClassType(); 9756 if (LHSSuperType.isNull()) 9757 break; 9758 9759 LHS = LHSSuperType->castAs<ObjCObjectType>(); 9760 } 9761 9762 // We didn't find anything by following the LHS to its root; now check 9763 // the RHS against the cached set of ancestors. 9764 while (true) { 9765 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl()); 9766 if (KnownLHS != LHSAncestors.end()) { 9767 LHS = KnownLHS->second; 9768 9769 // Get the type arguments. 9770 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten(); 9771 bool anyChanges = false; 9772 if (LHS->isSpecialized() && RHS->isSpecialized()) { 9773 // Both have type arguments, compare them. 9774 if (!sameObjCTypeArgs(*this, LHS->getInterface(), 9775 LHS->getTypeArgs(), RHS->getTypeArgs(), 9776 /*stripKindOf=*/true)) 9777 return {}; 9778 } else if (LHS->isSpecialized() != RHS->isSpecialized()) { 9779 // If only one has type arguments, the result will not have type 9780 // arguments. 9781 RHSTypeArgs = {}; 9782 anyChanges = true; 9783 } 9784 9785 // Compute the intersection of protocols. 9786 SmallVector<ObjCProtocolDecl *, 8> Protocols; 9787 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr, 9788 Protocols); 9789 if (!Protocols.empty()) 9790 anyChanges = true; 9791 9792 // If we need to return a kindof type but RHS is not a kindof type, we 9793 // build a new result type. 9794 if (anyChanges || RHS->isKindOfType() != anyKindOf) { 9795 QualType Result = getObjCInterfaceType(RHS->getInterface()); 9796 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols, 9797 anyKindOf || RHS->isKindOfType()); 9798 return getObjCObjectPointerType(Result); 9799 } 9800 9801 return getObjCObjectPointerType(QualType(RHS, 0)); 9802 } 9803 9804 // Find the superclass of the RHS. 9805 QualType RHSSuperType = RHS->getSuperClassType(); 9806 if (RHSSuperType.isNull()) 9807 break; 9808 9809 RHS = RHSSuperType->castAs<ObjCObjectType>(); 9810 } 9811 9812 return {}; 9813 } 9814 9815 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS, 9816 const ObjCObjectType *RHS) { 9817 assert(LHS->getInterface() && "LHS is not an interface type"); 9818 assert(RHS->getInterface() && "RHS is not an interface type"); 9819 9820 // Verify that the base decls are compatible: the RHS must be a subclass of 9821 // the LHS. 9822 ObjCInterfaceDecl *LHSInterface = LHS->getInterface(); 9823 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface()); 9824 if (!IsSuperClass) 9825 return false; 9826 9827 // If the LHS has protocol qualifiers, determine whether all of them are 9828 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the 9829 // LHS). 9830 if (LHS->getNumProtocols() > 0) { 9831 // OK if conversion of LHS to SuperClass results in narrowing of types 9832 // ; i.e., SuperClass may implement at least one of the protocols 9833 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok. 9834 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>. 9835 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols; 9836 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols); 9837 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's 9838 // qualifiers. 9839 for (auto *RHSPI : RHS->quals()) 9840 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols); 9841 // If there is no protocols associated with RHS, it is not a match. 9842 if (SuperClassInheritedProtocols.empty()) 9843 return false; 9844 9845 for (const auto *LHSProto : LHS->quals()) { 9846 bool SuperImplementsProtocol = false; 9847 for (auto *SuperClassProto : SuperClassInheritedProtocols) 9848 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) { 9849 SuperImplementsProtocol = true; 9850 break; 9851 } 9852 if (!SuperImplementsProtocol) 9853 return false; 9854 } 9855 } 9856 9857 // If the LHS is specialized, we may need to check type arguments. 9858 if (LHS->isSpecialized()) { 9859 // Follow the superclass chain until we've matched the LHS class in the 9860 // hierarchy. This substitutes type arguments through. 9861 const ObjCObjectType *RHSSuper = RHS; 9862 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface)) 9863 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>(); 9864 9865 // If the RHS is specializd, compare type arguments. 9866 if (RHSSuper->isSpecialized() && 9867 !sameObjCTypeArgs(*this, LHS->getInterface(), 9868 LHS->getTypeArgs(), RHSSuper->getTypeArgs(), 9869 /*stripKindOf=*/true)) { 9870 return false; 9871 } 9872 } 9873 9874 return true; 9875 } 9876 9877 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) { 9878 // get the "pointed to" types 9879 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>(); 9880 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>(); 9881 9882 if (!LHSOPT || !RHSOPT) 9883 return false; 9884 9885 return canAssignObjCInterfaces(LHSOPT, RHSOPT) || 9886 canAssignObjCInterfaces(RHSOPT, LHSOPT); 9887 } 9888 9889 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) { 9890 return canAssignObjCInterfaces( 9891 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(), 9892 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>()); 9893 } 9894 9895 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible, 9896 /// both shall have the identically qualified version of a compatible type. 9897 /// C99 6.2.7p1: Two types have compatible types if their types are the 9898 /// same. See 6.7.[2,3,5] for additional rules. 9899 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS, 9900 bool CompareUnqualified) { 9901 if (getLangOpts().CPlusPlus) 9902 return hasSameType(LHS, RHS); 9903 9904 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull(); 9905 } 9906 9907 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) { 9908 return typesAreCompatible(LHS, RHS); 9909 } 9910 9911 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) { 9912 return !mergeTypes(LHS, RHS, true).isNull(); 9913 } 9914 9915 /// mergeTransparentUnionType - if T is a transparent union type and a member 9916 /// of T is compatible with SubType, return the merged type, else return 9917 /// QualType() 9918 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType, 9919 bool OfBlockPointer, 9920 bool Unqualified) { 9921 if (const RecordType *UT = T->getAsUnionType()) { 9922 RecordDecl *UD = UT->getDecl(); 9923 if (UD->hasAttr<TransparentUnionAttr>()) { 9924 for (const auto *I : UD->fields()) { 9925 QualType ET = I->getType().getUnqualifiedType(); 9926 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified); 9927 if (!MT.isNull()) 9928 return MT; 9929 } 9930 } 9931 } 9932 9933 return {}; 9934 } 9935 9936 /// mergeFunctionParameterTypes - merge two types which appear as function 9937 /// parameter types 9938 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs, 9939 bool OfBlockPointer, 9940 bool Unqualified) { 9941 // GNU extension: two types are compatible if they appear as a function 9942 // argument, one of the types is a transparent union type and the other 9943 // type is compatible with a union member 9944 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer, 9945 Unqualified); 9946 if (!lmerge.isNull()) 9947 return lmerge; 9948 9949 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer, 9950 Unqualified); 9951 if (!rmerge.isNull()) 9952 return rmerge; 9953 9954 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified); 9955 } 9956 9957 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, 9958 bool OfBlockPointer, bool Unqualified, 9959 bool AllowCXX) { 9960 const auto *lbase = lhs->castAs<FunctionType>(); 9961 const auto *rbase = rhs->castAs<FunctionType>(); 9962 const auto *lproto = dyn_cast<FunctionProtoType>(lbase); 9963 const auto *rproto = dyn_cast<FunctionProtoType>(rbase); 9964 bool allLTypes = true; 9965 bool allRTypes = true; 9966 9967 // Check return type 9968 QualType retType; 9969 if (OfBlockPointer) { 9970 QualType RHS = rbase->getReturnType(); 9971 QualType LHS = lbase->getReturnType(); 9972 bool UnqualifiedResult = Unqualified; 9973 if (!UnqualifiedResult) 9974 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers()); 9975 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true); 9976 } 9977 else 9978 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false, 9979 Unqualified); 9980 if (retType.isNull()) 9981 return {}; 9982 9983 if (Unqualified) 9984 retType = retType.getUnqualifiedType(); 9985 9986 CanQualType LRetType = getCanonicalType(lbase->getReturnType()); 9987 CanQualType RRetType = getCanonicalType(rbase->getReturnType()); 9988 if (Unqualified) { 9989 LRetType = LRetType.getUnqualifiedType(); 9990 RRetType = RRetType.getUnqualifiedType(); 9991 } 9992 9993 if (getCanonicalType(retType) != LRetType) 9994 allLTypes = false; 9995 if (getCanonicalType(retType) != RRetType) 9996 allRTypes = false; 9997 9998 // FIXME: double check this 9999 // FIXME: should we error if lbase->getRegParmAttr() != 0 && 10000 // rbase->getRegParmAttr() != 0 && 10001 // lbase->getRegParmAttr() != rbase->getRegParmAttr()? 10002 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo(); 10003 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo(); 10004 10005 // Compatible functions must have compatible calling conventions 10006 if (lbaseInfo.getCC() != rbaseInfo.getCC()) 10007 return {}; 10008 10009 // Regparm is part of the calling convention. 10010 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm()) 10011 return {}; 10012 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm()) 10013 return {}; 10014 10015 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult()) 10016 return {}; 10017 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs()) 10018 return {}; 10019 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck()) 10020 return {}; 10021 10022 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'. 10023 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn(); 10024 10025 if (lbaseInfo.getNoReturn() != NoReturn) 10026 allLTypes = false; 10027 if (rbaseInfo.getNoReturn() != NoReturn) 10028 allRTypes = false; 10029 10030 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn); 10031 10032 if (lproto && rproto) { // two C99 style function prototypes 10033 assert((AllowCXX || 10034 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) && 10035 "C++ shouldn't be here"); 10036 // Compatible functions must have the same number of parameters 10037 if (lproto->getNumParams() != rproto->getNumParams()) 10038 return {}; 10039 10040 // Variadic and non-variadic functions aren't compatible 10041 if (lproto->isVariadic() != rproto->isVariadic()) 10042 return {}; 10043 10044 if (lproto->getMethodQuals() != rproto->getMethodQuals()) 10045 return {}; 10046 10047 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos; 10048 bool canUseLeft, canUseRight; 10049 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight, 10050 newParamInfos)) 10051 return {}; 10052 10053 if (!canUseLeft) 10054 allLTypes = false; 10055 if (!canUseRight) 10056 allRTypes = false; 10057 10058 // Check parameter type compatibility 10059 SmallVector<QualType, 10> types; 10060 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) { 10061 QualType lParamType = lproto->getParamType(i).getUnqualifiedType(); 10062 QualType rParamType = rproto->getParamType(i).getUnqualifiedType(); 10063 QualType paramType = mergeFunctionParameterTypes( 10064 lParamType, rParamType, OfBlockPointer, Unqualified); 10065 if (paramType.isNull()) 10066 return {}; 10067 10068 if (Unqualified) 10069 paramType = paramType.getUnqualifiedType(); 10070 10071 types.push_back(paramType); 10072 if (Unqualified) { 10073 lParamType = lParamType.getUnqualifiedType(); 10074 rParamType = rParamType.getUnqualifiedType(); 10075 } 10076 10077 if (getCanonicalType(paramType) != getCanonicalType(lParamType)) 10078 allLTypes = false; 10079 if (getCanonicalType(paramType) != getCanonicalType(rParamType)) 10080 allRTypes = false; 10081 } 10082 10083 if (allLTypes) return lhs; 10084 if (allRTypes) return rhs; 10085 10086 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo(); 10087 EPI.ExtInfo = einfo; 10088 EPI.ExtParameterInfos = 10089 newParamInfos.empty() ? nullptr : newParamInfos.data(); 10090 return getFunctionType(retType, types, EPI); 10091 } 10092 10093 if (lproto) allRTypes = false; 10094 if (rproto) allLTypes = false; 10095 10096 const FunctionProtoType *proto = lproto ? lproto : rproto; 10097 if (proto) { 10098 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here"); 10099 if (proto->isVariadic()) 10100 return {}; 10101 // Check that the types are compatible with the types that 10102 // would result from default argument promotions (C99 6.7.5.3p15). 10103 // The only types actually affected are promotable integer 10104 // types and floats, which would be passed as a different 10105 // type depending on whether the prototype is visible. 10106 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) { 10107 QualType paramTy = proto->getParamType(i); 10108 10109 // Look at the converted type of enum types, since that is the type used 10110 // to pass enum values. 10111 if (const auto *Enum = paramTy->getAs<EnumType>()) { 10112 paramTy = Enum->getDecl()->getIntegerType(); 10113 if (paramTy.isNull()) 10114 return {}; 10115 } 10116 10117 if (paramTy->isPromotableIntegerType() || 10118 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy) 10119 return {}; 10120 } 10121 10122 if (allLTypes) return lhs; 10123 if (allRTypes) return rhs; 10124 10125 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo(); 10126 EPI.ExtInfo = einfo; 10127 return getFunctionType(retType, proto->getParamTypes(), EPI); 10128 } 10129 10130 if (allLTypes) return lhs; 10131 if (allRTypes) return rhs; 10132 return getFunctionNoProtoType(retType, einfo); 10133 } 10134 10135 /// Given that we have an enum type and a non-enum type, try to merge them. 10136 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET, 10137 QualType other, bool isBlockReturnType) { 10138 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char, 10139 // a signed integer type, or an unsigned integer type. 10140 // Compatibility is based on the underlying type, not the promotion 10141 // type. 10142 QualType underlyingType = ET->getDecl()->getIntegerType(); 10143 if (underlyingType.isNull()) 10144 return {}; 10145 if (Context.hasSameType(underlyingType, other)) 10146 return other; 10147 10148 // In block return types, we're more permissive and accept any 10149 // integral type of the same size. 10150 if (isBlockReturnType && other->isIntegerType() && 10151 Context.getTypeSize(underlyingType) == Context.getTypeSize(other)) 10152 return other; 10153 10154 return {}; 10155 } 10156 10157 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, 10158 bool OfBlockPointer, 10159 bool Unqualified, bool BlockReturnType) { 10160 // For C++ we will not reach this code with reference types (see below), 10161 // for OpenMP variant call overloading we might. 10162 // 10163 // C++ [expr]: If an expression initially has the type "reference to T", the 10164 // type is adjusted to "T" prior to any further analysis, the expression 10165 // designates the object or function denoted by the reference, and the 10166 // expression is an lvalue unless the reference is an rvalue reference and 10167 // the expression is a function call (possibly inside parentheses). 10168 auto *LHSRefTy = LHS->getAs<ReferenceType>(); 10169 auto *RHSRefTy = RHS->getAs<ReferenceType>(); 10170 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy && 10171 LHS->getTypeClass() == RHS->getTypeClass()) 10172 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(), 10173 OfBlockPointer, Unqualified, BlockReturnType); 10174 if (LHSRefTy || RHSRefTy) 10175 return {}; 10176 10177 if (Unqualified) { 10178 LHS = LHS.getUnqualifiedType(); 10179 RHS = RHS.getUnqualifiedType(); 10180 } 10181 10182 QualType LHSCan = getCanonicalType(LHS), 10183 RHSCan = getCanonicalType(RHS); 10184 10185 // If two types are identical, they are compatible. 10186 if (LHSCan == RHSCan) 10187 return LHS; 10188 10189 // If the qualifiers are different, the types aren't compatible... mostly. 10190 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 10191 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 10192 if (LQuals != RQuals) { 10193 // If any of these qualifiers are different, we have a type 10194 // mismatch. 10195 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 10196 LQuals.getAddressSpace() != RQuals.getAddressSpace() || 10197 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() || 10198 LQuals.hasUnaligned() != RQuals.hasUnaligned()) 10199 return {}; 10200 10201 // Exactly one GC qualifier difference is allowed: __strong is 10202 // okay if the other type has no GC qualifier but is an Objective 10203 // C object pointer (i.e. implicitly strong by default). We fix 10204 // this by pretending that the unqualified type was actually 10205 // qualified __strong. 10206 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 10207 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 10208 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 10209 10210 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 10211 return {}; 10212 10213 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) { 10214 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong)); 10215 } 10216 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) { 10217 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS); 10218 } 10219 return {}; 10220 } 10221 10222 // Okay, qualifiers are equal. 10223 10224 Type::TypeClass LHSClass = LHSCan->getTypeClass(); 10225 Type::TypeClass RHSClass = RHSCan->getTypeClass(); 10226 10227 // We want to consider the two function types to be the same for these 10228 // comparisons, just force one to the other. 10229 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto; 10230 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto; 10231 10232 // Same as above for arrays 10233 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray) 10234 LHSClass = Type::ConstantArray; 10235 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray) 10236 RHSClass = Type::ConstantArray; 10237 10238 // ObjCInterfaces are just specialized ObjCObjects. 10239 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject; 10240 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject; 10241 10242 // Canonicalize ExtVector -> Vector. 10243 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector; 10244 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector; 10245 10246 // If the canonical type classes don't match. 10247 if (LHSClass != RHSClass) { 10248 // Note that we only have special rules for turning block enum 10249 // returns into block int returns, not vice-versa. 10250 if (const auto *ETy = LHS->getAs<EnumType>()) { 10251 return mergeEnumWithInteger(*this, ETy, RHS, false); 10252 } 10253 if (const EnumType* ETy = RHS->getAs<EnumType>()) { 10254 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType); 10255 } 10256 // allow block pointer type to match an 'id' type. 10257 if (OfBlockPointer && !BlockReturnType) { 10258 if (LHS->isObjCIdType() && RHS->isBlockPointerType()) 10259 return LHS; 10260 if (RHS->isObjCIdType() && LHS->isBlockPointerType()) 10261 return RHS; 10262 } 10263 10264 return {}; 10265 } 10266 10267 // The canonical type classes match. 10268 switch (LHSClass) { 10269 #define TYPE(Class, Base) 10270 #define ABSTRACT_TYPE(Class, Base) 10271 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 10272 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 10273 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 10274 #include "clang/AST/TypeNodes.inc" 10275 llvm_unreachable("Non-canonical and dependent types shouldn't get here"); 10276 10277 case Type::Auto: 10278 case Type::DeducedTemplateSpecialization: 10279 case Type::LValueReference: 10280 case Type::RValueReference: 10281 case Type::MemberPointer: 10282 llvm_unreachable("C++ should never be in mergeTypes"); 10283 10284 case Type::ObjCInterface: 10285 case Type::IncompleteArray: 10286 case Type::VariableArray: 10287 case Type::FunctionProto: 10288 case Type::ExtVector: 10289 llvm_unreachable("Types are eliminated above"); 10290 10291 case Type::Pointer: 10292 { 10293 // Merge two pointer types, while trying to preserve typedef info 10294 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType(); 10295 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType(); 10296 if (Unqualified) { 10297 LHSPointee = LHSPointee.getUnqualifiedType(); 10298 RHSPointee = RHSPointee.getUnqualifiedType(); 10299 } 10300 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false, 10301 Unqualified); 10302 if (ResultType.isNull()) 10303 return {}; 10304 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 10305 return LHS; 10306 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 10307 return RHS; 10308 return getPointerType(ResultType); 10309 } 10310 case Type::BlockPointer: 10311 { 10312 // Merge two block pointer types, while trying to preserve typedef info 10313 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType(); 10314 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType(); 10315 if (Unqualified) { 10316 LHSPointee = LHSPointee.getUnqualifiedType(); 10317 RHSPointee = RHSPointee.getUnqualifiedType(); 10318 } 10319 if (getLangOpts().OpenCL) { 10320 Qualifiers LHSPteeQual = LHSPointee.getQualifiers(); 10321 Qualifiers RHSPteeQual = RHSPointee.getQualifiers(); 10322 // Blocks can't be an expression in a ternary operator (OpenCL v2.0 10323 // 6.12.5) thus the following check is asymmetric. 10324 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual)) 10325 return {}; 10326 LHSPteeQual.removeAddressSpace(); 10327 RHSPteeQual.removeAddressSpace(); 10328 LHSPointee = 10329 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue()); 10330 RHSPointee = 10331 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue()); 10332 } 10333 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer, 10334 Unqualified); 10335 if (ResultType.isNull()) 10336 return {}; 10337 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 10338 return LHS; 10339 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 10340 return RHS; 10341 return getBlockPointerType(ResultType); 10342 } 10343 case Type::Atomic: 10344 { 10345 // Merge two pointer types, while trying to preserve typedef info 10346 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType(); 10347 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType(); 10348 if (Unqualified) { 10349 LHSValue = LHSValue.getUnqualifiedType(); 10350 RHSValue = RHSValue.getUnqualifiedType(); 10351 } 10352 QualType ResultType = mergeTypes(LHSValue, RHSValue, false, 10353 Unqualified); 10354 if (ResultType.isNull()) 10355 return {}; 10356 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType)) 10357 return LHS; 10358 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType)) 10359 return RHS; 10360 return getAtomicType(ResultType); 10361 } 10362 case Type::ConstantArray: 10363 { 10364 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS); 10365 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS); 10366 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize()) 10367 return {}; 10368 10369 QualType LHSElem = getAsArrayType(LHS)->getElementType(); 10370 QualType RHSElem = getAsArrayType(RHS)->getElementType(); 10371 if (Unqualified) { 10372 LHSElem = LHSElem.getUnqualifiedType(); 10373 RHSElem = RHSElem.getUnqualifiedType(); 10374 } 10375 10376 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified); 10377 if (ResultType.isNull()) 10378 return {}; 10379 10380 const VariableArrayType* LVAT = getAsVariableArrayType(LHS); 10381 const VariableArrayType* RVAT = getAsVariableArrayType(RHS); 10382 10383 // If either side is a variable array, and both are complete, check whether 10384 // the current dimension is definite. 10385 if (LVAT || RVAT) { 10386 auto SizeFetch = [this](const VariableArrayType* VAT, 10387 const ConstantArrayType* CAT) 10388 -> std::pair<bool,llvm::APInt> { 10389 if (VAT) { 10390 Optional<llvm::APSInt> TheInt; 10391 Expr *E = VAT->getSizeExpr(); 10392 if (E && (TheInt = E->getIntegerConstantExpr(*this))) 10393 return std::make_pair(true, *TheInt); 10394 return std::make_pair(false, llvm::APSInt()); 10395 } 10396 if (CAT) 10397 return std::make_pair(true, CAT->getSize()); 10398 return std::make_pair(false, llvm::APInt()); 10399 }; 10400 10401 bool HaveLSize, HaveRSize; 10402 llvm::APInt LSize, RSize; 10403 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT); 10404 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT); 10405 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize)) 10406 return {}; // Definite, but unequal, array dimension 10407 } 10408 10409 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 10410 return LHS; 10411 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 10412 return RHS; 10413 if (LCAT) 10414 return getConstantArrayType(ResultType, LCAT->getSize(), 10415 LCAT->getSizeExpr(), 10416 ArrayType::ArraySizeModifier(), 0); 10417 if (RCAT) 10418 return getConstantArrayType(ResultType, RCAT->getSize(), 10419 RCAT->getSizeExpr(), 10420 ArrayType::ArraySizeModifier(), 0); 10421 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 10422 return LHS; 10423 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 10424 return RHS; 10425 if (LVAT) { 10426 // FIXME: This isn't correct! But tricky to implement because 10427 // the array's size has to be the size of LHS, but the type 10428 // has to be different. 10429 return LHS; 10430 } 10431 if (RVAT) { 10432 // FIXME: This isn't correct! But tricky to implement because 10433 // the array's size has to be the size of RHS, but the type 10434 // has to be different. 10435 return RHS; 10436 } 10437 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS; 10438 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS; 10439 return getIncompleteArrayType(ResultType, 10440 ArrayType::ArraySizeModifier(), 0); 10441 } 10442 case Type::FunctionNoProto: 10443 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified); 10444 case Type::Record: 10445 case Type::Enum: 10446 return {}; 10447 case Type::Builtin: 10448 // Only exactly equal builtin types are compatible, which is tested above. 10449 return {}; 10450 case Type::Complex: 10451 // Distinct complex types are incompatible. 10452 return {}; 10453 case Type::Vector: 10454 // FIXME: The merged type should be an ExtVector! 10455 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(), 10456 RHSCan->castAs<VectorType>())) 10457 return LHS; 10458 return {}; 10459 case Type::ConstantMatrix: 10460 if (areCompatMatrixTypes(LHSCan->castAs<ConstantMatrixType>(), 10461 RHSCan->castAs<ConstantMatrixType>())) 10462 return LHS; 10463 return {}; 10464 case Type::ObjCObject: { 10465 // Check if the types are assignment compatible. 10466 // FIXME: This should be type compatibility, e.g. whether 10467 // "LHS x; RHS x;" at global scope is legal. 10468 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectType>(), 10469 RHS->castAs<ObjCObjectType>())) 10470 return LHS; 10471 return {}; 10472 } 10473 case Type::ObjCObjectPointer: 10474 if (OfBlockPointer) { 10475 if (canAssignObjCInterfacesInBlockPointer( 10476 LHS->castAs<ObjCObjectPointerType>(), 10477 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType)) 10478 return LHS; 10479 return {}; 10480 } 10481 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectPointerType>(), 10482 RHS->castAs<ObjCObjectPointerType>())) 10483 return LHS; 10484 return {}; 10485 case Type::Pipe: 10486 assert(LHS != RHS && 10487 "Equivalent pipe types should have already been handled!"); 10488 return {}; 10489 case Type::BitInt: { 10490 // Merge two bit-precise int types, while trying to preserve typedef info. 10491 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned(); 10492 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned(); 10493 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits(); 10494 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits(); 10495 10496 // Like unsigned/int, shouldn't have a type if they don't match. 10497 if (LHSUnsigned != RHSUnsigned) 10498 return {}; 10499 10500 if (LHSBits != RHSBits) 10501 return {}; 10502 return LHS; 10503 } 10504 } 10505 10506 llvm_unreachable("Invalid Type::Class!"); 10507 } 10508 10509 bool ASTContext::mergeExtParameterInfo( 10510 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType, 10511 bool &CanUseFirst, bool &CanUseSecond, 10512 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) { 10513 assert(NewParamInfos.empty() && "param info list not empty"); 10514 CanUseFirst = CanUseSecond = true; 10515 bool FirstHasInfo = FirstFnType->hasExtParameterInfos(); 10516 bool SecondHasInfo = SecondFnType->hasExtParameterInfos(); 10517 10518 // Fast path: if the first type doesn't have ext parameter infos, 10519 // we match if and only if the second type also doesn't have them. 10520 if (!FirstHasInfo && !SecondHasInfo) 10521 return true; 10522 10523 bool NeedParamInfo = false; 10524 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size() 10525 : SecondFnType->getExtParameterInfos().size(); 10526 10527 for (size_t I = 0; I < E; ++I) { 10528 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam; 10529 if (FirstHasInfo) 10530 FirstParam = FirstFnType->getExtParameterInfo(I); 10531 if (SecondHasInfo) 10532 SecondParam = SecondFnType->getExtParameterInfo(I); 10533 10534 // Cannot merge unless everything except the noescape flag matches. 10535 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false)) 10536 return false; 10537 10538 bool FirstNoEscape = FirstParam.isNoEscape(); 10539 bool SecondNoEscape = SecondParam.isNoEscape(); 10540 bool IsNoEscape = FirstNoEscape && SecondNoEscape; 10541 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape)); 10542 if (NewParamInfos.back().getOpaqueValue()) 10543 NeedParamInfo = true; 10544 if (FirstNoEscape != IsNoEscape) 10545 CanUseFirst = false; 10546 if (SecondNoEscape != IsNoEscape) 10547 CanUseSecond = false; 10548 } 10549 10550 if (!NeedParamInfo) 10551 NewParamInfos.clear(); 10552 10553 return true; 10554 } 10555 10556 void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) { 10557 ObjCLayouts[CD] = nullptr; 10558 } 10559 10560 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 10561 /// 'RHS' attributes and returns the merged version; including for function 10562 /// return types. 10563 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) { 10564 QualType LHSCan = getCanonicalType(LHS), 10565 RHSCan = getCanonicalType(RHS); 10566 // If two types are identical, they are compatible. 10567 if (LHSCan == RHSCan) 10568 return LHS; 10569 if (RHSCan->isFunctionType()) { 10570 if (!LHSCan->isFunctionType()) 10571 return {}; 10572 QualType OldReturnType = 10573 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType(); 10574 QualType NewReturnType = 10575 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType(); 10576 QualType ResReturnType = 10577 mergeObjCGCQualifiers(NewReturnType, OldReturnType); 10578 if (ResReturnType.isNull()) 10579 return {}; 10580 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) { 10581 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo(); 10582 // In either case, use OldReturnType to build the new function type. 10583 const auto *F = LHS->castAs<FunctionType>(); 10584 if (const auto *FPT = cast<FunctionProtoType>(F)) { 10585 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10586 EPI.ExtInfo = getFunctionExtInfo(LHS); 10587 QualType ResultType = 10588 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI); 10589 return ResultType; 10590 } 10591 } 10592 return {}; 10593 } 10594 10595 // If the qualifiers are different, the types can still be merged. 10596 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 10597 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 10598 if (LQuals != RQuals) { 10599 // If any of these qualifiers are different, we have a type mismatch. 10600 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 10601 LQuals.getAddressSpace() != RQuals.getAddressSpace()) 10602 return {}; 10603 10604 // Exactly one GC qualifier difference is allowed: __strong is 10605 // okay if the other type has no GC qualifier but is an Objective 10606 // C object pointer (i.e. implicitly strong by default). We fix 10607 // this by pretending that the unqualified type was actually 10608 // qualified __strong. 10609 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 10610 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 10611 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 10612 10613 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 10614 return {}; 10615 10616 if (GC_L == Qualifiers::Strong) 10617 return LHS; 10618 if (GC_R == Qualifiers::Strong) 10619 return RHS; 10620 return {}; 10621 } 10622 10623 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) { 10624 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType(); 10625 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType(); 10626 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT); 10627 if (ResQT == LHSBaseQT) 10628 return LHS; 10629 if (ResQT == RHSBaseQT) 10630 return RHS; 10631 } 10632 return {}; 10633 } 10634 10635 //===----------------------------------------------------------------------===// 10636 // Integer Predicates 10637 //===----------------------------------------------------------------------===// 10638 10639 unsigned ASTContext::getIntWidth(QualType T) const { 10640 if (const auto *ET = T->getAs<EnumType>()) 10641 T = ET->getDecl()->getIntegerType(); 10642 if (T->isBooleanType()) 10643 return 1; 10644 if (const auto *EIT = T->getAs<BitIntType>()) 10645 return EIT->getNumBits(); 10646 // For builtin types, just use the standard type sizing method 10647 return (unsigned)getTypeSize(T); 10648 } 10649 10650 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const { 10651 assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) && 10652 "Unexpected type"); 10653 10654 // Turn <4 x signed int> -> <4 x unsigned int> 10655 if (const auto *VTy = T->getAs<VectorType>()) 10656 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()), 10657 VTy->getNumElements(), VTy->getVectorKind()); 10658 10659 // For _BitInt, return an unsigned _BitInt with same width. 10660 if (const auto *EITy = T->getAs<BitIntType>()) 10661 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits()); 10662 10663 // For enums, get the underlying integer type of the enum, and let the general 10664 // integer type signchanging code handle it. 10665 if (const auto *ETy = T->getAs<EnumType>()) 10666 T = ETy->getDecl()->getIntegerType(); 10667 10668 switch (T->castAs<BuiltinType>()->getKind()) { 10669 case BuiltinType::Char_S: 10670 case BuiltinType::SChar: 10671 return UnsignedCharTy; 10672 case BuiltinType::Short: 10673 return UnsignedShortTy; 10674 case BuiltinType::Int: 10675 return UnsignedIntTy; 10676 case BuiltinType::Long: 10677 return UnsignedLongTy; 10678 case BuiltinType::LongLong: 10679 return UnsignedLongLongTy; 10680 case BuiltinType::Int128: 10681 return UnsignedInt128Ty; 10682 // wchar_t is special. It is either signed or not, but when it's signed, 10683 // there's no matching "unsigned wchar_t". Therefore we return the unsigned 10684 // version of it's underlying type instead. 10685 case BuiltinType::WChar_S: 10686 return getUnsignedWCharType(); 10687 10688 case BuiltinType::ShortAccum: 10689 return UnsignedShortAccumTy; 10690 case BuiltinType::Accum: 10691 return UnsignedAccumTy; 10692 case BuiltinType::LongAccum: 10693 return UnsignedLongAccumTy; 10694 case BuiltinType::SatShortAccum: 10695 return SatUnsignedShortAccumTy; 10696 case BuiltinType::SatAccum: 10697 return SatUnsignedAccumTy; 10698 case BuiltinType::SatLongAccum: 10699 return SatUnsignedLongAccumTy; 10700 case BuiltinType::ShortFract: 10701 return UnsignedShortFractTy; 10702 case BuiltinType::Fract: 10703 return UnsignedFractTy; 10704 case BuiltinType::LongFract: 10705 return UnsignedLongFractTy; 10706 case BuiltinType::SatShortFract: 10707 return SatUnsignedShortFractTy; 10708 case BuiltinType::SatFract: 10709 return SatUnsignedFractTy; 10710 case BuiltinType::SatLongFract: 10711 return SatUnsignedLongFractTy; 10712 default: 10713 llvm_unreachable("Unexpected signed integer or fixed point type"); 10714 } 10715 } 10716 10717 QualType ASTContext::getCorrespondingSignedType(QualType T) const { 10718 assert((T->hasUnsignedIntegerRepresentation() || 10719 T->isUnsignedFixedPointType()) && 10720 "Unexpected type"); 10721 10722 // Turn <4 x unsigned int> -> <4 x signed int> 10723 if (const auto *VTy = T->getAs<VectorType>()) 10724 return getVectorType(getCorrespondingSignedType(VTy->getElementType()), 10725 VTy->getNumElements(), VTy->getVectorKind()); 10726 10727 // For _BitInt, return a signed _BitInt with same width. 10728 if (const auto *EITy = T->getAs<BitIntType>()) 10729 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits()); 10730 10731 // For enums, get the underlying integer type of the enum, and let the general 10732 // integer type signchanging code handle it. 10733 if (const auto *ETy = T->getAs<EnumType>()) 10734 T = ETy->getDecl()->getIntegerType(); 10735 10736 switch (T->castAs<BuiltinType>()->getKind()) { 10737 case BuiltinType::Char_U: 10738 case BuiltinType::UChar: 10739 return SignedCharTy; 10740 case BuiltinType::UShort: 10741 return ShortTy; 10742 case BuiltinType::UInt: 10743 return IntTy; 10744 case BuiltinType::ULong: 10745 return LongTy; 10746 case BuiltinType::ULongLong: 10747 return LongLongTy; 10748 case BuiltinType::UInt128: 10749 return Int128Ty; 10750 // wchar_t is special. It is either unsigned or not, but when it's unsigned, 10751 // there's no matching "signed wchar_t". Therefore we return the signed 10752 // version of it's underlying type instead. 10753 case BuiltinType::WChar_U: 10754 return getSignedWCharType(); 10755 10756 case BuiltinType::UShortAccum: 10757 return ShortAccumTy; 10758 case BuiltinType::UAccum: 10759 return AccumTy; 10760 case BuiltinType::ULongAccum: 10761 return LongAccumTy; 10762 case BuiltinType::SatUShortAccum: 10763 return SatShortAccumTy; 10764 case BuiltinType::SatUAccum: 10765 return SatAccumTy; 10766 case BuiltinType::SatULongAccum: 10767 return SatLongAccumTy; 10768 case BuiltinType::UShortFract: 10769 return ShortFractTy; 10770 case BuiltinType::UFract: 10771 return FractTy; 10772 case BuiltinType::ULongFract: 10773 return LongFractTy; 10774 case BuiltinType::SatUShortFract: 10775 return SatShortFractTy; 10776 case BuiltinType::SatUFract: 10777 return SatFractTy; 10778 case BuiltinType::SatULongFract: 10779 return SatLongFractTy; 10780 default: 10781 llvm_unreachable("Unexpected unsigned integer or fixed point type"); 10782 } 10783 } 10784 10785 ASTMutationListener::~ASTMutationListener() = default; 10786 10787 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD, 10788 QualType ReturnType) {} 10789 10790 //===----------------------------------------------------------------------===// 10791 // Builtin Type Computation 10792 //===----------------------------------------------------------------------===// 10793 10794 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the 10795 /// pointer over the consumed characters. This returns the resultant type. If 10796 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic 10797 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of 10798 /// a vector of "i*". 10799 /// 10800 /// RequiresICE is filled in on return to indicate whether the value is required 10801 /// to be an Integer Constant Expression. 10802 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, 10803 ASTContext::GetBuiltinTypeError &Error, 10804 bool &RequiresICE, 10805 bool AllowTypeModifiers) { 10806 // Modifiers. 10807 int HowLong = 0; 10808 bool Signed = false, Unsigned = false; 10809 RequiresICE = false; 10810 10811 // Read the prefixed modifiers first. 10812 bool Done = false; 10813 #ifndef NDEBUG 10814 bool IsSpecial = false; 10815 #endif 10816 while (!Done) { 10817 switch (*Str++) { 10818 default: Done = true; --Str; break; 10819 case 'I': 10820 RequiresICE = true; 10821 break; 10822 case 'S': 10823 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!"); 10824 assert(!Signed && "Can't use 'S' modifier multiple times!"); 10825 Signed = true; 10826 break; 10827 case 'U': 10828 assert(!Signed && "Can't use both 'S' and 'U' modifiers!"); 10829 assert(!Unsigned && "Can't use 'U' modifier multiple times!"); 10830 Unsigned = true; 10831 break; 10832 case 'L': 10833 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers"); 10834 assert(HowLong <= 2 && "Can't have LLLL modifier"); 10835 ++HowLong; 10836 break; 10837 case 'N': 10838 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise. 10839 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10840 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!"); 10841 #ifndef NDEBUG 10842 IsSpecial = true; 10843 #endif 10844 if (Context.getTargetInfo().getLongWidth() == 32) 10845 ++HowLong; 10846 break; 10847 case 'W': 10848 // This modifier represents int64 type. 10849 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10850 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!"); 10851 #ifndef NDEBUG 10852 IsSpecial = true; 10853 #endif 10854 switch (Context.getTargetInfo().getInt64Type()) { 10855 default: 10856 llvm_unreachable("Unexpected integer type"); 10857 case TargetInfo::SignedLong: 10858 HowLong = 1; 10859 break; 10860 case TargetInfo::SignedLongLong: 10861 HowLong = 2; 10862 break; 10863 } 10864 break; 10865 case 'Z': 10866 // This modifier represents int32 type. 10867 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10868 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!"); 10869 #ifndef NDEBUG 10870 IsSpecial = true; 10871 #endif 10872 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) { 10873 default: 10874 llvm_unreachable("Unexpected integer type"); 10875 case TargetInfo::SignedInt: 10876 HowLong = 0; 10877 break; 10878 case TargetInfo::SignedLong: 10879 HowLong = 1; 10880 break; 10881 case TargetInfo::SignedLongLong: 10882 HowLong = 2; 10883 break; 10884 } 10885 break; 10886 case 'O': 10887 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10888 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!"); 10889 #ifndef NDEBUG 10890 IsSpecial = true; 10891 #endif 10892 if (Context.getLangOpts().OpenCL) 10893 HowLong = 1; 10894 else 10895 HowLong = 2; 10896 break; 10897 } 10898 } 10899 10900 QualType Type; 10901 10902 // Read the base type. 10903 switch (*Str++) { 10904 default: llvm_unreachable("Unknown builtin type letter!"); 10905 case 'x': 10906 assert(HowLong == 0 && !Signed && !Unsigned && 10907 "Bad modifiers used with 'x'!"); 10908 Type = Context.Float16Ty; 10909 break; 10910 case 'y': 10911 assert(HowLong == 0 && !Signed && !Unsigned && 10912 "Bad modifiers used with 'y'!"); 10913 Type = Context.BFloat16Ty; 10914 break; 10915 case 'v': 10916 assert(HowLong == 0 && !Signed && !Unsigned && 10917 "Bad modifiers used with 'v'!"); 10918 Type = Context.VoidTy; 10919 break; 10920 case 'h': 10921 assert(HowLong == 0 && !Signed && !Unsigned && 10922 "Bad modifiers used with 'h'!"); 10923 Type = Context.HalfTy; 10924 break; 10925 case 'f': 10926 assert(HowLong == 0 && !Signed && !Unsigned && 10927 "Bad modifiers used with 'f'!"); 10928 Type = Context.FloatTy; 10929 break; 10930 case 'd': 10931 assert(HowLong < 3 && !Signed && !Unsigned && 10932 "Bad modifiers used with 'd'!"); 10933 if (HowLong == 1) 10934 Type = Context.LongDoubleTy; 10935 else if (HowLong == 2) 10936 Type = Context.Float128Ty; 10937 else 10938 Type = Context.DoubleTy; 10939 break; 10940 case 's': 10941 assert(HowLong == 0 && "Bad modifiers used with 's'!"); 10942 if (Unsigned) 10943 Type = Context.UnsignedShortTy; 10944 else 10945 Type = Context.ShortTy; 10946 break; 10947 case 'i': 10948 if (HowLong == 3) 10949 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty; 10950 else if (HowLong == 2) 10951 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy; 10952 else if (HowLong == 1) 10953 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy; 10954 else 10955 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy; 10956 break; 10957 case 'c': 10958 assert(HowLong == 0 && "Bad modifiers used with 'c'!"); 10959 if (Signed) 10960 Type = Context.SignedCharTy; 10961 else if (Unsigned) 10962 Type = Context.UnsignedCharTy; 10963 else 10964 Type = Context.CharTy; 10965 break; 10966 case 'b': // boolean 10967 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!"); 10968 Type = Context.BoolTy; 10969 break; 10970 case 'z': // size_t. 10971 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!"); 10972 Type = Context.getSizeType(); 10973 break; 10974 case 'w': // wchar_t. 10975 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!"); 10976 Type = Context.getWideCharType(); 10977 break; 10978 case 'F': 10979 Type = Context.getCFConstantStringType(); 10980 break; 10981 case 'G': 10982 Type = Context.getObjCIdType(); 10983 break; 10984 case 'H': 10985 Type = Context.getObjCSelType(); 10986 break; 10987 case 'M': 10988 Type = Context.getObjCSuperType(); 10989 break; 10990 case 'a': 10991 Type = Context.getBuiltinVaListType(); 10992 assert(!Type.isNull() && "builtin va list type not initialized!"); 10993 break; 10994 case 'A': 10995 // This is a "reference" to a va_list; however, what exactly 10996 // this means depends on how va_list is defined. There are two 10997 // different kinds of va_list: ones passed by value, and ones 10998 // passed by reference. An example of a by-value va_list is 10999 // x86, where va_list is a char*. An example of by-ref va_list 11000 // is x86-64, where va_list is a __va_list_tag[1]. For x86, 11001 // we want this argument to be a char*&; for x86-64, we want 11002 // it to be a __va_list_tag*. 11003 Type = Context.getBuiltinVaListType(); 11004 assert(!Type.isNull() && "builtin va list type not initialized!"); 11005 if (Type->isArrayType()) 11006 Type = Context.getArrayDecayedType(Type); 11007 else 11008 Type = Context.getLValueReferenceType(Type); 11009 break; 11010 case 'q': { 11011 char *End; 11012 unsigned NumElements = strtoul(Str, &End, 10); 11013 assert(End != Str && "Missing vector size"); 11014 Str = End; 11015 11016 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 11017 RequiresICE, false); 11018 assert(!RequiresICE && "Can't require vector ICE"); 11019 11020 Type = Context.getScalableVectorType(ElementType, NumElements); 11021 break; 11022 } 11023 case 'V': { 11024 char *End; 11025 unsigned NumElements = strtoul(Str, &End, 10); 11026 assert(End != Str && "Missing vector size"); 11027 Str = End; 11028 11029 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 11030 RequiresICE, false); 11031 assert(!RequiresICE && "Can't require vector ICE"); 11032 11033 // TODO: No way to make AltiVec vectors in builtins yet. 11034 Type = Context.getVectorType(ElementType, NumElements, 11035 VectorType::GenericVector); 11036 break; 11037 } 11038 case 'E': { 11039 char *End; 11040 11041 unsigned NumElements = strtoul(Str, &End, 10); 11042 assert(End != Str && "Missing vector size"); 11043 11044 Str = End; 11045 11046 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 11047 false); 11048 Type = Context.getExtVectorType(ElementType, NumElements); 11049 break; 11050 } 11051 case 'X': { 11052 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 11053 false); 11054 assert(!RequiresICE && "Can't require complex ICE"); 11055 Type = Context.getComplexType(ElementType); 11056 break; 11057 } 11058 case 'Y': 11059 Type = Context.getPointerDiffType(); 11060 break; 11061 case 'P': 11062 Type = Context.getFILEType(); 11063 if (Type.isNull()) { 11064 Error = ASTContext::GE_Missing_stdio; 11065 return {}; 11066 } 11067 break; 11068 case 'J': 11069 if (Signed) 11070 Type = Context.getsigjmp_bufType(); 11071 else 11072 Type = Context.getjmp_bufType(); 11073 11074 if (Type.isNull()) { 11075 Error = ASTContext::GE_Missing_setjmp; 11076 return {}; 11077 } 11078 break; 11079 case 'K': 11080 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!"); 11081 Type = Context.getucontext_tType(); 11082 11083 if (Type.isNull()) { 11084 Error = ASTContext::GE_Missing_ucontext; 11085 return {}; 11086 } 11087 break; 11088 case 'p': 11089 Type = Context.getProcessIDType(); 11090 break; 11091 } 11092 11093 // If there are modifiers and if we're allowed to parse them, go for it. 11094 Done = !AllowTypeModifiers; 11095 while (!Done) { 11096 switch (char c = *Str++) { 11097 default: Done = true; --Str; break; 11098 case '*': 11099 case '&': { 11100 // Both pointers and references can have their pointee types 11101 // qualified with an address space. 11102 char *End; 11103 unsigned AddrSpace = strtoul(Str, &End, 10); 11104 if (End != Str) { 11105 // Note AddrSpace == 0 is not the same as an unspecified address space. 11106 Type = Context.getAddrSpaceQualType( 11107 Type, 11108 Context.getLangASForBuiltinAddressSpace(AddrSpace)); 11109 Str = End; 11110 } 11111 if (c == '*') 11112 Type = Context.getPointerType(Type); 11113 else 11114 Type = Context.getLValueReferenceType(Type); 11115 break; 11116 } 11117 // FIXME: There's no way to have a built-in with an rvalue ref arg. 11118 case 'C': 11119 Type = Type.withConst(); 11120 break; 11121 case 'D': 11122 Type = Context.getVolatileType(Type); 11123 break; 11124 case 'R': 11125 Type = Type.withRestrict(); 11126 break; 11127 } 11128 } 11129 11130 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) && 11131 "Integer constant 'I' type must be an integer"); 11132 11133 return Type; 11134 } 11135 11136 // On some targets such as PowerPC, some of the builtins are defined with custom 11137 // type descriptors for target-dependent types. These descriptors are decoded in 11138 // other functions, but it may be useful to be able to fall back to default 11139 // descriptor decoding to define builtins mixing target-dependent and target- 11140 // independent types. This function allows decoding one type descriptor with 11141 // default decoding. 11142 QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context, 11143 GetBuiltinTypeError &Error, bool &RequireICE, 11144 bool AllowTypeModifiers) const { 11145 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers); 11146 } 11147 11148 /// GetBuiltinType - Return the type for the specified builtin. 11149 QualType ASTContext::GetBuiltinType(unsigned Id, 11150 GetBuiltinTypeError &Error, 11151 unsigned *IntegerConstantArgs) const { 11152 const char *TypeStr = BuiltinInfo.getTypeString(Id); 11153 if (TypeStr[0] == '\0') { 11154 Error = GE_Missing_type; 11155 return {}; 11156 } 11157 11158 SmallVector<QualType, 8> ArgTypes; 11159 11160 bool RequiresICE = false; 11161 Error = GE_None; 11162 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error, 11163 RequiresICE, true); 11164 if (Error != GE_None) 11165 return {}; 11166 11167 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE"); 11168 11169 while (TypeStr[0] && TypeStr[0] != '.') { 11170 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true); 11171 if (Error != GE_None) 11172 return {}; 11173 11174 // If this argument is required to be an IntegerConstantExpression and the 11175 // caller cares, fill in the bitmask we return. 11176 if (RequiresICE && IntegerConstantArgs) 11177 *IntegerConstantArgs |= 1 << ArgTypes.size(); 11178 11179 // Do array -> pointer decay. The builtin should use the decayed type. 11180 if (Ty->isArrayType()) 11181 Ty = getArrayDecayedType(Ty); 11182 11183 ArgTypes.push_back(Ty); 11184 } 11185 11186 if (Id == Builtin::BI__GetExceptionInfo) 11187 return {}; 11188 11189 assert((TypeStr[0] != '.' || TypeStr[1] == 0) && 11190 "'.' should only occur at end of builtin type list!"); 11191 11192 bool Variadic = (TypeStr[0] == '.'); 11193 11194 FunctionType::ExtInfo EI(getDefaultCallingConvention( 11195 Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true)); 11196 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true); 11197 11198 11199 // We really shouldn't be making a no-proto type here. 11200 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus) 11201 return getFunctionNoProtoType(ResType, EI); 11202 11203 FunctionProtoType::ExtProtoInfo EPI; 11204 EPI.ExtInfo = EI; 11205 EPI.Variadic = Variadic; 11206 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id)) 11207 EPI.ExceptionSpec.Type = 11208 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone; 11209 11210 return getFunctionType(ResType, ArgTypes, EPI); 11211 } 11212 11213 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, 11214 const FunctionDecl *FD) { 11215 if (!FD->isExternallyVisible()) 11216 return GVA_Internal; 11217 11218 // Non-user-provided functions get emitted as weak definitions with every 11219 // use, no matter whether they've been explicitly instantiated etc. 11220 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 11221 if (!MD->isUserProvided()) 11222 return GVA_DiscardableODR; 11223 11224 GVALinkage External; 11225 switch (FD->getTemplateSpecializationKind()) { 11226 case TSK_Undeclared: 11227 case TSK_ExplicitSpecialization: 11228 External = GVA_StrongExternal; 11229 break; 11230 11231 case TSK_ExplicitInstantiationDefinition: 11232 return GVA_StrongODR; 11233 11234 // C++11 [temp.explicit]p10: 11235 // [ Note: The intent is that an inline function that is the subject of 11236 // an explicit instantiation declaration will still be implicitly 11237 // instantiated when used so that the body can be considered for 11238 // inlining, but that no out-of-line copy of the inline function would be 11239 // generated in the translation unit. -- end note ] 11240 case TSK_ExplicitInstantiationDeclaration: 11241 return GVA_AvailableExternally; 11242 11243 case TSK_ImplicitInstantiation: 11244 External = GVA_DiscardableODR; 11245 break; 11246 } 11247 11248 if (!FD->isInlined()) 11249 return External; 11250 11251 if ((!Context.getLangOpts().CPlusPlus && 11252 !Context.getTargetInfo().getCXXABI().isMicrosoft() && 11253 !FD->hasAttr<DLLExportAttr>()) || 11254 FD->hasAttr<GNUInlineAttr>()) { 11255 // FIXME: This doesn't match gcc's behavior for dllexport inline functions. 11256 11257 // GNU or C99 inline semantics. Determine whether this symbol should be 11258 // externally visible. 11259 if (FD->isInlineDefinitionExternallyVisible()) 11260 return External; 11261 11262 // C99 inline semantics, where the symbol is not externally visible. 11263 return GVA_AvailableExternally; 11264 } 11265 11266 // Functions specified with extern and inline in -fms-compatibility mode 11267 // forcibly get emitted. While the body of the function cannot be later 11268 // replaced, the function definition cannot be discarded. 11269 if (FD->isMSExternInline()) 11270 return GVA_StrongODR; 11271 11272 return GVA_DiscardableODR; 11273 } 11274 11275 static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context, 11276 const Decl *D, GVALinkage L) { 11277 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx 11278 // dllexport/dllimport on inline functions. 11279 if (D->hasAttr<DLLImportAttr>()) { 11280 if (L == GVA_DiscardableODR || L == GVA_StrongODR) 11281 return GVA_AvailableExternally; 11282 } else if (D->hasAttr<DLLExportAttr>()) { 11283 if (L == GVA_DiscardableODR) 11284 return GVA_StrongODR; 11285 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) { 11286 // Device-side functions with __global__ attribute must always be 11287 // visible externally so they can be launched from host. 11288 if (D->hasAttr<CUDAGlobalAttr>() && 11289 (L == GVA_DiscardableODR || L == GVA_Internal)) 11290 return GVA_StrongODR; 11291 // Single source offloading languages like CUDA/HIP need to be able to 11292 // access static device variables from host code of the same compilation 11293 // unit. This is done by externalizing the static variable with a shared 11294 // name between the host and device compilation which is the same for the 11295 // same compilation unit whereas different among different compilation 11296 // units. 11297 if (Context.shouldExternalizeStaticVar(D)) 11298 return GVA_StrongExternal; 11299 } 11300 return L; 11301 } 11302 11303 /// Adjust the GVALinkage for a declaration based on what an external AST source 11304 /// knows about whether there can be other definitions of this declaration. 11305 static GVALinkage 11306 adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D, 11307 GVALinkage L) { 11308 ExternalASTSource *Source = Ctx.getExternalSource(); 11309 if (!Source) 11310 return L; 11311 11312 switch (Source->hasExternalDefinitions(D)) { 11313 case ExternalASTSource::EK_Never: 11314 // Other translation units rely on us to provide the definition. 11315 if (L == GVA_DiscardableODR) 11316 return GVA_StrongODR; 11317 break; 11318 11319 case ExternalASTSource::EK_Always: 11320 return GVA_AvailableExternally; 11321 11322 case ExternalASTSource::EK_ReplyHazy: 11323 break; 11324 } 11325 return L; 11326 } 11327 11328 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const { 11329 return adjustGVALinkageForExternalDefinitionKind(*this, FD, 11330 adjustGVALinkageForAttributes(*this, FD, 11331 basicGVALinkageForFunction(*this, FD))); 11332 } 11333 11334 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context, 11335 const VarDecl *VD) { 11336 if (!VD->isExternallyVisible()) 11337 return GVA_Internal; 11338 11339 if (VD->isStaticLocal()) { 11340 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod(); 11341 while (LexicalContext && !isa<FunctionDecl>(LexicalContext)) 11342 LexicalContext = LexicalContext->getLexicalParent(); 11343 11344 // ObjC Blocks can create local variables that don't have a FunctionDecl 11345 // LexicalContext. 11346 if (!LexicalContext) 11347 return GVA_DiscardableODR; 11348 11349 // Otherwise, let the static local variable inherit its linkage from the 11350 // nearest enclosing function. 11351 auto StaticLocalLinkage = 11352 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext)); 11353 11354 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must 11355 // be emitted in any object with references to the symbol for the object it 11356 // contains, whether inline or out-of-line." 11357 // Similar behavior is observed with MSVC. An alternative ABI could use 11358 // StrongODR/AvailableExternally to match the function, but none are 11359 // known/supported currently. 11360 if (StaticLocalLinkage == GVA_StrongODR || 11361 StaticLocalLinkage == GVA_AvailableExternally) 11362 return GVA_DiscardableODR; 11363 return StaticLocalLinkage; 11364 } 11365 11366 // MSVC treats in-class initialized static data members as definitions. 11367 // By giving them non-strong linkage, out-of-line definitions won't 11368 // cause link errors. 11369 if (Context.isMSStaticDataMemberInlineDefinition(VD)) 11370 return GVA_DiscardableODR; 11371 11372 // Most non-template variables have strong linkage; inline variables are 11373 // linkonce_odr or (occasionally, for compatibility) weak_odr. 11374 GVALinkage StrongLinkage; 11375 switch (Context.getInlineVariableDefinitionKind(VD)) { 11376 case ASTContext::InlineVariableDefinitionKind::None: 11377 StrongLinkage = GVA_StrongExternal; 11378 break; 11379 case ASTContext::InlineVariableDefinitionKind::Weak: 11380 case ASTContext::InlineVariableDefinitionKind::WeakUnknown: 11381 StrongLinkage = GVA_DiscardableODR; 11382 break; 11383 case ASTContext::InlineVariableDefinitionKind::Strong: 11384 StrongLinkage = GVA_StrongODR; 11385 break; 11386 } 11387 11388 switch (VD->getTemplateSpecializationKind()) { 11389 case TSK_Undeclared: 11390 return StrongLinkage; 11391 11392 case TSK_ExplicitSpecialization: 11393 return Context.getTargetInfo().getCXXABI().isMicrosoft() && 11394 VD->isStaticDataMember() 11395 ? GVA_StrongODR 11396 : StrongLinkage; 11397 11398 case TSK_ExplicitInstantiationDefinition: 11399 return GVA_StrongODR; 11400 11401 case TSK_ExplicitInstantiationDeclaration: 11402 return GVA_AvailableExternally; 11403 11404 case TSK_ImplicitInstantiation: 11405 return GVA_DiscardableODR; 11406 } 11407 11408 llvm_unreachable("Invalid Linkage!"); 11409 } 11410 11411 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) { 11412 return adjustGVALinkageForExternalDefinitionKind(*this, VD, 11413 adjustGVALinkageForAttributes(*this, VD, 11414 basicGVALinkageForVariable(*this, VD))); 11415 } 11416 11417 bool ASTContext::DeclMustBeEmitted(const Decl *D) { 11418 if (const auto *VD = dyn_cast<VarDecl>(D)) { 11419 if (!VD->isFileVarDecl()) 11420 return false; 11421 // Global named register variables (GNU extension) are never emitted. 11422 if (VD->getStorageClass() == SC_Register) 11423 return false; 11424 if (VD->getDescribedVarTemplate() || 11425 isa<VarTemplatePartialSpecializationDecl>(VD)) 11426 return false; 11427 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 11428 // We never need to emit an uninstantiated function template. 11429 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 11430 return false; 11431 } else if (isa<PragmaCommentDecl>(D)) 11432 return true; 11433 else if (isa<PragmaDetectMismatchDecl>(D)) 11434 return true; 11435 else if (isa<OMPRequiresDecl>(D)) 11436 return true; 11437 else if (isa<OMPThreadPrivateDecl>(D)) 11438 return !D->getDeclContext()->isDependentContext(); 11439 else if (isa<OMPAllocateDecl>(D)) 11440 return !D->getDeclContext()->isDependentContext(); 11441 else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D)) 11442 return !D->getDeclContext()->isDependentContext(); 11443 else if (isa<ImportDecl>(D)) 11444 return true; 11445 else 11446 return false; 11447 11448 // If this is a member of a class template, we do not need to emit it. 11449 if (D->getDeclContext()->isDependentContext()) 11450 return false; 11451 11452 // Weak references don't produce any output by themselves. 11453 if (D->hasAttr<WeakRefAttr>()) 11454 return false; 11455 11456 // Aliases and used decls are required. 11457 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>()) 11458 return true; 11459 11460 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 11461 // Forward declarations aren't required. 11462 if (!FD->doesThisDeclarationHaveABody()) 11463 return FD->doesDeclarationForceExternallyVisibleDefinition(); 11464 11465 // Constructors and destructors are required. 11466 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>()) 11467 return true; 11468 11469 // The key function for a class is required. This rule only comes 11470 // into play when inline functions can be key functions, though. 11471 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 11472 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 11473 const CXXRecordDecl *RD = MD->getParent(); 11474 if (MD->isOutOfLine() && RD->isDynamicClass()) { 11475 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD); 11476 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl()) 11477 return true; 11478 } 11479 } 11480 } 11481 11482 GVALinkage Linkage = GetGVALinkageForFunction(FD); 11483 11484 // static, static inline, always_inline, and extern inline functions can 11485 // always be deferred. Normal inline functions can be deferred in C99/C++. 11486 // Implicit template instantiations can also be deferred in C++. 11487 return !isDiscardableGVALinkage(Linkage); 11488 } 11489 11490 const auto *VD = cast<VarDecl>(D); 11491 assert(VD->isFileVarDecl() && "Expected file scoped var"); 11492 11493 // If the decl is marked as `declare target to`, it should be emitted for the 11494 // host and for the device. 11495 if (LangOpts.OpenMP && 11496 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 11497 return true; 11498 11499 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly && 11500 !isMSStaticDataMemberInlineDefinition(VD)) 11501 return false; 11502 11503 // Variables that can be needed in other TUs are required. 11504 auto Linkage = GetGVALinkageForVariable(VD); 11505 if (!isDiscardableGVALinkage(Linkage)) 11506 return true; 11507 11508 // We never need to emit a variable that is available in another TU. 11509 if (Linkage == GVA_AvailableExternally) 11510 return false; 11511 11512 // Variables that have destruction with side-effects are required. 11513 if (VD->needsDestruction(*this)) 11514 return true; 11515 11516 // Variables that have initialization with side-effects are required. 11517 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) && 11518 // We can get a value-dependent initializer during error recovery. 11519 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 11520 return true; 11521 11522 // Likewise, variables with tuple-like bindings are required if their 11523 // bindings have side-effects. 11524 if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) 11525 for (const auto *BD : DD->bindings()) 11526 if (const auto *BindingVD = BD->getHoldingVar()) 11527 if (DeclMustBeEmitted(BindingVD)) 11528 return true; 11529 11530 return false; 11531 } 11532 11533 void ASTContext::forEachMultiversionedFunctionVersion( 11534 const FunctionDecl *FD, 11535 llvm::function_ref<void(FunctionDecl *)> Pred) const { 11536 assert(FD->isMultiVersion() && "Only valid for multiversioned functions"); 11537 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls; 11538 FD = FD->getMostRecentDecl(); 11539 // FIXME: The order of traversal here matters and depends on the order of 11540 // lookup results, which happens to be (mostly) oldest-to-newest, but we 11541 // shouldn't rely on that. 11542 for (auto *CurDecl : 11543 FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) { 11544 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl(); 11545 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) && 11546 std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) { 11547 SeenDecls.insert(CurFD); 11548 Pred(CurFD); 11549 } 11550 } 11551 } 11552 11553 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic, 11554 bool IsCXXMethod, 11555 bool IsBuiltin) const { 11556 // Pass through to the C++ ABI object 11557 if (IsCXXMethod) 11558 return ABI->getDefaultMethodCallConv(IsVariadic); 11559 11560 // Builtins ignore user-specified default calling convention and remain the 11561 // Target's default calling convention. 11562 if (!IsBuiltin) { 11563 switch (LangOpts.getDefaultCallingConv()) { 11564 case LangOptions::DCC_None: 11565 break; 11566 case LangOptions::DCC_CDecl: 11567 return CC_C; 11568 case LangOptions::DCC_FastCall: 11569 if (getTargetInfo().hasFeature("sse2") && !IsVariadic) 11570 return CC_X86FastCall; 11571 break; 11572 case LangOptions::DCC_StdCall: 11573 if (!IsVariadic) 11574 return CC_X86StdCall; 11575 break; 11576 case LangOptions::DCC_VectorCall: 11577 // __vectorcall cannot be applied to variadic functions. 11578 if (!IsVariadic) 11579 return CC_X86VectorCall; 11580 break; 11581 case LangOptions::DCC_RegCall: 11582 // __regcall cannot be applied to variadic functions. 11583 if (!IsVariadic) 11584 return CC_X86RegCall; 11585 break; 11586 } 11587 } 11588 return Target->getDefaultCallingConv(); 11589 } 11590 11591 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const { 11592 // Pass through to the C++ ABI object 11593 return ABI->isNearlyEmpty(RD); 11594 } 11595 11596 VTableContextBase *ASTContext::getVTableContext() { 11597 if (!VTContext.get()) { 11598 auto ABI = Target->getCXXABI(); 11599 if (ABI.isMicrosoft()) 11600 VTContext.reset(new MicrosoftVTableContext(*this)); 11601 else { 11602 auto ComponentLayout = getLangOpts().RelativeCXXABIVTables 11603 ? ItaniumVTableContext::Relative 11604 : ItaniumVTableContext::Pointer; 11605 VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout)); 11606 } 11607 } 11608 return VTContext.get(); 11609 } 11610 11611 MangleContext *ASTContext::createMangleContext(const TargetInfo *T) { 11612 if (!T) 11613 T = Target; 11614 switch (T->getCXXABI().getKind()) { 11615 case TargetCXXABI::AppleARM64: 11616 case TargetCXXABI::Fuchsia: 11617 case TargetCXXABI::GenericAArch64: 11618 case TargetCXXABI::GenericItanium: 11619 case TargetCXXABI::GenericARM: 11620 case TargetCXXABI::GenericMIPS: 11621 case TargetCXXABI::iOS: 11622 case TargetCXXABI::WebAssembly: 11623 case TargetCXXABI::WatchOS: 11624 case TargetCXXABI::XL: 11625 return ItaniumMangleContext::create(*this, getDiagnostics()); 11626 case TargetCXXABI::Microsoft: 11627 return MicrosoftMangleContext::create(*this, getDiagnostics()); 11628 } 11629 llvm_unreachable("Unsupported ABI"); 11630 } 11631 11632 MangleContext *ASTContext::createDeviceMangleContext(const TargetInfo &T) { 11633 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft && 11634 "Device mangle context does not support Microsoft mangling."); 11635 switch (T.getCXXABI().getKind()) { 11636 case TargetCXXABI::AppleARM64: 11637 case TargetCXXABI::Fuchsia: 11638 case TargetCXXABI::GenericAArch64: 11639 case TargetCXXABI::GenericItanium: 11640 case TargetCXXABI::GenericARM: 11641 case TargetCXXABI::GenericMIPS: 11642 case TargetCXXABI::iOS: 11643 case TargetCXXABI::WebAssembly: 11644 case TargetCXXABI::WatchOS: 11645 case TargetCXXABI::XL: 11646 return ItaniumMangleContext::create( 11647 *this, getDiagnostics(), 11648 [](ASTContext &, const NamedDecl *ND) -> llvm::Optional<unsigned> { 11649 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) 11650 return RD->getDeviceLambdaManglingNumber(); 11651 return llvm::None; 11652 }); 11653 case TargetCXXABI::Microsoft: 11654 return MicrosoftMangleContext::create(*this, getDiagnostics()); 11655 } 11656 llvm_unreachable("Unsupported ABI"); 11657 } 11658 11659 CXXABI::~CXXABI() = default; 11660 11661 size_t ASTContext::getSideTableAllocatedMemory() const { 11662 return ASTRecordLayouts.getMemorySize() + 11663 llvm::capacity_in_bytes(ObjCLayouts) + 11664 llvm::capacity_in_bytes(KeyFunctions) + 11665 llvm::capacity_in_bytes(ObjCImpls) + 11666 llvm::capacity_in_bytes(BlockVarCopyInits) + 11667 llvm::capacity_in_bytes(DeclAttrs) + 11668 llvm::capacity_in_bytes(TemplateOrInstantiation) + 11669 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) + 11670 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) + 11671 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) + 11672 llvm::capacity_in_bytes(OverriddenMethods) + 11673 llvm::capacity_in_bytes(Types) + 11674 llvm::capacity_in_bytes(VariableArrayTypes); 11675 } 11676 11677 /// getIntTypeForBitwidth - 11678 /// sets integer QualTy according to specified details: 11679 /// bitwidth, signed/unsigned. 11680 /// Returns empty type if there is no appropriate target types. 11681 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth, 11682 unsigned Signed) const { 11683 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed); 11684 CanQualType QualTy = getFromTargetType(Ty); 11685 if (!QualTy && DestWidth == 128) 11686 return Signed ? Int128Ty : UnsignedInt128Ty; 11687 return QualTy; 11688 } 11689 11690 /// getRealTypeForBitwidth - 11691 /// sets floating point QualTy according to specified bitwidth. 11692 /// Returns empty type if there is no appropriate target types. 11693 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth, 11694 FloatModeKind ExplicitType) const { 11695 FloatModeKind Ty = 11696 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType); 11697 switch (Ty) { 11698 case FloatModeKind::Float: 11699 return FloatTy; 11700 case FloatModeKind::Double: 11701 return DoubleTy; 11702 case FloatModeKind::LongDouble: 11703 return LongDoubleTy; 11704 case FloatModeKind::Float128: 11705 return Float128Ty; 11706 case FloatModeKind::Ibm128: 11707 return Ibm128Ty; 11708 case FloatModeKind::NoFloat: 11709 return {}; 11710 } 11711 11712 llvm_unreachable("Unhandled TargetInfo::RealType value"); 11713 } 11714 11715 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) { 11716 if (Number > 1) 11717 MangleNumbers[ND] = Number; 11718 } 11719 11720 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const { 11721 auto I = MangleNumbers.find(ND); 11722 return I != MangleNumbers.end() ? I->second : 1; 11723 } 11724 11725 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) { 11726 if (Number > 1) 11727 StaticLocalNumbers[VD] = Number; 11728 } 11729 11730 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const { 11731 auto I = StaticLocalNumbers.find(VD); 11732 return I != StaticLocalNumbers.end() ? I->second : 1; 11733 } 11734 11735 MangleNumberingContext & 11736 ASTContext::getManglingNumberContext(const DeclContext *DC) { 11737 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C. 11738 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC]; 11739 if (!MCtx) 11740 MCtx = createMangleNumberingContext(); 11741 return *MCtx; 11742 } 11743 11744 MangleNumberingContext & 11745 ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) { 11746 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C. 11747 std::unique_ptr<MangleNumberingContext> &MCtx = 11748 ExtraMangleNumberingContexts[D]; 11749 if (!MCtx) 11750 MCtx = createMangleNumberingContext(); 11751 return *MCtx; 11752 } 11753 11754 std::unique_ptr<MangleNumberingContext> 11755 ASTContext::createMangleNumberingContext() const { 11756 return ABI->createMangleNumberingContext(); 11757 } 11758 11759 const CXXConstructorDecl * 11760 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) { 11761 return ABI->getCopyConstructorForExceptionObject( 11762 cast<CXXRecordDecl>(RD->getFirstDecl())); 11763 } 11764 11765 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD, 11766 CXXConstructorDecl *CD) { 11767 return ABI->addCopyConstructorForExceptionObject( 11768 cast<CXXRecordDecl>(RD->getFirstDecl()), 11769 cast<CXXConstructorDecl>(CD->getFirstDecl())); 11770 } 11771 11772 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD, 11773 TypedefNameDecl *DD) { 11774 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD); 11775 } 11776 11777 TypedefNameDecl * 11778 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) { 11779 return ABI->getTypedefNameForUnnamedTagDecl(TD); 11780 } 11781 11782 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD, 11783 DeclaratorDecl *DD) { 11784 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD); 11785 } 11786 11787 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) { 11788 return ABI->getDeclaratorForUnnamedTagDecl(TD); 11789 } 11790 11791 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) { 11792 ParamIndices[D] = index; 11793 } 11794 11795 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const { 11796 ParameterIndexTable::const_iterator I = ParamIndices.find(D); 11797 assert(I != ParamIndices.end() && 11798 "ParmIndices lacks entry set by ParmVarDecl"); 11799 return I->second; 11800 } 11801 11802 QualType ASTContext::getStringLiteralArrayType(QualType EltTy, 11803 unsigned Length) const { 11804 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 11805 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 11806 EltTy = EltTy.withConst(); 11807 11808 EltTy = adjustStringLiteralBaseType(EltTy); 11809 11810 // Get an array type for the string, according to C99 6.4.5. This includes 11811 // the null terminator character. 11812 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr, 11813 ArrayType::Normal, /*IndexTypeQuals*/ 0); 11814 } 11815 11816 StringLiteral * 11817 ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const { 11818 StringLiteral *&Result = StringLiteralCache[Key]; 11819 if (!Result) 11820 Result = StringLiteral::Create( 11821 *this, Key, StringLiteral::Ascii, 11822 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()), 11823 SourceLocation()); 11824 return Result; 11825 } 11826 11827 MSGuidDecl * 11828 ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const { 11829 assert(MSGuidTagDecl && "building MS GUID without MS extensions?"); 11830 11831 llvm::FoldingSetNodeID ID; 11832 MSGuidDecl::Profile(ID, Parts); 11833 11834 void *InsertPos; 11835 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos)) 11836 return Existing; 11837 11838 QualType GUIDType = getMSGuidType().withConst(); 11839 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts); 11840 MSGuidDecls.InsertNode(New, InsertPos); 11841 return New; 11842 } 11843 11844 TemplateParamObjectDecl * 11845 ASTContext::getTemplateParamObjectDecl(QualType T, const APValue &V) const { 11846 assert(T->isRecordType() && "template param object of unexpected type"); 11847 11848 // C++ [temp.param]p8: 11849 // [...] a static storage duration object of type 'const T' [...] 11850 T.addConst(); 11851 11852 llvm::FoldingSetNodeID ID; 11853 TemplateParamObjectDecl::Profile(ID, T, V); 11854 11855 void *InsertPos; 11856 if (TemplateParamObjectDecl *Existing = 11857 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos)) 11858 return Existing; 11859 11860 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V); 11861 TemplateParamObjectDecls.InsertNode(New, InsertPos); 11862 return New; 11863 } 11864 11865 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const { 11866 const llvm::Triple &T = getTargetInfo().getTriple(); 11867 if (!T.isOSDarwin()) 11868 return false; 11869 11870 if (!(T.isiOS() && T.isOSVersionLT(7)) && 11871 !(T.isMacOSX() && T.isOSVersionLT(10, 9))) 11872 return false; 11873 11874 QualType AtomicTy = E->getPtr()->getType()->getPointeeType(); 11875 CharUnits sizeChars = getTypeSizeInChars(AtomicTy); 11876 uint64_t Size = sizeChars.getQuantity(); 11877 CharUnits alignChars = getTypeAlignInChars(AtomicTy); 11878 unsigned Align = alignChars.getQuantity(); 11879 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth(); 11880 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits); 11881 } 11882 11883 bool 11884 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, 11885 const ObjCMethodDecl *MethodImpl) { 11886 // No point trying to match an unavailable/deprecated mothod. 11887 if (MethodDecl->hasAttr<UnavailableAttr>() 11888 || MethodDecl->hasAttr<DeprecatedAttr>()) 11889 return false; 11890 if (MethodDecl->getObjCDeclQualifier() != 11891 MethodImpl->getObjCDeclQualifier()) 11892 return false; 11893 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType())) 11894 return false; 11895 11896 if (MethodDecl->param_size() != MethodImpl->param_size()) 11897 return false; 11898 11899 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(), 11900 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(), 11901 EF = MethodDecl->param_end(); 11902 IM != EM && IF != EF; ++IM, ++IF) { 11903 const ParmVarDecl *DeclVar = (*IF); 11904 const ParmVarDecl *ImplVar = (*IM); 11905 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier()) 11906 return false; 11907 if (!hasSameType(DeclVar->getType(), ImplVar->getType())) 11908 return false; 11909 } 11910 11911 return (MethodDecl->isVariadic() == MethodImpl->isVariadic()); 11912 } 11913 11914 uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const { 11915 LangAS AS; 11916 if (QT->getUnqualifiedDesugaredType()->isNullPtrType()) 11917 AS = LangAS::Default; 11918 else 11919 AS = QT->getPointeeType().getAddressSpace(); 11920 11921 return getTargetInfo().getNullPointerValue(AS); 11922 } 11923 11924 unsigned ASTContext::getTargetAddressSpace(QualType T) const { 11925 // Return the address space for the type. If the type is a 11926 // function type without an address space qualifier, the 11927 // program address space is used. Otherwise, the target picks 11928 // the best address space based on the type information 11929 return T->isFunctionType() && !T.hasAddressSpace() 11930 ? getTargetInfo().getProgramAddressSpace() 11931 : getTargetAddressSpace(T.getQualifiers()); 11932 } 11933 11934 unsigned ASTContext::getTargetAddressSpace(Qualifiers Q) const { 11935 return getTargetAddressSpace(Q.getAddressSpace()); 11936 } 11937 11938 unsigned ASTContext::getTargetAddressSpace(LangAS AS) const { 11939 if (isTargetAddressSpace(AS)) 11940 return toTargetAddressSpace(AS); 11941 else 11942 return (*AddrSpaceMap)[(unsigned)AS]; 11943 } 11944 11945 QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const { 11946 assert(Ty->isFixedPointType()); 11947 11948 if (Ty->isSaturatedFixedPointType()) return Ty; 11949 11950 switch (Ty->castAs<BuiltinType>()->getKind()) { 11951 default: 11952 llvm_unreachable("Not a fixed point type!"); 11953 case BuiltinType::ShortAccum: 11954 return SatShortAccumTy; 11955 case BuiltinType::Accum: 11956 return SatAccumTy; 11957 case BuiltinType::LongAccum: 11958 return SatLongAccumTy; 11959 case BuiltinType::UShortAccum: 11960 return SatUnsignedShortAccumTy; 11961 case BuiltinType::UAccum: 11962 return SatUnsignedAccumTy; 11963 case BuiltinType::ULongAccum: 11964 return SatUnsignedLongAccumTy; 11965 case BuiltinType::ShortFract: 11966 return SatShortFractTy; 11967 case BuiltinType::Fract: 11968 return SatFractTy; 11969 case BuiltinType::LongFract: 11970 return SatLongFractTy; 11971 case BuiltinType::UShortFract: 11972 return SatUnsignedShortFractTy; 11973 case BuiltinType::UFract: 11974 return SatUnsignedFractTy; 11975 case BuiltinType::ULongFract: 11976 return SatUnsignedLongFractTy; 11977 } 11978 } 11979 11980 LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const { 11981 if (LangOpts.OpenCL) 11982 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS); 11983 11984 if (LangOpts.CUDA) 11985 return getTargetInfo().getCUDABuiltinAddressSpace(AS); 11986 11987 return getLangASFromTargetAS(AS); 11988 } 11989 11990 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that 11991 // doesn't include ASTContext.h 11992 template 11993 clang::LazyGenerationalUpdatePtr< 11994 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType 11995 clang::LazyGenerationalUpdatePtr< 11996 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue( 11997 const clang::ASTContext &Ctx, Decl *Value); 11998 11999 unsigned char ASTContext::getFixedPointScale(QualType Ty) const { 12000 assert(Ty->isFixedPointType()); 12001 12002 const TargetInfo &Target = getTargetInfo(); 12003 switch (Ty->castAs<BuiltinType>()->getKind()) { 12004 default: 12005 llvm_unreachable("Not a fixed point type!"); 12006 case BuiltinType::ShortAccum: 12007 case BuiltinType::SatShortAccum: 12008 return Target.getShortAccumScale(); 12009 case BuiltinType::Accum: 12010 case BuiltinType::SatAccum: 12011 return Target.getAccumScale(); 12012 case BuiltinType::LongAccum: 12013 case BuiltinType::SatLongAccum: 12014 return Target.getLongAccumScale(); 12015 case BuiltinType::UShortAccum: 12016 case BuiltinType::SatUShortAccum: 12017 return Target.getUnsignedShortAccumScale(); 12018 case BuiltinType::UAccum: 12019 case BuiltinType::SatUAccum: 12020 return Target.getUnsignedAccumScale(); 12021 case BuiltinType::ULongAccum: 12022 case BuiltinType::SatULongAccum: 12023 return Target.getUnsignedLongAccumScale(); 12024 case BuiltinType::ShortFract: 12025 case BuiltinType::SatShortFract: 12026 return Target.getShortFractScale(); 12027 case BuiltinType::Fract: 12028 case BuiltinType::SatFract: 12029 return Target.getFractScale(); 12030 case BuiltinType::LongFract: 12031 case BuiltinType::SatLongFract: 12032 return Target.getLongFractScale(); 12033 case BuiltinType::UShortFract: 12034 case BuiltinType::SatUShortFract: 12035 return Target.getUnsignedShortFractScale(); 12036 case BuiltinType::UFract: 12037 case BuiltinType::SatUFract: 12038 return Target.getUnsignedFractScale(); 12039 case BuiltinType::ULongFract: 12040 case BuiltinType::SatULongFract: 12041 return Target.getUnsignedLongFractScale(); 12042 } 12043 } 12044 12045 unsigned char ASTContext::getFixedPointIBits(QualType Ty) const { 12046 assert(Ty->isFixedPointType()); 12047 12048 const TargetInfo &Target = getTargetInfo(); 12049 switch (Ty->castAs<BuiltinType>()->getKind()) { 12050 default: 12051 llvm_unreachable("Not a fixed point type!"); 12052 case BuiltinType::ShortAccum: 12053 case BuiltinType::SatShortAccum: 12054 return Target.getShortAccumIBits(); 12055 case BuiltinType::Accum: 12056 case BuiltinType::SatAccum: 12057 return Target.getAccumIBits(); 12058 case BuiltinType::LongAccum: 12059 case BuiltinType::SatLongAccum: 12060 return Target.getLongAccumIBits(); 12061 case BuiltinType::UShortAccum: 12062 case BuiltinType::SatUShortAccum: 12063 return Target.getUnsignedShortAccumIBits(); 12064 case BuiltinType::UAccum: 12065 case BuiltinType::SatUAccum: 12066 return Target.getUnsignedAccumIBits(); 12067 case BuiltinType::ULongAccum: 12068 case BuiltinType::SatULongAccum: 12069 return Target.getUnsignedLongAccumIBits(); 12070 case BuiltinType::ShortFract: 12071 case BuiltinType::SatShortFract: 12072 case BuiltinType::Fract: 12073 case BuiltinType::SatFract: 12074 case BuiltinType::LongFract: 12075 case BuiltinType::SatLongFract: 12076 case BuiltinType::UShortFract: 12077 case BuiltinType::SatUShortFract: 12078 case BuiltinType::UFract: 12079 case BuiltinType::SatUFract: 12080 case BuiltinType::ULongFract: 12081 case BuiltinType::SatULongFract: 12082 return 0; 12083 } 12084 } 12085 12086 llvm::FixedPointSemantics 12087 ASTContext::getFixedPointSemantics(QualType Ty) const { 12088 assert((Ty->isFixedPointType() || Ty->isIntegerType()) && 12089 "Can only get the fixed point semantics for a " 12090 "fixed point or integer type."); 12091 if (Ty->isIntegerType()) 12092 return llvm::FixedPointSemantics::GetIntegerSemantics( 12093 getIntWidth(Ty), Ty->isSignedIntegerType()); 12094 12095 bool isSigned = Ty->isSignedFixedPointType(); 12096 return llvm::FixedPointSemantics( 12097 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned, 12098 Ty->isSaturatedFixedPointType(), 12099 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding()); 12100 } 12101 12102 llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const { 12103 assert(Ty->isFixedPointType()); 12104 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty)); 12105 } 12106 12107 llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const { 12108 assert(Ty->isFixedPointType()); 12109 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty)); 12110 } 12111 12112 QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const { 12113 assert(Ty->isUnsignedFixedPointType() && 12114 "Expected unsigned fixed point type"); 12115 12116 switch (Ty->castAs<BuiltinType>()->getKind()) { 12117 case BuiltinType::UShortAccum: 12118 return ShortAccumTy; 12119 case BuiltinType::UAccum: 12120 return AccumTy; 12121 case BuiltinType::ULongAccum: 12122 return LongAccumTy; 12123 case BuiltinType::SatUShortAccum: 12124 return SatShortAccumTy; 12125 case BuiltinType::SatUAccum: 12126 return SatAccumTy; 12127 case BuiltinType::SatULongAccum: 12128 return SatLongAccumTy; 12129 case BuiltinType::UShortFract: 12130 return ShortFractTy; 12131 case BuiltinType::UFract: 12132 return FractTy; 12133 case BuiltinType::ULongFract: 12134 return LongFractTy; 12135 case BuiltinType::SatUShortFract: 12136 return SatShortFractTy; 12137 case BuiltinType::SatUFract: 12138 return SatFractTy; 12139 case BuiltinType::SatULongFract: 12140 return SatLongFractTy; 12141 default: 12142 llvm_unreachable("Unexpected unsigned fixed point type"); 12143 } 12144 } 12145 12146 ParsedTargetAttr 12147 ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const { 12148 assert(TD != nullptr); 12149 ParsedTargetAttr ParsedAttr = TD->parse(); 12150 12151 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) { 12152 return !Target->isValidFeatureName(StringRef{Feat}.substr(1)); 12153 }); 12154 return ParsedAttr; 12155 } 12156 12157 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 12158 const FunctionDecl *FD) const { 12159 if (FD) 12160 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD)); 12161 else 12162 Target->initFeatureMap(FeatureMap, getDiagnostics(), 12163 Target->getTargetOpts().CPU, 12164 Target->getTargetOpts().Features); 12165 } 12166 12167 // Fills in the supplied string map with the set of target features for the 12168 // passed in function. 12169 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 12170 GlobalDecl GD) const { 12171 StringRef TargetCPU = Target->getTargetOpts().CPU; 12172 const FunctionDecl *FD = GD.getDecl()->getAsFunction(); 12173 if (const auto *TD = FD->getAttr<TargetAttr>()) { 12174 ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD); 12175 12176 // Make a copy of the features as passed on the command line into the 12177 // beginning of the additional features from the function to override. 12178 ParsedAttr.Features.insert( 12179 ParsedAttr.Features.begin(), 12180 Target->getTargetOpts().FeaturesAsWritten.begin(), 12181 Target->getTargetOpts().FeaturesAsWritten.end()); 12182 12183 if (ParsedAttr.Architecture != "" && 12184 Target->isValidCPUName(ParsedAttr.Architecture)) 12185 TargetCPU = ParsedAttr.Architecture; 12186 12187 // Now populate the feature map, first with the TargetCPU which is either 12188 // the default or a new one from the target attribute string. Then we'll use 12189 // the passed in features (FeaturesAsWritten) along with the new ones from 12190 // the attribute. 12191 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, 12192 ParsedAttr.Features); 12193 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) { 12194 llvm::SmallVector<StringRef, 32> FeaturesTmp; 12195 Target->getCPUSpecificCPUDispatchFeatures( 12196 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp); 12197 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end()); 12198 Features.insert(Features.begin(), 12199 Target->getTargetOpts().FeaturesAsWritten.begin(), 12200 Target->getTargetOpts().FeaturesAsWritten.end()); 12201 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features); 12202 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) { 12203 std::vector<std::string> Features; 12204 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex()); 12205 if (VersionStr.startswith("arch=")) 12206 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1); 12207 else if (VersionStr != "default") 12208 Features.push_back((StringRef{"+"} + VersionStr).str()); 12209 12210 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features); 12211 } else { 12212 FeatureMap = Target->getTargetOpts().FeatureMap; 12213 } 12214 } 12215 12216 OMPTraitInfo &ASTContext::getNewOMPTraitInfo() { 12217 OMPTraitInfoVector.emplace_back(new OMPTraitInfo()); 12218 return *OMPTraitInfoVector.back(); 12219 } 12220 12221 const StreamingDiagnostic &clang:: 12222 operator<<(const StreamingDiagnostic &DB, 12223 const ASTContext::SectionInfo &Section) { 12224 if (Section.Decl) 12225 return DB << Section.Decl; 12226 return DB << "a prior #pragma section"; 12227 } 12228 12229 bool ASTContext::mayExternalizeStaticVar(const Decl *D) const { 12230 bool IsStaticVar = 12231 isa<VarDecl>(D) && cast<VarDecl>(D)->getStorageClass() == SC_Static; 12232 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() && 12233 !D->getAttr<CUDADeviceAttr>()->isImplicit()) || 12234 (D->hasAttr<CUDAConstantAttr>() && 12235 !D->getAttr<CUDAConstantAttr>()->isImplicit()); 12236 // CUDA/HIP: static managed variables need to be externalized since it is 12237 // a declaration in IR, therefore cannot have internal linkage. 12238 return IsStaticVar && 12239 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar); 12240 } 12241 12242 bool ASTContext::shouldExternalizeStaticVar(const Decl *D) const { 12243 return mayExternalizeStaticVar(D) && 12244 (D->hasAttr<HIPManagedAttr>() || 12245 CUDADeviceVarODRUsedByHost.count(cast<VarDecl>(D))); 12246 } 12247 12248 StringRef ASTContext::getCUIDHash() const { 12249 if (!CUIDHash.empty()) 12250 return CUIDHash; 12251 if (LangOpts.CUID.empty()) 12252 return StringRef(); 12253 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true); 12254 return CUIDHash; 12255 } 12256