1 //===- ASTContext.cpp - Context to hold long-lived AST nodes --------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the ASTContext interface. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/ASTContext.h" 14 #include "CXXABI.h" 15 #include "Interp/Context.h" 16 #include "clang/AST/APValue.h" 17 #include "clang/AST/ASTConcept.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/ASTTypeTraits.h" 20 #include "clang/AST/Attr.h" 21 #include "clang/AST/AttrIterator.h" 22 #include "clang/AST/CharUnits.h" 23 #include "clang/AST/Comment.h" 24 #include "clang/AST/Decl.h" 25 #include "clang/AST/DeclBase.h" 26 #include "clang/AST/DeclCXX.h" 27 #include "clang/AST/DeclContextInternals.h" 28 #include "clang/AST/DeclObjC.h" 29 #include "clang/AST/DeclOpenMP.h" 30 #include "clang/AST/DeclTemplate.h" 31 #include "clang/AST/DeclarationName.h" 32 #include "clang/AST/DependenceFlags.h" 33 #include "clang/AST/Expr.h" 34 #include "clang/AST/ExprCXX.h" 35 #include "clang/AST/ExprConcepts.h" 36 #include "clang/AST/ExternalASTSource.h" 37 #include "clang/AST/Mangle.h" 38 #include "clang/AST/MangleNumberingContext.h" 39 #include "clang/AST/NestedNameSpecifier.h" 40 #include "clang/AST/ParentMapContext.h" 41 #include "clang/AST/RawCommentList.h" 42 #include "clang/AST/RecordLayout.h" 43 #include "clang/AST/Stmt.h" 44 #include "clang/AST/TemplateBase.h" 45 #include "clang/AST/TemplateName.h" 46 #include "clang/AST/Type.h" 47 #include "clang/AST/TypeLoc.h" 48 #include "clang/AST/UnresolvedSet.h" 49 #include "clang/AST/VTableBuilder.h" 50 #include "clang/Basic/AddressSpaces.h" 51 #include "clang/Basic/Builtins.h" 52 #include "clang/Basic/CommentOptions.h" 53 #include "clang/Basic/ExceptionSpecificationType.h" 54 #include "clang/Basic/IdentifierTable.h" 55 #include "clang/Basic/LLVM.h" 56 #include "clang/Basic/LangOptions.h" 57 #include "clang/Basic/Linkage.h" 58 #include "clang/Basic/Module.h" 59 #include "clang/Basic/NoSanitizeList.h" 60 #include "clang/Basic/ObjCRuntime.h" 61 #include "clang/Basic/SourceLocation.h" 62 #include "clang/Basic/SourceManager.h" 63 #include "clang/Basic/Specifiers.h" 64 #include "clang/Basic/TargetCXXABI.h" 65 #include "clang/Basic/TargetInfo.h" 66 #include "clang/Basic/XRayLists.h" 67 #include "llvm/ADT/APFixedPoint.h" 68 #include "llvm/ADT/APInt.h" 69 #include "llvm/ADT/APSInt.h" 70 #include "llvm/ADT/ArrayRef.h" 71 #include "llvm/ADT/DenseMap.h" 72 #include "llvm/ADT/DenseSet.h" 73 #include "llvm/ADT/FoldingSet.h" 74 #include "llvm/ADT/None.h" 75 #include "llvm/ADT/Optional.h" 76 #include "llvm/ADT/PointerUnion.h" 77 #include "llvm/ADT/STLExtras.h" 78 #include "llvm/ADT/SmallPtrSet.h" 79 #include "llvm/ADT/SmallVector.h" 80 #include "llvm/ADT/StringExtras.h" 81 #include "llvm/ADT/StringRef.h" 82 #include "llvm/ADT/Triple.h" 83 #include "llvm/Support/Capacity.h" 84 #include "llvm/Support/Casting.h" 85 #include "llvm/Support/Compiler.h" 86 #include "llvm/Support/ErrorHandling.h" 87 #include "llvm/Support/MD5.h" 88 #include "llvm/Support/MathExtras.h" 89 #include "llvm/Support/raw_ostream.h" 90 #include <algorithm> 91 #include <cassert> 92 #include <cstddef> 93 #include <cstdint> 94 #include <cstdlib> 95 #include <map> 96 #include <memory> 97 #include <string> 98 #include <tuple> 99 #include <utility> 100 101 using namespace clang; 102 103 enum FloatingRank { 104 BFloat16Rank, 105 Float16Rank, 106 HalfRank, 107 FloatRank, 108 DoubleRank, 109 LongDoubleRank, 110 Float128Rank, 111 Ibm128Rank 112 }; 113 114 /// \returns location that is relevant when searching for Doc comments related 115 /// to \p D. 116 static SourceLocation getDeclLocForCommentSearch(const Decl *D, 117 SourceManager &SourceMgr) { 118 assert(D); 119 120 // User can not attach documentation to implicit declarations. 121 if (D->isImplicit()) 122 return {}; 123 124 // User can not attach documentation to implicit instantiations. 125 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 126 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 127 return {}; 128 } 129 130 if (const auto *VD = dyn_cast<VarDecl>(D)) { 131 if (VD->isStaticDataMember() && 132 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 133 return {}; 134 } 135 136 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) { 137 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 138 return {}; 139 } 140 141 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) { 142 TemplateSpecializationKind TSK = CTSD->getSpecializationKind(); 143 if (TSK == TSK_ImplicitInstantiation || 144 TSK == TSK_Undeclared) 145 return {}; 146 } 147 148 if (const auto *ED = dyn_cast<EnumDecl>(D)) { 149 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 150 return {}; 151 } 152 if (const auto *TD = dyn_cast<TagDecl>(D)) { 153 // When tag declaration (but not definition!) is part of the 154 // decl-specifier-seq of some other declaration, it doesn't get comment 155 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition()) 156 return {}; 157 } 158 // TODO: handle comments for function parameters properly. 159 if (isa<ParmVarDecl>(D)) 160 return {}; 161 162 // TODO: we could look up template parameter documentation in the template 163 // documentation. 164 if (isa<TemplateTypeParmDecl>(D) || 165 isa<NonTypeTemplateParmDecl>(D) || 166 isa<TemplateTemplateParmDecl>(D)) 167 return {}; 168 169 // Find declaration location. 170 // For Objective-C declarations we generally don't expect to have multiple 171 // declarators, thus use declaration starting location as the "declaration 172 // location". 173 // For all other declarations multiple declarators are used quite frequently, 174 // so we use the location of the identifier as the "declaration location". 175 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) || 176 isa<ObjCPropertyDecl>(D) || 177 isa<RedeclarableTemplateDecl>(D) || 178 isa<ClassTemplateSpecializationDecl>(D) || 179 // Allow association with Y across {} in `typedef struct X {} Y`. 180 isa<TypedefDecl>(D)) 181 return D->getBeginLoc(); 182 183 const SourceLocation DeclLoc = D->getLocation(); 184 if (DeclLoc.isMacroID()) { 185 if (isa<TypedefDecl>(D)) { 186 // If location of the typedef name is in a macro, it is because being 187 // declared via a macro. Try using declaration's starting location as 188 // the "declaration location". 189 return D->getBeginLoc(); 190 } 191 192 if (const auto *TD = dyn_cast<TagDecl>(D)) { 193 // If location of the tag decl is inside a macro, but the spelling of 194 // the tag name comes from a macro argument, it looks like a special 195 // macro like NS_ENUM is being used to define the tag decl. In that 196 // case, adjust the source location to the expansion loc so that we can 197 // attach the comment to the tag decl. 198 if (SourceMgr.isMacroArgExpansion(DeclLoc) && TD->isCompleteDefinition()) 199 return SourceMgr.getExpansionLoc(DeclLoc); 200 } 201 } 202 203 return DeclLoc; 204 } 205 206 RawComment *ASTContext::getRawCommentForDeclNoCacheImpl( 207 const Decl *D, const SourceLocation RepresentativeLocForDecl, 208 const std::map<unsigned, RawComment *> &CommentsInTheFile) const { 209 // If the declaration doesn't map directly to a location in a file, we 210 // can't find the comment. 211 if (RepresentativeLocForDecl.isInvalid() || 212 !RepresentativeLocForDecl.isFileID()) 213 return nullptr; 214 215 // If there are no comments anywhere, we won't find anything. 216 if (CommentsInTheFile.empty()) 217 return nullptr; 218 219 // Decompose the location for the declaration and find the beginning of the 220 // file buffer. 221 const std::pair<FileID, unsigned> DeclLocDecomp = 222 SourceMgr.getDecomposedLoc(RepresentativeLocForDecl); 223 224 // Slow path. 225 auto OffsetCommentBehindDecl = 226 CommentsInTheFile.lower_bound(DeclLocDecomp.second); 227 228 // First check whether we have a trailing comment. 229 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) { 230 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second; 231 if ((CommentBehindDecl->isDocumentation() || 232 LangOpts.CommentOpts.ParseAllComments) && 233 CommentBehindDecl->isTrailingComment() && 234 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) || 235 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) { 236 237 // Check that Doxygen trailing comment comes after the declaration, starts 238 // on the same line and in the same file as the declaration. 239 if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) == 240 Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first, 241 OffsetCommentBehindDecl->first)) { 242 return CommentBehindDecl; 243 } 244 } 245 } 246 247 // The comment just after the declaration was not a trailing comment. 248 // Let's look at the previous comment. 249 if (OffsetCommentBehindDecl == CommentsInTheFile.begin()) 250 return nullptr; 251 252 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl; 253 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second; 254 255 // Check that we actually have a non-member Doxygen comment. 256 if (!(CommentBeforeDecl->isDocumentation() || 257 LangOpts.CommentOpts.ParseAllComments) || 258 CommentBeforeDecl->isTrailingComment()) 259 return nullptr; 260 261 // Decompose the end of the comment. 262 const unsigned CommentEndOffset = 263 Comments.getCommentEndOffset(CommentBeforeDecl); 264 265 // Get the corresponding buffer. 266 bool Invalid = false; 267 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first, 268 &Invalid).data(); 269 if (Invalid) 270 return nullptr; 271 272 // Extract text between the comment and declaration. 273 StringRef Text(Buffer + CommentEndOffset, 274 DeclLocDecomp.second - CommentEndOffset); 275 276 // There should be no other declarations or preprocessor directives between 277 // comment and declaration. 278 if (Text.find_first_of(";{}#@") != StringRef::npos) 279 return nullptr; 280 281 return CommentBeforeDecl; 282 } 283 284 RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const { 285 const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr); 286 287 // If the declaration doesn't map directly to a location in a file, we 288 // can't find the comment. 289 if (DeclLoc.isInvalid() || !DeclLoc.isFileID()) 290 return nullptr; 291 292 if (ExternalSource && !CommentsLoaded) { 293 ExternalSource->ReadComments(); 294 CommentsLoaded = true; 295 } 296 297 if (Comments.empty()) 298 return nullptr; 299 300 const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first; 301 const auto CommentsInThisFile = Comments.getCommentsInFile(File); 302 if (!CommentsInThisFile || CommentsInThisFile->empty()) 303 return nullptr; 304 305 return getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile); 306 } 307 308 void ASTContext::addComment(const RawComment &RC) { 309 assert(LangOpts.RetainCommentsFromSystemHeaders || 310 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin())); 311 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc); 312 } 313 314 /// If we have a 'templated' declaration for a template, adjust 'D' to 315 /// refer to the actual template. 316 /// If we have an implicit instantiation, adjust 'D' to refer to template. 317 static const Decl &adjustDeclToTemplate(const Decl &D) { 318 if (const auto *FD = dyn_cast<FunctionDecl>(&D)) { 319 // Is this function declaration part of a function template? 320 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 321 return *FTD; 322 323 // Nothing to do if function is not an implicit instantiation. 324 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) 325 return D; 326 327 // Function is an implicit instantiation of a function template? 328 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate()) 329 return *FTD; 330 331 // Function is instantiated from a member definition of a class template? 332 if (const FunctionDecl *MemberDecl = 333 FD->getInstantiatedFromMemberFunction()) 334 return *MemberDecl; 335 336 return D; 337 } 338 if (const auto *VD = dyn_cast<VarDecl>(&D)) { 339 // Static data member is instantiated from a member definition of a class 340 // template? 341 if (VD->isStaticDataMember()) 342 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember()) 343 return *MemberDecl; 344 345 return D; 346 } 347 if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) { 348 // Is this class declaration part of a class template? 349 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate()) 350 return *CTD; 351 352 // Class is an implicit instantiation of a class template or partial 353 // specialization? 354 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) { 355 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation) 356 return D; 357 llvm::PointerUnion<ClassTemplateDecl *, 358 ClassTemplatePartialSpecializationDecl *> 359 PU = CTSD->getSpecializedTemplateOrPartial(); 360 return PU.is<ClassTemplateDecl *>() 361 ? *static_cast<const Decl *>(PU.get<ClassTemplateDecl *>()) 362 : *static_cast<const Decl *>( 363 PU.get<ClassTemplatePartialSpecializationDecl *>()); 364 } 365 366 // Class is instantiated from a member definition of a class template? 367 if (const MemberSpecializationInfo *Info = 368 CRD->getMemberSpecializationInfo()) 369 return *Info->getInstantiatedFrom(); 370 371 return D; 372 } 373 if (const auto *ED = dyn_cast<EnumDecl>(&D)) { 374 // Enum is instantiated from a member definition of a class template? 375 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum()) 376 return *MemberDecl; 377 378 return D; 379 } 380 // FIXME: Adjust alias templates? 381 return D; 382 } 383 384 const RawComment *ASTContext::getRawCommentForAnyRedecl( 385 const Decl *D, 386 const Decl **OriginalDecl) const { 387 if (!D) { 388 if (OriginalDecl) 389 OriginalDecl = nullptr; 390 return nullptr; 391 } 392 393 D = &adjustDeclToTemplate(*D); 394 395 // Any comment directly attached to D? 396 { 397 auto DeclComment = DeclRawComments.find(D); 398 if (DeclComment != DeclRawComments.end()) { 399 if (OriginalDecl) 400 *OriginalDecl = D; 401 return DeclComment->second; 402 } 403 } 404 405 // Any comment attached to any redeclaration of D? 406 const Decl *CanonicalD = D->getCanonicalDecl(); 407 if (!CanonicalD) 408 return nullptr; 409 410 { 411 auto RedeclComment = RedeclChainComments.find(CanonicalD); 412 if (RedeclComment != RedeclChainComments.end()) { 413 if (OriginalDecl) 414 *OriginalDecl = RedeclComment->second; 415 auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second); 416 assert(CommentAtRedecl != DeclRawComments.end() && 417 "This decl is supposed to have comment attached."); 418 return CommentAtRedecl->second; 419 } 420 } 421 422 // Any redeclarations of D that we haven't checked for comments yet? 423 // We can't use DenseMap::iterator directly since it'd get invalid. 424 auto LastCheckedRedecl = [this, CanonicalD]() -> const Decl * { 425 auto LookupRes = CommentlessRedeclChains.find(CanonicalD); 426 if (LookupRes != CommentlessRedeclChains.end()) 427 return LookupRes->second; 428 return nullptr; 429 }(); 430 431 for (const auto Redecl : D->redecls()) { 432 assert(Redecl); 433 // Skip all redeclarations that have been checked previously. 434 if (LastCheckedRedecl) { 435 if (LastCheckedRedecl == Redecl) { 436 LastCheckedRedecl = nullptr; 437 } 438 continue; 439 } 440 const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl); 441 if (RedeclComment) { 442 cacheRawCommentForDecl(*Redecl, *RedeclComment); 443 if (OriginalDecl) 444 *OriginalDecl = Redecl; 445 return RedeclComment; 446 } 447 CommentlessRedeclChains[CanonicalD] = Redecl; 448 } 449 450 if (OriginalDecl) 451 *OriginalDecl = nullptr; 452 return nullptr; 453 } 454 455 void ASTContext::cacheRawCommentForDecl(const Decl &OriginalD, 456 const RawComment &Comment) const { 457 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments); 458 DeclRawComments.try_emplace(&OriginalD, &Comment); 459 const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl(); 460 RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD); 461 CommentlessRedeclChains.erase(CanonicalDecl); 462 } 463 464 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod, 465 SmallVectorImpl<const NamedDecl *> &Redeclared) { 466 const DeclContext *DC = ObjCMethod->getDeclContext(); 467 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) { 468 const ObjCInterfaceDecl *ID = IMD->getClassInterface(); 469 if (!ID) 470 return; 471 // Add redeclared method here. 472 for (const auto *Ext : ID->known_extensions()) { 473 if (ObjCMethodDecl *RedeclaredMethod = 474 Ext->getMethod(ObjCMethod->getSelector(), 475 ObjCMethod->isInstanceMethod())) 476 Redeclared.push_back(RedeclaredMethod); 477 } 478 } 479 } 480 481 void ASTContext::attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls, 482 const Preprocessor *PP) { 483 if (Comments.empty() || Decls.empty()) 484 return; 485 486 FileID File; 487 for (Decl *D : Decls) { 488 SourceLocation Loc = D->getLocation(); 489 if (Loc.isValid()) { 490 // See if there are any new comments that are not attached to a decl. 491 // The location doesn't have to be precise - we care only about the file. 492 File = SourceMgr.getDecomposedLoc(Loc).first; 493 break; 494 } 495 } 496 497 if (File.isInvalid()) 498 return; 499 500 auto CommentsInThisFile = Comments.getCommentsInFile(File); 501 if (!CommentsInThisFile || CommentsInThisFile->empty() || 502 CommentsInThisFile->rbegin()->second->isAttached()) 503 return; 504 505 // There is at least one comment not attached to a decl. 506 // Maybe it should be attached to one of Decls? 507 // 508 // Note that this way we pick up not only comments that precede the 509 // declaration, but also comments that *follow* the declaration -- thanks to 510 // the lookahead in the lexer: we've consumed the semicolon and looked 511 // ahead through comments. 512 513 for (const Decl *D : Decls) { 514 assert(D); 515 if (D->isInvalidDecl()) 516 continue; 517 518 D = &adjustDeclToTemplate(*D); 519 520 const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr); 521 522 if (DeclLoc.isInvalid() || !DeclLoc.isFileID()) 523 continue; 524 525 if (DeclRawComments.count(D) > 0) 526 continue; 527 528 if (RawComment *const DocComment = 529 getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile)) { 530 cacheRawCommentForDecl(*D, *DocComment); 531 comments::FullComment *FC = DocComment->parse(*this, PP, D); 532 ParsedComments[D->getCanonicalDecl()] = FC; 533 } 534 } 535 } 536 537 comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC, 538 const Decl *D) const { 539 auto *ThisDeclInfo = new (*this) comments::DeclInfo; 540 ThisDeclInfo->CommentDecl = D; 541 ThisDeclInfo->IsFilled = false; 542 ThisDeclInfo->fill(); 543 ThisDeclInfo->CommentDecl = FC->getDecl(); 544 if (!ThisDeclInfo->TemplateParameters) 545 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters; 546 comments::FullComment *CFC = 547 new (*this) comments::FullComment(FC->getBlocks(), 548 ThisDeclInfo); 549 return CFC; 550 } 551 552 comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const { 553 const RawComment *RC = getRawCommentForDeclNoCache(D); 554 return RC ? RC->parse(*this, nullptr, D) : nullptr; 555 } 556 557 comments::FullComment *ASTContext::getCommentForDecl( 558 const Decl *D, 559 const Preprocessor *PP) const { 560 if (!D || D->isInvalidDecl()) 561 return nullptr; 562 D = &adjustDeclToTemplate(*D); 563 564 const Decl *Canonical = D->getCanonicalDecl(); 565 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos = 566 ParsedComments.find(Canonical); 567 568 if (Pos != ParsedComments.end()) { 569 if (Canonical != D) { 570 comments::FullComment *FC = Pos->second; 571 comments::FullComment *CFC = cloneFullComment(FC, D); 572 return CFC; 573 } 574 return Pos->second; 575 } 576 577 const Decl *OriginalDecl = nullptr; 578 579 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl); 580 if (!RC) { 581 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) { 582 SmallVector<const NamedDecl*, 8> Overridden; 583 const auto *OMD = dyn_cast<ObjCMethodDecl>(D); 584 if (OMD && OMD->isPropertyAccessor()) 585 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl()) 586 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP)) 587 return cloneFullComment(FC, D); 588 if (OMD) 589 addRedeclaredMethods(OMD, Overridden); 590 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden); 591 for (unsigned i = 0, e = Overridden.size(); i < e; i++) 592 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP)) 593 return cloneFullComment(FC, D); 594 } 595 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) { 596 // Attach any tag type's documentation to its typedef if latter 597 // does not have one of its own. 598 QualType QT = TD->getUnderlyingType(); 599 if (const auto *TT = QT->getAs<TagType>()) 600 if (const Decl *TD = TT->getDecl()) 601 if (comments::FullComment *FC = getCommentForDecl(TD, PP)) 602 return cloneFullComment(FC, D); 603 } 604 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) { 605 while (IC->getSuperClass()) { 606 IC = IC->getSuperClass(); 607 if (comments::FullComment *FC = getCommentForDecl(IC, PP)) 608 return cloneFullComment(FC, D); 609 } 610 } 611 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) { 612 if (const ObjCInterfaceDecl *IC = CD->getClassInterface()) 613 if (comments::FullComment *FC = getCommentForDecl(IC, PP)) 614 return cloneFullComment(FC, D); 615 } 616 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) { 617 if (!(RD = RD->getDefinition())) 618 return nullptr; 619 // Check non-virtual bases. 620 for (const auto &I : RD->bases()) { 621 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public)) 622 continue; 623 QualType Ty = I.getType(); 624 if (Ty.isNull()) 625 continue; 626 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) { 627 if (!(NonVirtualBase= NonVirtualBase->getDefinition())) 628 continue; 629 630 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP)) 631 return cloneFullComment(FC, D); 632 } 633 } 634 // Check virtual bases. 635 for (const auto &I : RD->vbases()) { 636 if (I.getAccessSpecifier() != AS_public) 637 continue; 638 QualType Ty = I.getType(); 639 if (Ty.isNull()) 640 continue; 641 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) { 642 if (!(VirtualBase= VirtualBase->getDefinition())) 643 continue; 644 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP)) 645 return cloneFullComment(FC, D); 646 } 647 } 648 } 649 return nullptr; 650 } 651 652 // If the RawComment was attached to other redeclaration of this Decl, we 653 // should parse the comment in context of that other Decl. This is important 654 // because comments can contain references to parameter names which can be 655 // different across redeclarations. 656 if (D != OriginalDecl && OriginalDecl) 657 return getCommentForDecl(OriginalDecl, PP); 658 659 comments::FullComment *FC = RC->parse(*this, PP, D); 660 ParsedComments[Canonical] = FC; 661 return FC; 662 } 663 664 void 665 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID, 666 const ASTContext &C, 667 TemplateTemplateParmDecl *Parm) { 668 ID.AddInteger(Parm->getDepth()); 669 ID.AddInteger(Parm->getPosition()); 670 ID.AddBoolean(Parm->isParameterPack()); 671 672 TemplateParameterList *Params = Parm->getTemplateParameters(); 673 ID.AddInteger(Params->size()); 674 for (TemplateParameterList::const_iterator P = Params->begin(), 675 PEnd = Params->end(); 676 P != PEnd; ++P) { 677 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { 678 ID.AddInteger(0); 679 ID.AddBoolean(TTP->isParameterPack()); 680 const TypeConstraint *TC = TTP->getTypeConstraint(); 681 ID.AddBoolean(TC != nullptr); 682 if (TC) 683 TC->getImmediatelyDeclaredConstraint()->Profile(ID, C, 684 /*Canonical=*/true); 685 if (TTP->isExpandedParameterPack()) { 686 ID.AddBoolean(true); 687 ID.AddInteger(TTP->getNumExpansionParameters()); 688 } else 689 ID.AddBoolean(false); 690 continue; 691 } 692 693 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 694 ID.AddInteger(1); 695 ID.AddBoolean(NTTP->isParameterPack()); 696 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr()); 697 if (NTTP->isExpandedParameterPack()) { 698 ID.AddBoolean(true); 699 ID.AddInteger(NTTP->getNumExpansionTypes()); 700 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { 701 QualType T = NTTP->getExpansionType(I); 702 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr()); 703 } 704 } else 705 ID.AddBoolean(false); 706 continue; 707 } 708 709 auto *TTP = cast<TemplateTemplateParmDecl>(*P); 710 ID.AddInteger(2); 711 Profile(ID, C, TTP); 712 } 713 Expr *RequiresClause = Parm->getTemplateParameters()->getRequiresClause(); 714 ID.AddBoolean(RequiresClause != nullptr); 715 if (RequiresClause) 716 RequiresClause->Profile(ID, C, /*Canonical=*/true); 717 } 718 719 static Expr * 720 canonicalizeImmediatelyDeclaredConstraint(const ASTContext &C, Expr *IDC, 721 QualType ConstrainedType) { 722 // This is a bit ugly - we need to form a new immediately-declared 723 // constraint that references the new parameter; this would ideally 724 // require semantic analysis (e.g. template<C T> struct S {}; - the 725 // converted arguments of C<T> could be an argument pack if C is 726 // declared as template<typename... T> concept C = ...). 727 // We don't have semantic analysis here so we dig deep into the 728 // ready-made constraint expr and change the thing manually. 729 ConceptSpecializationExpr *CSE; 730 if (const auto *Fold = dyn_cast<CXXFoldExpr>(IDC)) 731 CSE = cast<ConceptSpecializationExpr>(Fold->getLHS()); 732 else 733 CSE = cast<ConceptSpecializationExpr>(IDC); 734 ArrayRef<TemplateArgument> OldConverted = CSE->getTemplateArguments(); 735 SmallVector<TemplateArgument, 3> NewConverted; 736 NewConverted.reserve(OldConverted.size()); 737 if (OldConverted.front().getKind() == TemplateArgument::Pack) { 738 // The case: 739 // template<typename... T> concept C = true; 740 // template<C<int> T> struct S; -> constraint is C<{T, int}> 741 NewConverted.push_back(ConstrainedType); 742 llvm::append_range(NewConverted, 743 OldConverted.front().pack_elements().drop_front(1)); 744 TemplateArgument NewPack(NewConverted); 745 746 NewConverted.clear(); 747 NewConverted.push_back(NewPack); 748 assert(OldConverted.size() == 1 && 749 "Template parameter pack should be the last parameter"); 750 } else { 751 assert(OldConverted.front().getKind() == TemplateArgument::Type && 752 "Unexpected first argument kind for immediately-declared " 753 "constraint"); 754 NewConverted.push_back(ConstrainedType); 755 llvm::append_range(NewConverted, OldConverted.drop_front(1)); 756 } 757 Expr *NewIDC = ConceptSpecializationExpr::Create( 758 C, CSE->getNamedConcept(), NewConverted, nullptr, 759 CSE->isInstantiationDependent(), CSE->containsUnexpandedParameterPack()); 760 761 if (auto *OrigFold = dyn_cast<CXXFoldExpr>(IDC)) 762 NewIDC = new (C) CXXFoldExpr( 763 OrigFold->getType(), /*Callee*/nullptr, SourceLocation(), NewIDC, 764 BinaryOperatorKind::BO_LAnd, SourceLocation(), /*RHS=*/nullptr, 765 SourceLocation(), /*NumExpansions=*/None); 766 return NewIDC; 767 } 768 769 TemplateTemplateParmDecl * 770 ASTContext::getCanonicalTemplateTemplateParmDecl( 771 TemplateTemplateParmDecl *TTP) const { 772 // Check if we already have a canonical template template parameter. 773 llvm::FoldingSetNodeID ID; 774 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP); 775 void *InsertPos = nullptr; 776 CanonicalTemplateTemplateParm *Canonical 777 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 778 if (Canonical) 779 return Canonical->getParam(); 780 781 // Build a canonical template parameter list. 782 TemplateParameterList *Params = TTP->getTemplateParameters(); 783 SmallVector<NamedDecl *, 4> CanonParams; 784 CanonParams.reserve(Params->size()); 785 for (TemplateParameterList::const_iterator P = Params->begin(), 786 PEnd = Params->end(); 787 P != PEnd; ++P) { 788 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { 789 TemplateTypeParmDecl *NewTTP = TemplateTypeParmDecl::Create(*this, 790 getTranslationUnitDecl(), SourceLocation(), SourceLocation(), 791 TTP->getDepth(), TTP->getIndex(), nullptr, false, 792 TTP->isParameterPack(), TTP->hasTypeConstraint(), 793 TTP->isExpandedParameterPack() ? 794 llvm::Optional<unsigned>(TTP->getNumExpansionParameters()) : None); 795 if (const auto *TC = TTP->getTypeConstraint()) { 796 QualType ParamAsArgument(NewTTP->getTypeForDecl(), 0); 797 Expr *NewIDC = canonicalizeImmediatelyDeclaredConstraint( 798 *this, TC->getImmediatelyDeclaredConstraint(), 799 ParamAsArgument); 800 TemplateArgumentListInfo CanonArgsAsWritten; 801 if (auto *Args = TC->getTemplateArgsAsWritten()) 802 for (const auto &ArgLoc : Args->arguments()) 803 CanonArgsAsWritten.addArgument( 804 TemplateArgumentLoc(ArgLoc.getArgument(), 805 TemplateArgumentLocInfo())); 806 NewTTP->setTypeConstraint( 807 NestedNameSpecifierLoc(), 808 DeclarationNameInfo(TC->getNamedConcept()->getDeclName(), 809 SourceLocation()), /*FoundDecl=*/nullptr, 810 // Actually canonicalizing a TemplateArgumentLoc is difficult so we 811 // simply omit the ArgsAsWritten 812 TC->getNamedConcept(), /*ArgsAsWritten=*/nullptr, NewIDC); 813 } 814 CanonParams.push_back(NewTTP); 815 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 816 QualType T = getCanonicalType(NTTP->getType()); 817 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); 818 NonTypeTemplateParmDecl *Param; 819 if (NTTP->isExpandedParameterPack()) { 820 SmallVector<QualType, 2> ExpandedTypes; 821 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos; 822 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { 823 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I))); 824 ExpandedTInfos.push_back( 825 getTrivialTypeSourceInfo(ExpandedTypes.back())); 826 } 827 828 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 829 SourceLocation(), 830 SourceLocation(), 831 NTTP->getDepth(), 832 NTTP->getPosition(), nullptr, 833 T, 834 TInfo, 835 ExpandedTypes, 836 ExpandedTInfos); 837 } else { 838 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 839 SourceLocation(), 840 SourceLocation(), 841 NTTP->getDepth(), 842 NTTP->getPosition(), nullptr, 843 T, 844 NTTP->isParameterPack(), 845 TInfo); 846 } 847 if (AutoType *AT = T->getContainedAutoType()) { 848 if (AT->isConstrained()) { 849 Param->setPlaceholderTypeConstraint( 850 canonicalizeImmediatelyDeclaredConstraint( 851 *this, NTTP->getPlaceholderTypeConstraint(), T)); 852 } 853 } 854 CanonParams.push_back(Param); 855 856 } else 857 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl( 858 cast<TemplateTemplateParmDecl>(*P))); 859 } 860 861 Expr *CanonRequiresClause = nullptr; 862 if (Expr *RequiresClause = TTP->getTemplateParameters()->getRequiresClause()) 863 CanonRequiresClause = RequiresClause; 864 865 TemplateTemplateParmDecl *CanonTTP 866 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 867 SourceLocation(), TTP->getDepth(), 868 TTP->getPosition(), 869 TTP->isParameterPack(), 870 nullptr, 871 TemplateParameterList::Create(*this, SourceLocation(), 872 SourceLocation(), 873 CanonParams, 874 SourceLocation(), 875 CanonRequiresClause)); 876 877 // Get the new insert position for the node we care about. 878 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 879 assert(!Canonical && "Shouldn't be in the map!"); 880 (void)Canonical; 881 882 // Create the canonical template template parameter entry. 883 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP); 884 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos); 885 return CanonTTP; 886 } 887 888 TargetCXXABI::Kind ASTContext::getCXXABIKind() const { 889 auto Kind = getTargetInfo().getCXXABI().getKind(); 890 return getLangOpts().CXXABI.value_or(Kind); 891 } 892 893 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) { 894 if (!LangOpts.CPlusPlus) return nullptr; 895 896 switch (getCXXABIKind()) { 897 case TargetCXXABI::AppleARM64: 898 case TargetCXXABI::Fuchsia: 899 case TargetCXXABI::GenericARM: // Same as Itanium at this level 900 case TargetCXXABI::iOS: 901 case TargetCXXABI::WatchOS: 902 case TargetCXXABI::GenericAArch64: 903 case TargetCXXABI::GenericMIPS: 904 case TargetCXXABI::GenericItanium: 905 case TargetCXXABI::WebAssembly: 906 case TargetCXXABI::XL: 907 return CreateItaniumCXXABI(*this); 908 case TargetCXXABI::Microsoft: 909 return CreateMicrosoftCXXABI(*this); 910 } 911 llvm_unreachable("Invalid CXXABI type!"); 912 } 913 914 interp::Context &ASTContext::getInterpContext() { 915 if (!InterpContext) { 916 InterpContext.reset(new interp::Context(*this)); 917 } 918 return *InterpContext.get(); 919 } 920 921 ParentMapContext &ASTContext::getParentMapContext() { 922 if (!ParentMapCtx) 923 ParentMapCtx.reset(new ParentMapContext(*this)); 924 return *ParentMapCtx.get(); 925 } 926 927 static const LangASMap *getAddressSpaceMap(const TargetInfo &T, 928 const LangOptions &LOpts) { 929 if (LOpts.FakeAddressSpaceMap) { 930 // The fake address space map must have a distinct entry for each 931 // language-specific address space. 932 static const unsigned FakeAddrSpaceMap[] = { 933 0, // Default 934 1, // opencl_global 935 3, // opencl_local 936 2, // opencl_constant 937 0, // opencl_private 938 4, // opencl_generic 939 5, // opencl_global_device 940 6, // opencl_global_host 941 7, // cuda_device 942 8, // cuda_constant 943 9, // cuda_shared 944 1, // sycl_global 945 5, // sycl_global_device 946 6, // sycl_global_host 947 3, // sycl_local 948 0, // sycl_private 949 10, // ptr32_sptr 950 11, // ptr32_uptr 951 12 // ptr64 952 }; 953 return &FakeAddrSpaceMap; 954 } else { 955 return &T.getAddressSpaceMap(); 956 } 957 } 958 959 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI, 960 const LangOptions &LangOpts) { 961 switch (LangOpts.getAddressSpaceMapMangling()) { 962 case LangOptions::ASMM_Target: 963 return TI.useAddressSpaceMapMangling(); 964 case LangOptions::ASMM_On: 965 return true; 966 case LangOptions::ASMM_Off: 967 return false; 968 } 969 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything."); 970 } 971 972 ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM, 973 IdentifierTable &idents, SelectorTable &sels, 974 Builtin::Context &builtins, TranslationUnitKind TUKind) 975 : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize), 976 FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize), 977 TemplateSpecializationTypes(this_()), 978 DependentTemplateSpecializationTypes(this_()), AutoTypes(this_()), 979 SubstTemplateTemplateParmPacks(this_()), 980 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts), 981 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)), 982 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles, 983 LangOpts.XRayNeverInstrumentFiles, 984 LangOpts.XRayAttrListFiles, SM)), 985 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)), 986 PrintingPolicy(LOpts), Idents(idents), Selectors(sels), 987 BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this), 988 Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), 989 CompCategories(this_()), LastSDM(nullptr, 0) { 990 addTranslationUnitDecl(); 991 } 992 993 void ASTContext::cleanup() { 994 // Release the DenseMaps associated with DeclContext objects. 995 // FIXME: Is this the ideal solution? 996 ReleaseDeclContextMaps(); 997 998 // Call all of the deallocation functions on all of their targets. 999 for (auto &Pair : Deallocations) 1000 (Pair.first)(Pair.second); 1001 Deallocations.clear(); 1002 1003 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed 1004 // because they can contain DenseMaps. 1005 for (llvm::DenseMap<const ObjCContainerDecl*, 1006 const ASTRecordLayout*>::iterator 1007 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) 1008 // Increment in loop to prevent using deallocated memory. 1009 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second)) 1010 R->Destroy(*this); 1011 ObjCLayouts.clear(); 1012 1013 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator 1014 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) { 1015 // Increment in loop to prevent using deallocated memory. 1016 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second)) 1017 R->Destroy(*this); 1018 } 1019 ASTRecordLayouts.clear(); 1020 1021 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(), 1022 AEnd = DeclAttrs.end(); 1023 A != AEnd; ++A) 1024 A->second->~AttrVec(); 1025 DeclAttrs.clear(); 1026 1027 for (const auto &Value : ModuleInitializers) 1028 Value.second->~PerModuleInitializers(); 1029 ModuleInitializers.clear(); 1030 } 1031 1032 ASTContext::~ASTContext() { cleanup(); } 1033 1034 void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) { 1035 TraversalScope = TopLevelDecls; 1036 getParentMapContext().clear(); 1037 } 1038 1039 void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const { 1040 Deallocations.push_back({Callback, Data}); 1041 } 1042 1043 void 1044 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) { 1045 ExternalSource = std::move(Source); 1046 } 1047 1048 void ASTContext::PrintStats() const { 1049 llvm::errs() << "\n*** AST Context Stats:\n"; 1050 llvm::errs() << " " << Types.size() << " types total.\n"; 1051 1052 unsigned counts[] = { 1053 #define TYPE(Name, Parent) 0, 1054 #define ABSTRACT_TYPE(Name, Parent) 1055 #include "clang/AST/TypeNodes.inc" 1056 0 // Extra 1057 }; 1058 1059 for (unsigned i = 0, e = Types.size(); i != e; ++i) { 1060 Type *T = Types[i]; 1061 counts[(unsigned)T->getTypeClass()]++; 1062 } 1063 1064 unsigned Idx = 0; 1065 unsigned TotalBytes = 0; 1066 #define TYPE(Name, Parent) \ 1067 if (counts[Idx]) \ 1068 llvm::errs() << " " << counts[Idx] << " " << #Name \ 1069 << " types, " << sizeof(Name##Type) << " each " \ 1070 << "(" << counts[Idx] * sizeof(Name##Type) \ 1071 << " bytes)\n"; \ 1072 TotalBytes += counts[Idx] * sizeof(Name##Type); \ 1073 ++Idx; 1074 #define ABSTRACT_TYPE(Name, Parent) 1075 #include "clang/AST/TypeNodes.inc" 1076 1077 llvm::errs() << "Total bytes = " << TotalBytes << "\n"; 1078 1079 // Implicit special member functions. 1080 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/" 1081 << NumImplicitDefaultConstructors 1082 << " implicit default constructors created\n"; 1083 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/" 1084 << NumImplicitCopyConstructors 1085 << " implicit copy constructors created\n"; 1086 if (getLangOpts().CPlusPlus) 1087 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/" 1088 << NumImplicitMoveConstructors 1089 << " implicit move constructors created\n"; 1090 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/" 1091 << NumImplicitCopyAssignmentOperators 1092 << " implicit copy assignment operators created\n"; 1093 if (getLangOpts().CPlusPlus) 1094 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/" 1095 << NumImplicitMoveAssignmentOperators 1096 << " implicit move assignment operators created\n"; 1097 llvm::errs() << NumImplicitDestructorsDeclared << "/" 1098 << NumImplicitDestructors 1099 << " implicit destructors created\n"; 1100 1101 if (ExternalSource) { 1102 llvm::errs() << "\n"; 1103 ExternalSource->PrintStats(); 1104 } 1105 1106 BumpAlloc.PrintStats(); 1107 } 1108 1109 void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M, 1110 bool NotifyListeners) { 1111 if (NotifyListeners) 1112 if (auto *Listener = getASTMutationListener()) 1113 Listener->RedefinedHiddenDefinition(ND, M); 1114 1115 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M); 1116 } 1117 1118 void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) { 1119 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl())); 1120 if (It == MergedDefModules.end()) 1121 return; 1122 1123 auto &Merged = It->second; 1124 llvm::DenseSet<Module*> Found; 1125 for (Module *&M : Merged) 1126 if (!Found.insert(M).second) 1127 M = nullptr; 1128 llvm::erase_value(Merged, nullptr); 1129 } 1130 1131 ArrayRef<Module *> 1132 ASTContext::getModulesWithMergedDefinition(const NamedDecl *Def) { 1133 auto MergedIt = 1134 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl())); 1135 if (MergedIt == MergedDefModules.end()) 1136 return None; 1137 return MergedIt->second; 1138 } 1139 1140 void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) { 1141 if (LazyInitializers.empty()) 1142 return; 1143 1144 auto *Source = Ctx.getExternalSource(); 1145 assert(Source && "lazy initializers but no external source"); 1146 1147 auto LazyInits = std::move(LazyInitializers); 1148 LazyInitializers.clear(); 1149 1150 for (auto ID : LazyInits) 1151 Initializers.push_back(Source->GetExternalDecl(ID)); 1152 1153 assert(LazyInitializers.empty() && 1154 "GetExternalDecl for lazy module initializer added more inits"); 1155 } 1156 1157 void ASTContext::addModuleInitializer(Module *M, Decl *D) { 1158 // One special case: if we add a module initializer that imports another 1159 // module, and that module's only initializer is an ImportDecl, simplify. 1160 if (const auto *ID = dyn_cast<ImportDecl>(D)) { 1161 auto It = ModuleInitializers.find(ID->getImportedModule()); 1162 1163 // Maybe the ImportDecl does nothing at all. (Common case.) 1164 if (It == ModuleInitializers.end()) 1165 return; 1166 1167 // Maybe the ImportDecl only imports another ImportDecl. 1168 auto &Imported = *It->second; 1169 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) { 1170 Imported.resolve(*this); 1171 auto *OnlyDecl = Imported.Initializers.front(); 1172 if (isa<ImportDecl>(OnlyDecl)) 1173 D = OnlyDecl; 1174 } 1175 } 1176 1177 auto *&Inits = ModuleInitializers[M]; 1178 if (!Inits) 1179 Inits = new (*this) PerModuleInitializers; 1180 Inits->Initializers.push_back(D); 1181 } 1182 1183 void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) { 1184 auto *&Inits = ModuleInitializers[M]; 1185 if (!Inits) 1186 Inits = new (*this) PerModuleInitializers; 1187 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(), 1188 IDs.begin(), IDs.end()); 1189 } 1190 1191 ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) { 1192 auto It = ModuleInitializers.find(M); 1193 if (It == ModuleInitializers.end()) 1194 return None; 1195 1196 auto *Inits = It->second; 1197 Inits->resolve(*this); 1198 return Inits->Initializers; 1199 } 1200 1201 ExternCContextDecl *ASTContext::getExternCContextDecl() const { 1202 if (!ExternCContext) 1203 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl()); 1204 1205 return ExternCContext; 1206 } 1207 1208 BuiltinTemplateDecl * 1209 ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK, 1210 const IdentifierInfo *II) const { 1211 auto *BuiltinTemplate = 1212 BuiltinTemplateDecl::Create(*this, getTranslationUnitDecl(), II, BTK); 1213 BuiltinTemplate->setImplicit(); 1214 getTranslationUnitDecl()->addDecl(BuiltinTemplate); 1215 1216 return BuiltinTemplate; 1217 } 1218 1219 BuiltinTemplateDecl * 1220 ASTContext::getMakeIntegerSeqDecl() const { 1221 if (!MakeIntegerSeqDecl) 1222 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq, 1223 getMakeIntegerSeqName()); 1224 return MakeIntegerSeqDecl; 1225 } 1226 1227 BuiltinTemplateDecl * 1228 ASTContext::getTypePackElementDecl() const { 1229 if (!TypePackElementDecl) 1230 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element, 1231 getTypePackElementName()); 1232 return TypePackElementDecl; 1233 } 1234 1235 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name, 1236 RecordDecl::TagKind TK) const { 1237 SourceLocation Loc; 1238 RecordDecl *NewDecl; 1239 if (getLangOpts().CPlusPlus) 1240 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, 1241 Loc, &Idents.get(Name)); 1242 else 1243 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc, 1244 &Idents.get(Name)); 1245 NewDecl->setImplicit(); 1246 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit( 1247 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default)); 1248 return NewDecl; 1249 } 1250 1251 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T, 1252 StringRef Name) const { 1253 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); 1254 TypedefDecl *NewDecl = TypedefDecl::Create( 1255 const_cast<ASTContext &>(*this), getTranslationUnitDecl(), 1256 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo); 1257 NewDecl->setImplicit(); 1258 return NewDecl; 1259 } 1260 1261 TypedefDecl *ASTContext::getInt128Decl() const { 1262 if (!Int128Decl) 1263 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t"); 1264 return Int128Decl; 1265 } 1266 1267 TypedefDecl *ASTContext::getUInt128Decl() const { 1268 if (!UInt128Decl) 1269 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t"); 1270 return UInt128Decl; 1271 } 1272 1273 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) { 1274 auto *Ty = new (*this, TypeAlignment) BuiltinType(K); 1275 R = CanQualType::CreateUnsafe(QualType(Ty, 0)); 1276 Types.push_back(Ty); 1277 } 1278 1279 void ASTContext::InitBuiltinTypes(const TargetInfo &Target, 1280 const TargetInfo *AuxTarget) { 1281 assert((!this->Target || this->Target == &Target) && 1282 "Incorrect target reinitialization"); 1283 assert(VoidTy.isNull() && "Context reinitialized?"); 1284 1285 this->Target = &Target; 1286 this->AuxTarget = AuxTarget; 1287 1288 ABI.reset(createCXXABI(Target)); 1289 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts); 1290 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts); 1291 1292 // C99 6.2.5p19. 1293 InitBuiltinType(VoidTy, BuiltinType::Void); 1294 1295 // C99 6.2.5p2. 1296 InitBuiltinType(BoolTy, BuiltinType::Bool); 1297 // C99 6.2.5p3. 1298 if (LangOpts.CharIsSigned) 1299 InitBuiltinType(CharTy, BuiltinType::Char_S); 1300 else 1301 InitBuiltinType(CharTy, BuiltinType::Char_U); 1302 // C99 6.2.5p4. 1303 InitBuiltinType(SignedCharTy, BuiltinType::SChar); 1304 InitBuiltinType(ShortTy, BuiltinType::Short); 1305 InitBuiltinType(IntTy, BuiltinType::Int); 1306 InitBuiltinType(LongTy, BuiltinType::Long); 1307 InitBuiltinType(LongLongTy, BuiltinType::LongLong); 1308 1309 // C99 6.2.5p6. 1310 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar); 1311 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort); 1312 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt); 1313 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong); 1314 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong); 1315 1316 // C99 6.2.5p10. 1317 InitBuiltinType(FloatTy, BuiltinType::Float); 1318 InitBuiltinType(DoubleTy, BuiltinType::Double); 1319 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble); 1320 1321 // GNU extension, __float128 for IEEE quadruple precision 1322 InitBuiltinType(Float128Ty, BuiltinType::Float128); 1323 1324 // __ibm128 for IBM extended precision 1325 InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128); 1326 1327 // C11 extension ISO/IEC TS 18661-3 1328 InitBuiltinType(Float16Ty, BuiltinType::Float16); 1329 1330 // ISO/IEC JTC1 SC22 WG14 N1169 Extension 1331 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum); 1332 InitBuiltinType(AccumTy, BuiltinType::Accum); 1333 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum); 1334 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum); 1335 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum); 1336 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum); 1337 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract); 1338 InitBuiltinType(FractTy, BuiltinType::Fract); 1339 InitBuiltinType(LongFractTy, BuiltinType::LongFract); 1340 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract); 1341 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract); 1342 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract); 1343 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum); 1344 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum); 1345 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum); 1346 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum); 1347 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum); 1348 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum); 1349 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract); 1350 InitBuiltinType(SatFractTy, BuiltinType::SatFract); 1351 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract); 1352 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract); 1353 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract); 1354 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract); 1355 1356 // GNU extension, 128-bit integers. 1357 InitBuiltinType(Int128Ty, BuiltinType::Int128); 1358 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128); 1359 1360 // C++ 3.9.1p5 1361 if (TargetInfo::isTypeSigned(Target.getWCharType())) 1362 InitBuiltinType(WCharTy, BuiltinType::WChar_S); 1363 else // -fshort-wchar makes wchar_t be unsigned. 1364 InitBuiltinType(WCharTy, BuiltinType::WChar_U); 1365 if (LangOpts.CPlusPlus && LangOpts.WChar) 1366 WideCharTy = WCharTy; 1367 else { 1368 // C99 (or C++ using -fno-wchar). 1369 WideCharTy = getFromTargetType(Target.getWCharType()); 1370 } 1371 1372 WIntTy = getFromTargetType(Target.getWIntType()); 1373 1374 // C++20 (proposed) 1375 InitBuiltinType(Char8Ty, BuiltinType::Char8); 1376 1377 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 1378 InitBuiltinType(Char16Ty, BuiltinType::Char16); 1379 else // C99 1380 Char16Ty = getFromTargetType(Target.getChar16Type()); 1381 1382 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 1383 InitBuiltinType(Char32Ty, BuiltinType::Char32); 1384 else // C99 1385 Char32Ty = getFromTargetType(Target.getChar32Type()); 1386 1387 // Placeholder type for type-dependent expressions whose type is 1388 // completely unknown. No code should ever check a type against 1389 // DependentTy and users should never see it; however, it is here to 1390 // help diagnose failures to properly check for type-dependent 1391 // expressions. 1392 InitBuiltinType(DependentTy, BuiltinType::Dependent); 1393 1394 // Placeholder type for functions. 1395 InitBuiltinType(OverloadTy, BuiltinType::Overload); 1396 1397 // Placeholder type for bound members. 1398 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember); 1399 1400 // Placeholder type for pseudo-objects. 1401 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject); 1402 1403 // "any" type; useful for debugger-like clients. 1404 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny); 1405 1406 // Placeholder type for unbridged ARC casts. 1407 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast); 1408 1409 // Placeholder type for builtin functions. 1410 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn); 1411 1412 // Placeholder type for OMP array sections. 1413 if (LangOpts.OpenMP) { 1414 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection); 1415 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping); 1416 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator); 1417 } 1418 if (LangOpts.MatrixTypes) 1419 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx); 1420 1421 // Builtin types for 'id', 'Class', and 'SEL'. 1422 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId); 1423 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass); 1424 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel); 1425 1426 if (LangOpts.OpenCL) { 1427 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 1428 InitBuiltinType(SingletonId, BuiltinType::Id); 1429 #include "clang/Basic/OpenCLImageTypes.def" 1430 1431 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler); 1432 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent); 1433 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent); 1434 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue); 1435 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID); 1436 1437 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 1438 InitBuiltinType(Id##Ty, BuiltinType::Id); 1439 #include "clang/Basic/OpenCLExtensionTypes.def" 1440 } 1441 1442 if (Target.hasAArch64SVETypes()) { 1443 #define SVE_TYPE(Name, Id, SingletonId) \ 1444 InitBuiltinType(SingletonId, BuiltinType::Id); 1445 #include "clang/Basic/AArch64SVEACLETypes.def" 1446 } 1447 1448 if (Target.getTriple().isPPC64()) { 1449 #define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \ 1450 InitBuiltinType(Id##Ty, BuiltinType::Id); 1451 #include "clang/Basic/PPCTypes.def" 1452 #define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \ 1453 InitBuiltinType(Id##Ty, BuiltinType::Id); 1454 #include "clang/Basic/PPCTypes.def" 1455 } 1456 1457 if (Target.hasRISCVVTypes()) { 1458 #define RVV_TYPE(Name, Id, SingletonId) \ 1459 InitBuiltinType(SingletonId, BuiltinType::Id); 1460 #include "clang/Basic/RISCVVTypes.def" 1461 } 1462 1463 // Builtin type for __objc_yes and __objc_no 1464 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ? 1465 SignedCharTy : BoolTy); 1466 1467 ObjCConstantStringType = QualType(); 1468 1469 ObjCSuperType = QualType(); 1470 1471 // void * type 1472 if (LangOpts.OpenCLGenericAddressSpace) { 1473 auto Q = VoidTy.getQualifiers(); 1474 Q.setAddressSpace(LangAS::opencl_generic); 1475 VoidPtrTy = getPointerType(getCanonicalType( 1476 getQualifiedType(VoidTy.getUnqualifiedType(), Q))); 1477 } else { 1478 VoidPtrTy = getPointerType(VoidTy); 1479 } 1480 1481 // nullptr type (C++0x 2.14.7) 1482 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr); 1483 1484 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16 1485 InitBuiltinType(HalfTy, BuiltinType::Half); 1486 1487 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16); 1488 1489 // Builtin type used to help define __builtin_va_list. 1490 VaListTagDecl = nullptr; 1491 1492 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls. 1493 if (LangOpts.MicrosoftExt || LangOpts.Borland) { 1494 MSGuidTagDecl = buildImplicitRecord("_GUID"); 1495 getTranslationUnitDecl()->addDecl(MSGuidTagDecl); 1496 } 1497 } 1498 1499 DiagnosticsEngine &ASTContext::getDiagnostics() const { 1500 return SourceMgr.getDiagnostics(); 1501 } 1502 1503 AttrVec& ASTContext::getDeclAttrs(const Decl *D) { 1504 AttrVec *&Result = DeclAttrs[D]; 1505 if (!Result) { 1506 void *Mem = Allocate(sizeof(AttrVec)); 1507 Result = new (Mem) AttrVec; 1508 } 1509 1510 return *Result; 1511 } 1512 1513 /// Erase the attributes corresponding to the given declaration. 1514 void ASTContext::eraseDeclAttrs(const Decl *D) { 1515 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D); 1516 if (Pos != DeclAttrs.end()) { 1517 Pos->second->~AttrVec(); 1518 DeclAttrs.erase(Pos); 1519 } 1520 } 1521 1522 // FIXME: Remove ? 1523 MemberSpecializationInfo * 1524 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) { 1525 assert(Var->isStaticDataMember() && "Not a static data member"); 1526 return getTemplateOrSpecializationInfo(Var) 1527 .dyn_cast<MemberSpecializationInfo *>(); 1528 } 1529 1530 ASTContext::TemplateOrSpecializationInfo 1531 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) { 1532 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos = 1533 TemplateOrInstantiation.find(Var); 1534 if (Pos == TemplateOrInstantiation.end()) 1535 return {}; 1536 1537 return Pos->second; 1538 } 1539 1540 void 1541 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, 1542 TemplateSpecializationKind TSK, 1543 SourceLocation PointOfInstantiation) { 1544 assert(Inst->isStaticDataMember() && "Not a static data member"); 1545 assert(Tmpl->isStaticDataMember() && "Not a static data member"); 1546 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo( 1547 Tmpl, TSK, PointOfInstantiation)); 1548 } 1549 1550 void 1551 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst, 1552 TemplateOrSpecializationInfo TSI) { 1553 assert(!TemplateOrInstantiation[Inst] && 1554 "Already noted what the variable was instantiated from"); 1555 TemplateOrInstantiation[Inst] = TSI; 1556 } 1557 1558 NamedDecl * 1559 ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) { 1560 auto Pos = InstantiatedFromUsingDecl.find(UUD); 1561 if (Pos == InstantiatedFromUsingDecl.end()) 1562 return nullptr; 1563 1564 return Pos->second; 1565 } 1566 1567 void 1568 ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) { 1569 assert((isa<UsingDecl>(Pattern) || 1570 isa<UnresolvedUsingValueDecl>(Pattern) || 1571 isa<UnresolvedUsingTypenameDecl>(Pattern)) && 1572 "pattern decl is not a using decl"); 1573 assert((isa<UsingDecl>(Inst) || 1574 isa<UnresolvedUsingValueDecl>(Inst) || 1575 isa<UnresolvedUsingTypenameDecl>(Inst)) && 1576 "instantiation did not produce a using decl"); 1577 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists"); 1578 InstantiatedFromUsingDecl[Inst] = Pattern; 1579 } 1580 1581 UsingEnumDecl * 1582 ASTContext::getInstantiatedFromUsingEnumDecl(UsingEnumDecl *UUD) { 1583 auto Pos = InstantiatedFromUsingEnumDecl.find(UUD); 1584 if (Pos == InstantiatedFromUsingEnumDecl.end()) 1585 return nullptr; 1586 1587 return Pos->second; 1588 } 1589 1590 void ASTContext::setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst, 1591 UsingEnumDecl *Pattern) { 1592 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists"); 1593 InstantiatedFromUsingEnumDecl[Inst] = Pattern; 1594 } 1595 1596 UsingShadowDecl * 1597 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) { 1598 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos 1599 = InstantiatedFromUsingShadowDecl.find(Inst); 1600 if (Pos == InstantiatedFromUsingShadowDecl.end()) 1601 return nullptr; 1602 1603 return Pos->second; 1604 } 1605 1606 void 1607 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, 1608 UsingShadowDecl *Pattern) { 1609 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists"); 1610 InstantiatedFromUsingShadowDecl[Inst] = Pattern; 1611 } 1612 1613 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) { 1614 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos 1615 = InstantiatedFromUnnamedFieldDecl.find(Field); 1616 if (Pos == InstantiatedFromUnnamedFieldDecl.end()) 1617 return nullptr; 1618 1619 return Pos->second; 1620 } 1621 1622 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, 1623 FieldDecl *Tmpl) { 1624 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed"); 1625 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed"); 1626 assert(!InstantiatedFromUnnamedFieldDecl[Inst] && 1627 "Already noted what unnamed field was instantiated from"); 1628 1629 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl; 1630 } 1631 1632 ASTContext::overridden_cxx_method_iterator 1633 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const { 1634 return overridden_methods(Method).begin(); 1635 } 1636 1637 ASTContext::overridden_cxx_method_iterator 1638 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const { 1639 return overridden_methods(Method).end(); 1640 } 1641 1642 unsigned 1643 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const { 1644 auto Range = overridden_methods(Method); 1645 return Range.end() - Range.begin(); 1646 } 1647 1648 ASTContext::overridden_method_range 1649 ASTContext::overridden_methods(const CXXMethodDecl *Method) const { 1650 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos = 1651 OverriddenMethods.find(Method->getCanonicalDecl()); 1652 if (Pos == OverriddenMethods.end()) 1653 return overridden_method_range(nullptr, nullptr); 1654 return overridden_method_range(Pos->second.begin(), Pos->second.end()); 1655 } 1656 1657 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method, 1658 const CXXMethodDecl *Overridden) { 1659 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl()); 1660 OverriddenMethods[Method].push_back(Overridden); 1661 } 1662 1663 void ASTContext::getOverriddenMethods( 1664 const NamedDecl *D, 1665 SmallVectorImpl<const NamedDecl *> &Overridden) const { 1666 assert(D); 1667 1668 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) { 1669 Overridden.append(overridden_methods_begin(CXXMethod), 1670 overridden_methods_end(CXXMethod)); 1671 return; 1672 } 1673 1674 const auto *Method = dyn_cast<ObjCMethodDecl>(D); 1675 if (!Method) 1676 return; 1677 1678 SmallVector<const ObjCMethodDecl *, 8> OverDecls; 1679 Method->getOverriddenMethods(OverDecls); 1680 Overridden.append(OverDecls.begin(), OverDecls.end()); 1681 } 1682 1683 void ASTContext::addedLocalImportDecl(ImportDecl *Import) { 1684 assert(!Import->getNextLocalImport() && 1685 "Import declaration already in the chain"); 1686 assert(!Import->isFromASTFile() && "Non-local import declaration"); 1687 if (!FirstLocalImport) { 1688 FirstLocalImport = Import; 1689 LastLocalImport = Import; 1690 return; 1691 } 1692 1693 LastLocalImport->setNextLocalImport(Import); 1694 LastLocalImport = Import; 1695 } 1696 1697 //===----------------------------------------------------------------------===// 1698 // Type Sizing and Analysis 1699 //===----------------------------------------------------------------------===// 1700 1701 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified 1702 /// scalar floating point type. 1703 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const { 1704 switch (T->castAs<BuiltinType>()->getKind()) { 1705 default: 1706 llvm_unreachable("Not a floating point type!"); 1707 case BuiltinType::BFloat16: 1708 return Target->getBFloat16Format(); 1709 case BuiltinType::Float16: 1710 case BuiltinType::Half: 1711 return Target->getHalfFormat(); 1712 case BuiltinType::Float: return Target->getFloatFormat(); 1713 case BuiltinType::Double: return Target->getDoubleFormat(); 1714 case BuiltinType::Ibm128: 1715 return Target->getIbm128Format(); 1716 case BuiltinType::LongDouble: 1717 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) 1718 return AuxTarget->getLongDoubleFormat(); 1719 return Target->getLongDoubleFormat(); 1720 case BuiltinType::Float128: 1721 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) 1722 return AuxTarget->getFloat128Format(); 1723 return Target->getFloat128Format(); 1724 } 1725 } 1726 1727 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const { 1728 unsigned Align = Target->getCharWidth(); 1729 1730 bool UseAlignAttrOnly = false; 1731 if (unsigned AlignFromAttr = D->getMaxAlignment()) { 1732 Align = AlignFromAttr; 1733 1734 // __attribute__((aligned)) can increase or decrease alignment 1735 // *except* on a struct or struct member, where it only increases 1736 // alignment unless 'packed' is also specified. 1737 // 1738 // It is an error for alignas to decrease alignment, so we can 1739 // ignore that possibility; Sema should diagnose it. 1740 if (isa<FieldDecl>(D)) { 1741 UseAlignAttrOnly = D->hasAttr<PackedAttr>() || 1742 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 1743 } else { 1744 UseAlignAttrOnly = true; 1745 } 1746 } 1747 else if (isa<FieldDecl>(D)) 1748 UseAlignAttrOnly = 1749 D->hasAttr<PackedAttr>() || 1750 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 1751 1752 // If we're using the align attribute only, just ignore everything 1753 // else about the declaration and its type. 1754 if (UseAlignAttrOnly) { 1755 // do nothing 1756 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) { 1757 QualType T = VD->getType(); 1758 if (const auto *RT = T->getAs<ReferenceType>()) { 1759 if (ForAlignof) 1760 T = RT->getPointeeType(); 1761 else 1762 T = getPointerType(RT->getPointeeType()); 1763 } 1764 QualType BaseT = getBaseElementType(T); 1765 if (T->isFunctionType()) 1766 Align = getTypeInfoImpl(T.getTypePtr()).Align; 1767 else if (!BaseT->isIncompleteType()) { 1768 // Adjust alignments of declarations with array type by the 1769 // large-array alignment on the target. 1770 if (const ArrayType *arrayType = getAsArrayType(T)) { 1771 unsigned MinWidth = Target->getLargeArrayMinWidth(); 1772 if (!ForAlignof && MinWidth) { 1773 if (isa<VariableArrayType>(arrayType)) 1774 Align = std::max(Align, Target->getLargeArrayAlign()); 1775 else if (isa<ConstantArrayType>(arrayType) && 1776 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType))) 1777 Align = std::max(Align, Target->getLargeArrayAlign()); 1778 } 1779 } 1780 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr())); 1781 if (BaseT.getQualifiers().hasUnaligned()) 1782 Align = Target->getCharWidth(); 1783 if (const auto *VD = dyn_cast<VarDecl>(D)) { 1784 if (VD->hasGlobalStorage() && !ForAlignof) { 1785 uint64_t TypeSize = getTypeSize(T.getTypePtr()); 1786 Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize)); 1787 } 1788 } 1789 } 1790 1791 // Fields can be subject to extra alignment constraints, like if 1792 // the field is packed, the struct is packed, or the struct has a 1793 // a max-field-alignment constraint (#pragma pack). So calculate 1794 // the actual alignment of the field within the struct, and then 1795 // (as we're expected to) constrain that by the alignment of the type. 1796 if (const auto *Field = dyn_cast<FieldDecl>(VD)) { 1797 const RecordDecl *Parent = Field->getParent(); 1798 // We can only produce a sensible answer if the record is valid. 1799 if (!Parent->isInvalidDecl()) { 1800 const ASTRecordLayout &Layout = getASTRecordLayout(Parent); 1801 1802 // Start with the record's overall alignment. 1803 unsigned FieldAlign = toBits(Layout.getAlignment()); 1804 1805 // Use the GCD of that and the offset within the record. 1806 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex()); 1807 if (Offset > 0) { 1808 // Alignment is always a power of 2, so the GCD will be a power of 2, 1809 // which means we get to do this crazy thing instead of Euclid's. 1810 uint64_t LowBitOfOffset = Offset & (~Offset + 1); 1811 if (LowBitOfOffset < FieldAlign) 1812 FieldAlign = static_cast<unsigned>(LowBitOfOffset); 1813 } 1814 1815 Align = std::min(Align, FieldAlign); 1816 } 1817 } 1818 } 1819 1820 // Some targets have hard limitation on the maximum requestable alignment in 1821 // aligned attribute for static variables. 1822 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute(); 1823 const auto *VD = dyn_cast<VarDecl>(D); 1824 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static) 1825 Align = std::min(Align, MaxAlignedAttr); 1826 1827 return toCharUnitsFromBits(Align); 1828 } 1829 1830 CharUnits ASTContext::getExnObjectAlignment() const { 1831 return toCharUnitsFromBits(Target->getExnObjectAlignment()); 1832 } 1833 1834 // getTypeInfoDataSizeInChars - Return the size of a type, in 1835 // chars. If the type is a record, its data size is returned. This is 1836 // the size of the memcpy that's performed when assigning this type 1837 // using a trivial copy/move assignment operator. 1838 TypeInfoChars ASTContext::getTypeInfoDataSizeInChars(QualType T) const { 1839 TypeInfoChars Info = getTypeInfoInChars(T); 1840 1841 // In C++, objects can sometimes be allocated into the tail padding 1842 // of a base-class subobject. We decide whether that's possible 1843 // during class layout, so here we can just trust the layout results. 1844 if (getLangOpts().CPlusPlus) { 1845 if (const auto *RT = T->getAs<RecordType>()) { 1846 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl()); 1847 Info.Width = layout.getDataSize(); 1848 } 1849 } 1850 1851 return Info; 1852 } 1853 1854 /// getConstantArrayInfoInChars - Performing the computation in CharUnits 1855 /// instead of in bits prevents overflowing the uint64_t for some large arrays. 1856 TypeInfoChars 1857 static getConstantArrayInfoInChars(const ASTContext &Context, 1858 const ConstantArrayType *CAT) { 1859 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType()); 1860 uint64_t Size = CAT->getSize().getZExtValue(); 1861 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <= 1862 (uint64_t)(-1)/Size) && 1863 "Overflow in array type char size evaluation"); 1864 uint64_t Width = EltInfo.Width.getQuantity() * Size; 1865 unsigned Align = EltInfo.Align.getQuantity(); 1866 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() || 1867 Context.getTargetInfo().getPointerWidth(0) == 64) 1868 Width = llvm::alignTo(Width, Align); 1869 return TypeInfoChars(CharUnits::fromQuantity(Width), 1870 CharUnits::fromQuantity(Align), 1871 EltInfo.AlignRequirement); 1872 } 1873 1874 TypeInfoChars ASTContext::getTypeInfoInChars(const Type *T) const { 1875 if (const auto *CAT = dyn_cast<ConstantArrayType>(T)) 1876 return getConstantArrayInfoInChars(*this, CAT); 1877 TypeInfo Info = getTypeInfo(T); 1878 return TypeInfoChars(toCharUnitsFromBits(Info.Width), 1879 toCharUnitsFromBits(Info.Align), Info.AlignRequirement); 1880 } 1881 1882 TypeInfoChars ASTContext::getTypeInfoInChars(QualType T) const { 1883 return getTypeInfoInChars(T.getTypePtr()); 1884 } 1885 1886 bool ASTContext::isAlignmentRequired(const Type *T) const { 1887 return getTypeInfo(T).AlignRequirement != AlignRequirementKind::None; 1888 } 1889 1890 bool ASTContext::isAlignmentRequired(QualType T) const { 1891 return isAlignmentRequired(T.getTypePtr()); 1892 } 1893 1894 unsigned ASTContext::getTypeAlignIfKnown(QualType T, 1895 bool NeedsPreferredAlignment) const { 1896 // An alignment on a typedef overrides anything else. 1897 if (const auto *TT = T->getAs<TypedefType>()) 1898 if (unsigned Align = TT->getDecl()->getMaxAlignment()) 1899 return Align; 1900 1901 // If we have an (array of) complete type, we're done. 1902 T = getBaseElementType(T); 1903 if (!T->isIncompleteType()) 1904 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T); 1905 1906 // If we had an array type, its element type might be a typedef 1907 // type with an alignment attribute. 1908 if (const auto *TT = T->getAs<TypedefType>()) 1909 if (unsigned Align = TT->getDecl()->getMaxAlignment()) 1910 return Align; 1911 1912 // Otherwise, see if the declaration of the type had an attribute. 1913 if (const auto *TT = T->getAs<TagType>()) 1914 return TT->getDecl()->getMaxAlignment(); 1915 1916 return 0; 1917 } 1918 1919 TypeInfo ASTContext::getTypeInfo(const Type *T) const { 1920 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T); 1921 if (I != MemoizedTypeInfo.end()) 1922 return I->second; 1923 1924 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup. 1925 TypeInfo TI = getTypeInfoImpl(T); 1926 MemoizedTypeInfo[T] = TI; 1927 return TI; 1928 } 1929 1930 /// getTypeInfoImpl - Return the size of the specified type, in bits. This 1931 /// method does not work on incomplete types. 1932 /// 1933 /// FIXME: Pointers into different addr spaces could have different sizes and 1934 /// alignment requirements: getPointerInfo should take an AddrSpace, this 1935 /// should take a QualType, &c. 1936 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const { 1937 uint64_t Width = 0; 1938 unsigned Align = 8; 1939 AlignRequirementKind AlignRequirement = AlignRequirementKind::None; 1940 unsigned AS = 0; 1941 switch (T->getTypeClass()) { 1942 #define TYPE(Class, Base) 1943 #define ABSTRACT_TYPE(Class, Base) 1944 #define NON_CANONICAL_TYPE(Class, Base) 1945 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 1946 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \ 1947 case Type::Class: \ 1948 assert(!T->isDependentType() && "should not see dependent types here"); \ 1949 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr()); 1950 #include "clang/AST/TypeNodes.inc" 1951 llvm_unreachable("Should not see dependent types"); 1952 1953 case Type::FunctionNoProto: 1954 case Type::FunctionProto: 1955 // GCC extension: alignof(function) = 32 bits 1956 Width = 0; 1957 Align = 32; 1958 break; 1959 1960 case Type::IncompleteArray: 1961 case Type::VariableArray: 1962 case Type::ConstantArray: { 1963 // Model non-constant sized arrays as size zero, but track the alignment. 1964 uint64_t Size = 0; 1965 if (const auto *CAT = dyn_cast<ConstantArrayType>(T)) 1966 Size = CAT->getSize().getZExtValue(); 1967 1968 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType()); 1969 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) && 1970 "Overflow in array type bit size evaluation"); 1971 Width = EltInfo.Width * Size; 1972 Align = EltInfo.Align; 1973 AlignRequirement = EltInfo.AlignRequirement; 1974 if (!getTargetInfo().getCXXABI().isMicrosoft() || 1975 getTargetInfo().getPointerWidth(0) == 64) 1976 Width = llvm::alignTo(Width, Align); 1977 break; 1978 } 1979 1980 case Type::ExtVector: 1981 case Type::Vector: { 1982 const auto *VT = cast<VectorType>(T); 1983 TypeInfo EltInfo = getTypeInfo(VT->getElementType()); 1984 Width = VT->isExtVectorBoolType() ? VT->getNumElements() 1985 : EltInfo.Width * VT->getNumElements(); 1986 // Enforce at least byte alignment. 1987 Align = std::max<unsigned>(8, Width); 1988 1989 // If the alignment is not a power of 2, round up to the next power of 2. 1990 // This happens for non-power-of-2 length vectors. 1991 if (Align & (Align-1)) { 1992 Align = llvm::NextPowerOf2(Align); 1993 Width = llvm::alignTo(Width, Align); 1994 } 1995 // Adjust the alignment based on the target max. 1996 uint64_t TargetVectorAlign = Target->getMaxVectorAlign(); 1997 if (TargetVectorAlign && TargetVectorAlign < Align) 1998 Align = TargetVectorAlign; 1999 if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) 2000 // Adjust the alignment for fixed-length SVE vectors. This is important 2001 // for non-power-of-2 vector lengths. 2002 Align = 128; 2003 else if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 2004 // Adjust the alignment for fixed-length SVE predicates. 2005 Align = 16; 2006 break; 2007 } 2008 2009 case Type::ConstantMatrix: { 2010 const auto *MT = cast<ConstantMatrixType>(T); 2011 TypeInfo ElementInfo = getTypeInfo(MT->getElementType()); 2012 // The internal layout of a matrix value is implementation defined. 2013 // Initially be ABI compatible with arrays with respect to alignment and 2014 // size. 2015 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns(); 2016 Align = ElementInfo.Align; 2017 break; 2018 } 2019 2020 case Type::Builtin: 2021 switch (cast<BuiltinType>(T)->getKind()) { 2022 default: llvm_unreachable("Unknown builtin type!"); 2023 case BuiltinType::Void: 2024 // GCC extension: alignof(void) = 8 bits. 2025 Width = 0; 2026 Align = 8; 2027 break; 2028 case BuiltinType::Bool: 2029 Width = Target->getBoolWidth(); 2030 Align = Target->getBoolAlign(); 2031 break; 2032 case BuiltinType::Char_S: 2033 case BuiltinType::Char_U: 2034 case BuiltinType::UChar: 2035 case BuiltinType::SChar: 2036 case BuiltinType::Char8: 2037 Width = Target->getCharWidth(); 2038 Align = Target->getCharAlign(); 2039 break; 2040 case BuiltinType::WChar_S: 2041 case BuiltinType::WChar_U: 2042 Width = Target->getWCharWidth(); 2043 Align = Target->getWCharAlign(); 2044 break; 2045 case BuiltinType::Char16: 2046 Width = Target->getChar16Width(); 2047 Align = Target->getChar16Align(); 2048 break; 2049 case BuiltinType::Char32: 2050 Width = Target->getChar32Width(); 2051 Align = Target->getChar32Align(); 2052 break; 2053 case BuiltinType::UShort: 2054 case BuiltinType::Short: 2055 Width = Target->getShortWidth(); 2056 Align = Target->getShortAlign(); 2057 break; 2058 case BuiltinType::UInt: 2059 case BuiltinType::Int: 2060 Width = Target->getIntWidth(); 2061 Align = Target->getIntAlign(); 2062 break; 2063 case BuiltinType::ULong: 2064 case BuiltinType::Long: 2065 Width = Target->getLongWidth(); 2066 Align = Target->getLongAlign(); 2067 break; 2068 case BuiltinType::ULongLong: 2069 case BuiltinType::LongLong: 2070 Width = Target->getLongLongWidth(); 2071 Align = Target->getLongLongAlign(); 2072 break; 2073 case BuiltinType::Int128: 2074 case BuiltinType::UInt128: 2075 Width = 128; 2076 Align = 128; // int128_t is 128-bit aligned on all targets. 2077 break; 2078 case BuiltinType::ShortAccum: 2079 case BuiltinType::UShortAccum: 2080 case BuiltinType::SatShortAccum: 2081 case BuiltinType::SatUShortAccum: 2082 Width = Target->getShortAccumWidth(); 2083 Align = Target->getShortAccumAlign(); 2084 break; 2085 case BuiltinType::Accum: 2086 case BuiltinType::UAccum: 2087 case BuiltinType::SatAccum: 2088 case BuiltinType::SatUAccum: 2089 Width = Target->getAccumWidth(); 2090 Align = Target->getAccumAlign(); 2091 break; 2092 case BuiltinType::LongAccum: 2093 case BuiltinType::ULongAccum: 2094 case BuiltinType::SatLongAccum: 2095 case BuiltinType::SatULongAccum: 2096 Width = Target->getLongAccumWidth(); 2097 Align = Target->getLongAccumAlign(); 2098 break; 2099 case BuiltinType::ShortFract: 2100 case BuiltinType::UShortFract: 2101 case BuiltinType::SatShortFract: 2102 case BuiltinType::SatUShortFract: 2103 Width = Target->getShortFractWidth(); 2104 Align = Target->getShortFractAlign(); 2105 break; 2106 case BuiltinType::Fract: 2107 case BuiltinType::UFract: 2108 case BuiltinType::SatFract: 2109 case BuiltinType::SatUFract: 2110 Width = Target->getFractWidth(); 2111 Align = Target->getFractAlign(); 2112 break; 2113 case BuiltinType::LongFract: 2114 case BuiltinType::ULongFract: 2115 case BuiltinType::SatLongFract: 2116 case BuiltinType::SatULongFract: 2117 Width = Target->getLongFractWidth(); 2118 Align = Target->getLongFractAlign(); 2119 break; 2120 case BuiltinType::BFloat16: 2121 if (Target->hasBFloat16Type()) { 2122 Width = Target->getBFloat16Width(); 2123 Align = Target->getBFloat16Align(); 2124 } 2125 break; 2126 case BuiltinType::Float16: 2127 case BuiltinType::Half: 2128 if (Target->hasFloat16Type() || !getLangOpts().OpenMP || 2129 !getLangOpts().OpenMPIsDevice) { 2130 Width = Target->getHalfWidth(); 2131 Align = Target->getHalfAlign(); 2132 } else { 2133 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 2134 "Expected OpenMP device compilation."); 2135 Width = AuxTarget->getHalfWidth(); 2136 Align = AuxTarget->getHalfAlign(); 2137 } 2138 break; 2139 case BuiltinType::Float: 2140 Width = Target->getFloatWidth(); 2141 Align = Target->getFloatAlign(); 2142 break; 2143 case BuiltinType::Double: 2144 Width = Target->getDoubleWidth(); 2145 Align = Target->getDoubleAlign(); 2146 break; 2147 case BuiltinType::Ibm128: 2148 Width = Target->getIbm128Width(); 2149 Align = Target->getIbm128Align(); 2150 break; 2151 case BuiltinType::LongDouble: 2152 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 2153 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() || 2154 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) { 2155 Width = AuxTarget->getLongDoubleWidth(); 2156 Align = AuxTarget->getLongDoubleAlign(); 2157 } else { 2158 Width = Target->getLongDoubleWidth(); 2159 Align = Target->getLongDoubleAlign(); 2160 } 2161 break; 2162 case BuiltinType::Float128: 2163 if (Target->hasFloat128Type() || !getLangOpts().OpenMP || 2164 !getLangOpts().OpenMPIsDevice) { 2165 Width = Target->getFloat128Width(); 2166 Align = Target->getFloat128Align(); 2167 } else { 2168 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 2169 "Expected OpenMP device compilation."); 2170 Width = AuxTarget->getFloat128Width(); 2171 Align = AuxTarget->getFloat128Align(); 2172 } 2173 break; 2174 case BuiltinType::NullPtr: 2175 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t) 2176 Align = Target->getPointerAlign(0); // == sizeof(void*) 2177 break; 2178 case BuiltinType::ObjCId: 2179 case BuiltinType::ObjCClass: 2180 case BuiltinType::ObjCSel: 2181 Width = Target->getPointerWidth(0); 2182 Align = Target->getPointerAlign(0); 2183 break; 2184 case BuiltinType::OCLSampler: 2185 case BuiltinType::OCLEvent: 2186 case BuiltinType::OCLClkEvent: 2187 case BuiltinType::OCLQueue: 2188 case BuiltinType::OCLReserveID: 2189 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 2190 case BuiltinType::Id: 2191 #include "clang/Basic/OpenCLImageTypes.def" 2192 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 2193 case BuiltinType::Id: 2194 #include "clang/Basic/OpenCLExtensionTypes.def" 2195 AS = getTargetAddressSpace( 2196 Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T))); 2197 Width = Target->getPointerWidth(AS); 2198 Align = Target->getPointerAlign(AS); 2199 break; 2200 // The SVE types are effectively target-specific. The length of an 2201 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple 2202 // of 128 bits. There is one predicate bit for each vector byte, so the 2203 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits. 2204 // 2205 // Because the length is only known at runtime, we use a dummy value 2206 // of 0 for the static length. The alignment values are those defined 2207 // by the Procedure Call Standard for the Arm Architecture. 2208 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \ 2209 IsSigned, IsFP, IsBF) \ 2210 case BuiltinType::Id: \ 2211 Width = 0; \ 2212 Align = 128; \ 2213 break; 2214 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \ 2215 case BuiltinType::Id: \ 2216 Width = 0; \ 2217 Align = 16; \ 2218 break; 2219 #include "clang/Basic/AArch64SVEACLETypes.def" 2220 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 2221 case BuiltinType::Id: \ 2222 Width = Size; \ 2223 Align = Size; \ 2224 break; 2225 #include "clang/Basic/PPCTypes.def" 2226 #define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \ 2227 IsFP) \ 2228 case BuiltinType::Id: \ 2229 Width = 0; \ 2230 Align = ElBits; \ 2231 break; 2232 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \ 2233 case BuiltinType::Id: \ 2234 Width = 0; \ 2235 Align = 8; \ 2236 break; 2237 #include "clang/Basic/RISCVVTypes.def" 2238 } 2239 break; 2240 case Type::ObjCObjectPointer: 2241 Width = Target->getPointerWidth(0); 2242 Align = Target->getPointerAlign(0); 2243 break; 2244 case Type::BlockPointer: 2245 AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType()); 2246 Width = Target->getPointerWidth(AS); 2247 Align = Target->getPointerAlign(AS); 2248 break; 2249 case Type::LValueReference: 2250 case Type::RValueReference: 2251 // alignof and sizeof should never enter this code path here, so we go 2252 // the pointer route. 2253 AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType()); 2254 Width = Target->getPointerWidth(AS); 2255 Align = Target->getPointerAlign(AS); 2256 break; 2257 case Type::Pointer: 2258 AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType()); 2259 Width = Target->getPointerWidth(AS); 2260 Align = Target->getPointerAlign(AS); 2261 break; 2262 case Type::MemberPointer: { 2263 const auto *MPT = cast<MemberPointerType>(T); 2264 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT); 2265 Width = MPI.Width; 2266 Align = MPI.Align; 2267 break; 2268 } 2269 case Type::Complex: { 2270 // Complex types have the same alignment as their elements, but twice the 2271 // size. 2272 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType()); 2273 Width = EltInfo.Width * 2; 2274 Align = EltInfo.Align; 2275 break; 2276 } 2277 case Type::ObjCObject: 2278 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr()); 2279 case Type::Adjusted: 2280 case Type::Decayed: 2281 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr()); 2282 case Type::ObjCInterface: { 2283 const auto *ObjCI = cast<ObjCInterfaceType>(T); 2284 if (ObjCI->getDecl()->isInvalidDecl()) { 2285 Width = 8; 2286 Align = 8; 2287 break; 2288 } 2289 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 2290 Width = toBits(Layout.getSize()); 2291 Align = toBits(Layout.getAlignment()); 2292 break; 2293 } 2294 case Type::BitInt: { 2295 const auto *EIT = cast<BitIntType>(T); 2296 Align = 2297 std::min(static_cast<unsigned>(std::max( 2298 getCharWidth(), llvm::PowerOf2Ceil(EIT->getNumBits()))), 2299 Target->getLongLongAlign()); 2300 Width = llvm::alignTo(EIT->getNumBits(), Align); 2301 break; 2302 } 2303 case Type::Record: 2304 case Type::Enum: { 2305 const auto *TT = cast<TagType>(T); 2306 2307 if (TT->getDecl()->isInvalidDecl()) { 2308 Width = 8; 2309 Align = 8; 2310 break; 2311 } 2312 2313 if (const auto *ET = dyn_cast<EnumType>(TT)) { 2314 const EnumDecl *ED = ET->getDecl(); 2315 TypeInfo Info = 2316 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType()); 2317 if (unsigned AttrAlign = ED->getMaxAlignment()) { 2318 Info.Align = AttrAlign; 2319 Info.AlignRequirement = AlignRequirementKind::RequiredByEnum; 2320 } 2321 return Info; 2322 } 2323 2324 const auto *RT = cast<RecordType>(TT); 2325 const RecordDecl *RD = RT->getDecl(); 2326 const ASTRecordLayout &Layout = getASTRecordLayout(RD); 2327 Width = toBits(Layout.getSize()); 2328 Align = toBits(Layout.getAlignment()); 2329 AlignRequirement = RD->hasAttr<AlignedAttr>() 2330 ? AlignRequirementKind::RequiredByRecord 2331 : AlignRequirementKind::None; 2332 break; 2333 } 2334 2335 case Type::SubstTemplateTypeParm: 2336 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)-> 2337 getReplacementType().getTypePtr()); 2338 2339 case Type::Auto: 2340 case Type::DeducedTemplateSpecialization: { 2341 const auto *A = cast<DeducedType>(T); 2342 assert(!A->getDeducedType().isNull() && 2343 "cannot request the size of an undeduced or dependent auto type"); 2344 return getTypeInfo(A->getDeducedType().getTypePtr()); 2345 } 2346 2347 case Type::Paren: 2348 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr()); 2349 2350 case Type::MacroQualified: 2351 return getTypeInfo( 2352 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr()); 2353 2354 case Type::ObjCTypeParam: 2355 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr()); 2356 2357 case Type::Using: 2358 return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr()); 2359 2360 case Type::Typedef: { 2361 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl(); 2362 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr()); 2363 // If the typedef has an aligned attribute on it, it overrides any computed 2364 // alignment we have. This violates the GCC documentation (which says that 2365 // attribute(aligned) can only round up) but matches its implementation. 2366 if (unsigned AttrAlign = Typedef->getMaxAlignment()) { 2367 Align = AttrAlign; 2368 AlignRequirement = AlignRequirementKind::RequiredByTypedef; 2369 } else { 2370 Align = Info.Align; 2371 AlignRequirement = Info.AlignRequirement; 2372 } 2373 Width = Info.Width; 2374 break; 2375 } 2376 2377 case Type::Elaborated: 2378 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr()); 2379 2380 case Type::Attributed: 2381 return getTypeInfo( 2382 cast<AttributedType>(T)->getEquivalentType().getTypePtr()); 2383 2384 case Type::BTFTagAttributed: 2385 return getTypeInfo( 2386 cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr()); 2387 2388 case Type::Atomic: { 2389 // Start with the base type information. 2390 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType()); 2391 Width = Info.Width; 2392 Align = Info.Align; 2393 2394 if (!Width) { 2395 // An otherwise zero-sized type should still generate an 2396 // atomic operation. 2397 Width = Target->getCharWidth(); 2398 assert(Align); 2399 } else if (Width <= Target->getMaxAtomicPromoteWidth()) { 2400 // If the size of the type doesn't exceed the platform's max 2401 // atomic promotion width, make the size and alignment more 2402 // favorable to atomic operations: 2403 2404 // Round the size up to a power of 2. 2405 if (!llvm::isPowerOf2_64(Width)) 2406 Width = llvm::NextPowerOf2(Width); 2407 2408 // Set the alignment equal to the size. 2409 Align = static_cast<unsigned>(Width); 2410 } 2411 } 2412 break; 2413 2414 case Type::Pipe: 2415 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global)); 2416 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global)); 2417 break; 2418 } 2419 2420 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2"); 2421 return TypeInfo(Width, Align, AlignRequirement); 2422 } 2423 2424 unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const { 2425 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T); 2426 if (I != MemoizedUnadjustedAlign.end()) 2427 return I->second; 2428 2429 unsigned UnadjustedAlign; 2430 if (const auto *RT = T->getAs<RecordType>()) { 2431 const RecordDecl *RD = RT->getDecl(); 2432 const ASTRecordLayout &Layout = getASTRecordLayout(RD); 2433 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment()); 2434 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) { 2435 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 2436 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment()); 2437 } else { 2438 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType()); 2439 } 2440 2441 MemoizedUnadjustedAlign[T] = UnadjustedAlign; 2442 return UnadjustedAlign; 2443 } 2444 2445 unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const { 2446 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign(); 2447 return SimdAlign; 2448 } 2449 2450 /// toCharUnitsFromBits - Convert a size in bits to a size in characters. 2451 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const { 2452 return CharUnits::fromQuantity(BitSize / getCharWidth()); 2453 } 2454 2455 /// toBits - Convert a size in characters to a size in characters. 2456 int64_t ASTContext::toBits(CharUnits CharSize) const { 2457 return CharSize.getQuantity() * getCharWidth(); 2458 } 2459 2460 /// getTypeSizeInChars - Return the size of the specified type, in characters. 2461 /// This method does not work on incomplete types. 2462 CharUnits ASTContext::getTypeSizeInChars(QualType T) const { 2463 return getTypeInfoInChars(T).Width; 2464 } 2465 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const { 2466 return getTypeInfoInChars(T).Width; 2467 } 2468 2469 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in 2470 /// characters. This method does not work on incomplete types. 2471 CharUnits ASTContext::getTypeAlignInChars(QualType T) const { 2472 return toCharUnitsFromBits(getTypeAlign(T)); 2473 } 2474 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const { 2475 return toCharUnitsFromBits(getTypeAlign(T)); 2476 } 2477 2478 /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a 2479 /// type, in characters, before alignment adustments. This method does 2480 /// not work on incomplete types. 2481 CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const { 2482 return toCharUnitsFromBits(getTypeUnadjustedAlign(T)); 2483 } 2484 CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const { 2485 return toCharUnitsFromBits(getTypeUnadjustedAlign(T)); 2486 } 2487 2488 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified 2489 /// type for the current target in bits. This can be different than the ABI 2490 /// alignment in cases where it is beneficial for performance or backwards 2491 /// compatibility preserving to overalign a data type. (Note: despite the name, 2492 /// the preferred alignment is ABI-impacting, and not an optimization.) 2493 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const { 2494 TypeInfo TI = getTypeInfo(T); 2495 unsigned ABIAlign = TI.Align; 2496 2497 T = T->getBaseElementTypeUnsafe(); 2498 2499 // The preferred alignment of member pointers is that of a pointer. 2500 if (T->isMemberPointerType()) 2501 return getPreferredTypeAlign(getPointerDiffType().getTypePtr()); 2502 2503 if (!Target->allowsLargerPreferedTypeAlignment()) 2504 return ABIAlign; 2505 2506 if (const auto *RT = T->getAs<RecordType>()) { 2507 const RecordDecl *RD = RT->getDecl(); 2508 2509 // When used as part of a typedef, or together with a 'packed' attribute, 2510 // the 'aligned' attribute can be used to decrease alignment. Note that the 2511 // 'packed' case is already taken into consideration when computing the 2512 // alignment, we only need to handle the typedef case here. 2513 if (TI.AlignRequirement == AlignRequirementKind::RequiredByTypedef || 2514 RD->isInvalidDecl()) 2515 return ABIAlign; 2516 2517 unsigned PreferredAlign = static_cast<unsigned>( 2518 toBits(getASTRecordLayout(RD).PreferredAlignment)); 2519 assert(PreferredAlign >= ABIAlign && 2520 "PreferredAlign should be at least as large as ABIAlign."); 2521 return PreferredAlign; 2522 } 2523 2524 // Double (and, for targets supporting AIX `power` alignment, long double) and 2525 // long long should be naturally aligned (despite requiring less alignment) if 2526 // possible. 2527 if (const auto *CT = T->getAs<ComplexType>()) 2528 T = CT->getElementType().getTypePtr(); 2529 if (const auto *ET = T->getAs<EnumType>()) 2530 T = ET->getDecl()->getIntegerType().getTypePtr(); 2531 if (T->isSpecificBuiltinType(BuiltinType::Double) || 2532 T->isSpecificBuiltinType(BuiltinType::LongLong) || 2533 T->isSpecificBuiltinType(BuiltinType::ULongLong) || 2534 (T->isSpecificBuiltinType(BuiltinType::LongDouble) && 2535 Target->defaultsToAIXPowerAlignment())) 2536 // Don't increase the alignment if an alignment attribute was specified on a 2537 // typedef declaration. 2538 if (!TI.isAlignRequired()) 2539 return std::max(ABIAlign, (unsigned)getTypeSize(T)); 2540 2541 return ABIAlign; 2542 } 2543 2544 /// getTargetDefaultAlignForAttributeAligned - Return the default alignment 2545 /// for __attribute__((aligned)) on this target, to be used if no alignment 2546 /// value is specified. 2547 unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const { 2548 return getTargetInfo().getDefaultAlignForAttributeAligned(); 2549 } 2550 2551 /// getAlignOfGlobalVar - Return the alignment in bits that should be given 2552 /// to a global variable of the specified type. 2553 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const { 2554 uint64_t TypeSize = getTypeSize(T.getTypePtr()); 2555 return std::max(getPreferredTypeAlign(T), 2556 getTargetInfo().getMinGlobalAlign(TypeSize)); 2557 } 2558 2559 /// getAlignOfGlobalVarInChars - Return the alignment in characters that 2560 /// should be given to a global variable of the specified type. 2561 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const { 2562 return toCharUnitsFromBits(getAlignOfGlobalVar(T)); 2563 } 2564 2565 CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const { 2566 CharUnits Offset = CharUnits::Zero(); 2567 const ASTRecordLayout *Layout = &getASTRecordLayout(RD); 2568 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) { 2569 Offset += Layout->getBaseClassOffset(Base); 2570 Layout = &getASTRecordLayout(Base); 2571 } 2572 return Offset; 2573 } 2574 2575 CharUnits ASTContext::getMemberPointerPathAdjustment(const APValue &MP) const { 2576 const ValueDecl *MPD = MP.getMemberPointerDecl(); 2577 CharUnits ThisAdjustment = CharUnits::Zero(); 2578 ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath(); 2579 bool DerivedMember = MP.isMemberPointerToDerivedMember(); 2580 const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext()); 2581 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 2582 const CXXRecordDecl *Base = RD; 2583 const CXXRecordDecl *Derived = Path[I]; 2584 if (DerivedMember) 2585 std::swap(Base, Derived); 2586 ThisAdjustment += getASTRecordLayout(Derived).getBaseClassOffset(Base); 2587 RD = Path[I]; 2588 } 2589 if (DerivedMember) 2590 ThisAdjustment = -ThisAdjustment; 2591 return ThisAdjustment; 2592 } 2593 2594 /// DeepCollectObjCIvars - 2595 /// This routine first collects all declared, but not synthesized, ivars in 2596 /// super class and then collects all ivars, including those synthesized for 2597 /// current class. This routine is used for implementation of current class 2598 /// when all ivars, declared and synthesized are known. 2599 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, 2600 bool leafClass, 2601 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const { 2602 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass()) 2603 DeepCollectObjCIvars(SuperClass, false, Ivars); 2604 if (!leafClass) { 2605 llvm::append_range(Ivars, OI->ivars()); 2606 } else { 2607 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI); 2608 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv; 2609 Iv= Iv->getNextIvar()) 2610 Ivars.push_back(Iv); 2611 } 2612 } 2613 2614 /// CollectInheritedProtocols - Collect all protocols in current class and 2615 /// those inherited by it. 2616 void ASTContext::CollectInheritedProtocols(const Decl *CDecl, 2617 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) { 2618 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) { 2619 // We can use protocol_iterator here instead of 2620 // all_referenced_protocol_iterator since we are walking all categories. 2621 for (auto *Proto : OI->all_referenced_protocols()) { 2622 CollectInheritedProtocols(Proto, Protocols); 2623 } 2624 2625 // Categories of this Interface. 2626 for (const auto *Cat : OI->visible_categories()) 2627 CollectInheritedProtocols(Cat, Protocols); 2628 2629 if (ObjCInterfaceDecl *SD = OI->getSuperClass()) 2630 while (SD) { 2631 CollectInheritedProtocols(SD, Protocols); 2632 SD = SD->getSuperClass(); 2633 } 2634 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) { 2635 for (auto *Proto : OC->protocols()) { 2636 CollectInheritedProtocols(Proto, Protocols); 2637 } 2638 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) { 2639 // Insert the protocol. 2640 if (!Protocols.insert( 2641 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second) 2642 return; 2643 2644 for (auto *Proto : OP->protocols()) 2645 CollectInheritedProtocols(Proto, Protocols); 2646 } 2647 } 2648 2649 static bool unionHasUniqueObjectRepresentations(const ASTContext &Context, 2650 const RecordDecl *RD) { 2651 assert(RD->isUnion() && "Must be union type"); 2652 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl()); 2653 2654 for (const auto *Field : RD->fields()) { 2655 if (!Context.hasUniqueObjectRepresentations(Field->getType())) 2656 return false; 2657 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType()); 2658 if (FieldSize != UnionSize) 2659 return false; 2660 } 2661 return !RD->field_empty(); 2662 } 2663 2664 static int64_t getSubobjectOffset(const FieldDecl *Field, 2665 const ASTContext &Context, 2666 const clang::ASTRecordLayout & /*Layout*/) { 2667 return Context.getFieldOffset(Field); 2668 } 2669 2670 static int64_t getSubobjectOffset(const CXXRecordDecl *RD, 2671 const ASTContext &Context, 2672 const clang::ASTRecordLayout &Layout) { 2673 return Context.toBits(Layout.getBaseClassOffset(RD)); 2674 } 2675 2676 static llvm::Optional<int64_t> 2677 structHasUniqueObjectRepresentations(const ASTContext &Context, 2678 const RecordDecl *RD); 2679 2680 static llvm::Optional<int64_t> 2681 getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context) { 2682 if (Field->getType()->isRecordType()) { 2683 const RecordDecl *RD = Field->getType()->getAsRecordDecl(); 2684 if (!RD->isUnion()) 2685 return structHasUniqueObjectRepresentations(Context, RD); 2686 } 2687 2688 // A _BitInt type may not be unique if it has padding bits 2689 // but if it is a bitfield the padding bits are not used. 2690 bool IsBitIntType = Field->getType()->isBitIntType(); 2691 if (!Field->getType()->isReferenceType() && !IsBitIntType && 2692 !Context.hasUniqueObjectRepresentations(Field->getType())) 2693 return llvm::None; 2694 2695 int64_t FieldSizeInBits = 2696 Context.toBits(Context.getTypeSizeInChars(Field->getType())); 2697 if (Field->isBitField()) { 2698 int64_t BitfieldSize = Field->getBitWidthValue(Context); 2699 if (IsBitIntType) { 2700 if ((unsigned)BitfieldSize > 2701 cast<BitIntType>(Field->getType())->getNumBits()) 2702 return llvm::None; 2703 } else if (BitfieldSize > FieldSizeInBits) { 2704 return llvm::None; 2705 } 2706 FieldSizeInBits = BitfieldSize; 2707 } else if (IsBitIntType && 2708 !Context.hasUniqueObjectRepresentations(Field->getType())) { 2709 return llvm::None; 2710 } 2711 return FieldSizeInBits; 2712 } 2713 2714 static llvm::Optional<int64_t> 2715 getSubobjectSizeInBits(const CXXRecordDecl *RD, const ASTContext &Context) { 2716 return structHasUniqueObjectRepresentations(Context, RD); 2717 } 2718 2719 template <typename RangeT> 2720 static llvm::Optional<int64_t> structSubobjectsHaveUniqueObjectRepresentations( 2721 const RangeT &Subobjects, int64_t CurOffsetInBits, 2722 const ASTContext &Context, const clang::ASTRecordLayout &Layout) { 2723 for (const auto *Subobject : Subobjects) { 2724 llvm::Optional<int64_t> SizeInBits = 2725 getSubobjectSizeInBits(Subobject, Context); 2726 if (!SizeInBits) 2727 return llvm::None; 2728 if (*SizeInBits != 0) { 2729 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout); 2730 if (Offset != CurOffsetInBits) 2731 return llvm::None; 2732 CurOffsetInBits += *SizeInBits; 2733 } 2734 } 2735 return CurOffsetInBits; 2736 } 2737 2738 static llvm::Optional<int64_t> 2739 structHasUniqueObjectRepresentations(const ASTContext &Context, 2740 const RecordDecl *RD) { 2741 assert(!RD->isUnion() && "Must be struct/class type"); 2742 const auto &Layout = Context.getASTRecordLayout(RD); 2743 2744 int64_t CurOffsetInBits = 0; 2745 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) { 2746 if (ClassDecl->isDynamicClass()) 2747 return llvm::None; 2748 2749 SmallVector<CXXRecordDecl *, 4> Bases; 2750 for (const auto &Base : ClassDecl->bases()) { 2751 // Empty types can be inherited from, and non-empty types can potentially 2752 // have tail padding, so just make sure there isn't an error. 2753 Bases.emplace_back(Base.getType()->getAsCXXRecordDecl()); 2754 } 2755 2756 llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) { 2757 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R); 2758 }); 2759 2760 llvm::Optional<int64_t> OffsetAfterBases = 2761 structSubobjectsHaveUniqueObjectRepresentations(Bases, CurOffsetInBits, 2762 Context, Layout); 2763 if (!OffsetAfterBases) 2764 return llvm::None; 2765 CurOffsetInBits = *OffsetAfterBases; 2766 } 2767 2768 llvm::Optional<int64_t> OffsetAfterFields = 2769 structSubobjectsHaveUniqueObjectRepresentations( 2770 RD->fields(), CurOffsetInBits, Context, Layout); 2771 if (!OffsetAfterFields) 2772 return llvm::None; 2773 CurOffsetInBits = *OffsetAfterFields; 2774 2775 return CurOffsetInBits; 2776 } 2777 2778 bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const { 2779 // C++17 [meta.unary.prop]: 2780 // The predicate condition for a template specialization 2781 // has_unique_object_representations<T> shall be 2782 // satisfied if and only if: 2783 // (9.1) - T is trivially copyable, and 2784 // (9.2) - any two objects of type T with the same value have the same 2785 // object representation, where two objects 2786 // of array or non-union class type are considered to have the same value 2787 // if their respective sequences of 2788 // direct subobjects have the same values, and two objects of union type 2789 // are considered to have the same 2790 // value if they have the same active member and the corresponding members 2791 // have the same value. 2792 // The set of scalar types for which this condition holds is 2793 // implementation-defined. [ Note: If a type has padding 2794 // bits, the condition does not hold; otherwise, the condition holds true 2795 // for unsigned integral types. -- end note ] 2796 assert(!Ty.isNull() && "Null QualType sent to unique object rep check"); 2797 2798 // Arrays are unique only if their element type is unique. 2799 if (Ty->isArrayType()) 2800 return hasUniqueObjectRepresentations(getBaseElementType(Ty)); 2801 2802 // (9.1) - T is trivially copyable... 2803 if (!Ty.isTriviallyCopyableType(*this)) 2804 return false; 2805 2806 // All integrals and enums are unique. 2807 if (Ty->isIntegralOrEnumerationType()) { 2808 // Except _BitInt types that have padding bits. 2809 if (const auto *BIT = dyn_cast<BitIntType>(Ty)) 2810 return getTypeSize(BIT) == BIT->getNumBits(); 2811 2812 return true; 2813 } 2814 2815 // All other pointers are unique. 2816 if (Ty->isPointerType()) 2817 return true; 2818 2819 if (Ty->isMemberPointerType()) { 2820 const auto *MPT = Ty->getAs<MemberPointerType>(); 2821 return !ABI->getMemberPointerInfo(MPT).HasPadding; 2822 } 2823 2824 if (Ty->isRecordType()) { 2825 const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl(); 2826 2827 if (Record->isInvalidDecl()) 2828 return false; 2829 2830 if (Record->isUnion()) 2831 return unionHasUniqueObjectRepresentations(*this, Record); 2832 2833 Optional<int64_t> StructSize = 2834 structHasUniqueObjectRepresentations(*this, Record); 2835 2836 return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(Ty)); 2837 } 2838 2839 // FIXME: More cases to handle here (list by rsmith): 2840 // vectors (careful about, eg, vector of 3 foo) 2841 // _Complex int and friends 2842 // _Atomic T 2843 // Obj-C block pointers 2844 // Obj-C object pointers 2845 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t, 2846 // clk_event_t, queue_t, reserve_id_t) 2847 // There're also Obj-C class types and the Obj-C selector type, but I think it 2848 // makes sense for those to return false here. 2849 2850 return false; 2851 } 2852 2853 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const { 2854 unsigned count = 0; 2855 // Count ivars declared in class extension. 2856 for (const auto *Ext : OI->known_extensions()) 2857 count += Ext->ivar_size(); 2858 2859 // Count ivar defined in this class's implementation. This 2860 // includes synthesized ivars. 2861 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) 2862 count += ImplDecl->ivar_size(); 2863 2864 return count; 2865 } 2866 2867 bool ASTContext::isSentinelNullExpr(const Expr *E) { 2868 if (!E) 2869 return false; 2870 2871 // nullptr_t is always treated as null. 2872 if (E->getType()->isNullPtrType()) return true; 2873 2874 if (E->getType()->isAnyPointerType() && 2875 E->IgnoreParenCasts()->isNullPointerConstant(*this, 2876 Expr::NPC_ValueDependentIsNull)) 2877 return true; 2878 2879 // Unfortunately, __null has type 'int'. 2880 if (isa<GNUNullExpr>(E)) return true; 2881 2882 return false; 2883 } 2884 2885 /// Get the implementation of ObjCInterfaceDecl, or nullptr if none 2886 /// exists. 2887 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) { 2888 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 2889 I = ObjCImpls.find(D); 2890 if (I != ObjCImpls.end()) 2891 return cast<ObjCImplementationDecl>(I->second); 2892 return nullptr; 2893 } 2894 2895 /// Get the implementation of ObjCCategoryDecl, or nullptr if none 2896 /// exists. 2897 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) { 2898 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 2899 I = ObjCImpls.find(D); 2900 if (I != ObjCImpls.end()) 2901 return cast<ObjCCategoryImplDecl>(I->second); 2902 return nullptr; 2903 } 2904 2905 /// Set the implementation of ObjCInterfaceDecl. 2906 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD, 2907 ObjCImplementationDecl *ImplD) { 2908 assert(IFaceD && ImplD && "Passed null params"); 2909 ObjCImpls[IFaceD] = ImplD; 2910 } 2911 2912 /// Set the implementation of ObjCCategoryDecl. 2913 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD, 2914 ObjCCategoryImplDecl *ImplD) { 2915 assert(CatD && ImplD && "Passed null params"); 2916 ObjCImpls[CatD] = ImplD; 2917 } 2918 2919 const ObjCMethodDecl * 2920 ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const { 2921 return ObjCMethodRedecls.lookup(MD); 2922 } 2923 2924 void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD, 2925 const ObjCMethodDecl *Redecl) { 2926 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration"); 2927 ObjCMethodRedecls[MD] = Redecl; 2928 } 2929 2930 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface( 2931 const NamedDecl *ND) const { 2932 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext())) 2933 return ID; 2934 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext())) 2935 return CD->getClassInterface(); 2936 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext())) 2937 return IMD->getClassInterface(); 2938 2939 return nullptr; 2940 } 2941 2942 /// Get the copy initialization expression of VarDecl, or nullptr if 2943 /// none exists. 2944 BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const { 2945 assert(VD && "Passed null params"); 2946 assert(VD->hasAttr<BlocksAttr>() && 2947 "getBlockVarCopyInits - not __block var"); 2948 auto I = BlockVarCopyInits.find(VD); 2949 if (I != BlockVarCopyInits.end()) 2950 return I->second; 2951 return {nullptr, false}; 2952 } 2953 2954 /// Set the copy initialization expression of a block var decl. 2955 void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr, 2956 bool CanThrow) { 2957 assert(VD && CopyExpr && "Passed null params"); 2958 assert(VD->hasAttr<BlocksAttr>() && 2959 "setBlockVarCopyInits - not __block var"); 2960 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow); 2961 } 2962 2963 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T, 2964 unsigned DataSize) const { 2965 if (!DataSize) 2966 DataSize = TypeLoc::getFullDataSizeForType(T); 2967 else 2968 assert(DataSize == TypeLoc::getFullDataSizeForType(T) && 2969 "incorrect data size provided to CreateTypeSourceInfo!"); 2970 2971 auto *TInfo = 2972 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8); 2973 new (TInfo) TypeSourceInfo(T); 2974 return TInfo; 2975 } 2976 2977 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T, 2978 SourceLocation L) const { 2979 TypeSourceInfo *DI = CreateTypeSourceInfo(T); 2980 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L); 2981 return DI; 2982 } 2983 2984 const ASTRecordLayout & 2985 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const { 2986 return getObjCLayout(D, nullptr); 2987 } 2988 2989 const ASTRecordLayout & 2990 ASTContext::getASTObjCImplementationLayout( 2991 const ObjCImplementationDecl *D) const { 2992 return getObjCLayout(D->getClassInterface(), D); 2993 } 2994 2995 //===----------------------------------------------------------------------===// 2996 // Type creation/memoization methods 2997 //===----------------------------------------------------------------------===// 2998 2999 QualType 3000 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const { 3001 unsigned fastQuals = quals.getFastQualifiers(); 3002 quals.removeFastQualifiers(); 3003 3004 // Check if we've already instantiated this type. 3005 llvm::FoldingSetNodeID ID; 3006 ExtQuals::Profile(ID, baseType, quals); 3007 void *insertPos = nullptr; 3008 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) { 3009 assert(eq->getQualifiers() == quals); 3010 return QualType(eq, fastQuals); 3011 } 3012 3013 // If the base type is not canonical, make the appropriate canonical type. 3014 QualType canon; 3015 if (!baseType->isCanonicalUnqualified()) { 3016 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split(); 3017 canonSplit.Quals.addConsistentQualifiers(quals); 3018 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals); 3019 3020 // Re-find the insert position. 3021 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos); 3022 } 3023 3024 auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals); 3025 ExtQualNodes.InsertNode(eq, insertPos); 3026 return QualType(eq, fastQuals); 3027 } 3028 3029 QualType ASTContext::getAddrSpaceQualType(QualType T, 3030 LangAS AddressSpace) const { 3031 QualType CanT = getCanonicalType(T); 3032 if (CanT.getAddressSpace() == AddressSpace) 3033 return T; 3034 3035 // If we are composing extended qualifiers together, merge together 3036 // into one ExtQuals node. 3037 QualifierCollector Quals; 3038 const Type *TypeNode = Quals.strip(T); 3039 3040 // If this type already has an address space specified, it cannot get 3041 // another one. 3042 assert(!Quals.hasAddressSpace() && 3043 "Type cannot be in multiple addr spaces!"); 3044 Quals.addAddressSpace(AddressSpace); 3045 3046 return getExtQualType(TypeNode, Quals); 3047 } 3048 3049 QualType ASTContext::removeAddrSpaceQualType(QualType T) const { 3050 // If the type is not qualified with an address space, just return it 3051 // immediately. 3052 if (!T.hasAddressSpace()) 3053 return T; 3054 3055 // If we are composing extended qualifiers together, merge together 3056 // into one ExtQuals node. 3057 QualifierCollector Quals; 3058 const Type *TypeNode; 3059 3060 while (T.hasAddressSpace()) { 3061 TypeNode = Quals.strip(T); 3062 3063 // If the type no longer has an address space after stripping qualifiers, 3064 // jump out. 3065 if (!QualType(TypeNode, 0).hasAddressSpace()) 3066 break; 3067 3068 // There might be sugar in the way. Strip it and try again. 3069 T = T.getSingleStepDesugaredType(*this); 3070 } 3071 3072 Quals.removeAddressSpace(); 3073 3074 // Removal of the address space can mean there are no longer any 3075 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts) 3076 // or required. 3077 if (Quals.hasNonFastQualifiers()) 3078 return getExtQualType(TypeNode, Quals); 3079 else 3080 return QualType(TypeNode, Quals.getFastQualifiers()); 3081 } 3082 3083 QualType ASTContext::getObjCGCQualType(QualType T, 3084 Qualifiers::GC GCAttr) const { 3085 QualType CanT = getCanonicalType(T); 3086 if (CanT.getObjCGCAttr() == GCAttr) 3087 return T; 3088 3089 if (const auto *ptr = T->getAs<PointerType>()) { 3090 QualType Pointee = ptr->getPointeeType(); 3091 if (Pointee->isAnyPointerType()) { 3092 QualType ResultType = getObjCGCQualType(Pointee, GCAttr); 3093 return getPointerType(ResultType); 3094 } 3095 } 3096 3097 // If we are composing extended qualifiers together, merge together 3098 // into one ExtQuals node. 3099 QualifierCollector Quals; 3100 const Type *TypeNode = Quals.strip(T); 3101 3102 // If this type already has an ObjCGC specified, it cannot get 3103 // another one. 3104 assert(!Quals.hasObjCGCAttr() && 3105 "Type cannot have multiple ObjCGCs!"); 3106 Quals.addObjCGCAttr(GCAttr); 3107 3108 return getExtQualType(TypeNode, Quals); 3109 } 3110 3111 QualType ASTContext::removePtrSizeAddrSpace(QualType T) const { 3112 if (const PointerType *Ptr = T->getAs<PointerType>()) { 3113 QualType Pointee = Ptr->getPointeeType(); 3114 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) { 3115 return getPointerType(removeAddrSpaceQualType(Pointee)); 3116 } 3117 } 3118 return T; 3119 } 3120 3121 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T, 3122 FunctionType::ExtInfo Info) { 3123 if (T->getExtInfo() == Info) 3124 return T; 3125 3126 QualType Result; 3127 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) { 3128 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info); 3129 } else { 3130 const auto *FPT = cast<FunctionProtoType>(T); 3131 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 3132 EPI.ExtInfo = Info; 3133 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI); 3134 } 3135 3136 return cast<FunctionType>(Result.getTypePtr()); 3137 } 3138 3139 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD, 3140 QualType ResultType) { 3141 FD = FD->getMostRecentDecl(); 3142 while (true) { 3143 const auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 3144 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 3145 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI)); 3146 if (FunctionDecl *Next = FD->getPreviousDecl()) 3147 FD = Next; 3148 else 3149 break; 3150 } 3151 if (ASTMutationListener *L = getASTMutationListener()) 3152 L->DeducedReturnType(FD, ResultType); 3153 } 3154 3155 /// Get a function type and produce the equivalent function type with the 3156 /// specified exception specification. Type sugar that can be present on a 3157 /// declaration of a function with an exception specification is permitted 3158 /// and preserved. Other type sugar (for instance, typedefs) is not. 3159 QualType ASTContext::getFunctionTypeWithExceptionSpec( 3160 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) { 3161 // Might have some parens. 3162 if (const auto *PT = dyn_cast<ParenType>(Orig)) 3163 return getParenType( 3164 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI)); 3165 3166 // Might be wrapped in a macro qualified type. 3167 if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig)) 3168 return getMacroQualifiedType( 3169 getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI), 3170 MQT->getMacroIdentifier()); 3171 3172 // Might have a calling-convention attribute. 3173 if (const auto *AT = dyn_cast<AttributedType>(Orig)) 3174 return getAttributedType( 3175 AT->getAttrKind(), 3176 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI), 3177 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI)); 3178 3179 // Anything else must be a function type. Rebuild it with the new exception 3180 // specification. 3181 const auto *Proto = Orig->castAs<FunctionProtoType>(); 3182 return getFunctionType( 3183 Proto->getReturnType(), Proto->getParamTypes(), 3184 Proto->getExtProtoInfo().withExceptionSpec(ESI)); 3185 } 3186 3187 bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T, 3188 QualType U) { 3189 return hasSameType(T, U) || 3190 (getLangOpts().CPlusPlus17 && 3191 hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None), 3192 getFunctionTypeWithExceptionSpec(U, EST_None))); 3193 } 3194 3195 QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) { 3196 if (const auto *Proto = T->getAs<FunctionProtoType>()) { 3197 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType()); 3198 SmallVector<QualType, 16> Args(Proto->param_types()); 3199 for (unsigned i = 0, n = Args.size(); i != n; ++i) 3200 Args[i] = removePtrSizeAddrSpace(Args[i]); 3201 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo()); 3202 } 3203 3204 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) { 3205 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType()); 3206 return getFunctionNoProtoType(RetTy, Proto->getExtInfo()); 3207 } 3208 3209 return T; 3210 } 3211 3212 bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) { 3213 return hasSameType(T, U) || 3214 hasSameType(getFunctionTypeWithoutPtrSizes(T), 3215 getFunctionTypeWithoutPtrSizes(U)); 3216 } 3217 3218 void ASTContext::adjustExceptionSpec( 3219 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, 3220 bool AsWritten) { 3221 // Update the type. 3222 QualType Updated = 3223 getFunctionTypeWithExceptionSpec(FD->getType(), ESI); 3224 FD->setType(Updated); 3225 3226 if (!AsWritten) 3227 return; 3228 3229 // Update the type in the type source information too. 3230 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) { 3231 // If the type and the type-as-written differ, we may need to update 3232 // the type-as-written too. 3233 if (TSInfo->getType() != FD->getType()) 3234 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI); 3235 3236 // FIXME: When we get proper type location information for exceptions, 3237 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch 3238 // up the TypeSourceInfo; 3239 assert(TypeLoc::getFullDataSizeForType(Updated) == 3240 TypeLoc::getFullDataSizeForType(TSInfo->getType()) && 3241 "TypeLoc size mismatch from updating exception specification"); 3242 TSInfo->overrideType(Updated); 3243 } 3244 } 3245 3246 /// getComplexType - Return the uniqued reference to the type for a complex 3247 /// number with the specified element type. 3248 QualType ASTContext::getComplexType(QualType T) const { 3249 // Unique pointers, to guarantee there is only one pointer of a particular 3250 // structure. 3251 llvm::FoldingSetNodeID ID; 3252 ComplexType::Profile(ID, T); 3253 3254 void *InsertPos = nullptr; 3255 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos)) 3256 return QualType(CT, 0); 3257 3258 // If the pointee type isn't canonical, this won't be a canonical type either, 3259 // so fill in the canonical type field. 3260 QualType Canonical; 3261 if (!T.isCanonical()) { 3262 Canonical = getComplexType(getCanonicalType(T)); 3263 3264 // Get the new insert position for the node we care about. 3265 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos); 3266 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3267 } 3268 auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical); 3269 Types.push_back(New); 3270 ComplexTypes.InsertNode(New, InsertPos); 3271 return QualType(New, 0); 3272 } 3273 3274 /// getPointerType - Return the uniqued reference to the type for a pointer to 3275 /// the specified type. 3276 QualType ASTContext::getPointerType(QualType T) const { 3277 // Unique pointers, to guarantee there is only one pointer of a particular 3278 // structure. 3279 llvm::FoldingSetNodeID ID; 3280 PointerType::Profile(ID, T); 3281 3282 void *InsertPos = nullptr; 3283 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3284 return QualType(PT, 0); 3285 3286 // If the pointee type isn't canonical, this won't be a canonical type either, 3287 // so fill in the canonical type field. 3288 QualType Canonical; 3289 if (!T.isCanonical()) { 3290 Canonical = getPointerType(getCanonicalType(T)); 3291 3292 // Get the new insert position for the node we care about. 3293 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3294 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3295 } 3296 auto *New = new (*this, TypeAlignment) PointerType(T, Canonical); 3297 Types.push_back(New); 3298 PointerTypes.InsertNode(New, InsertPos); 3299 return QualType(New, 0); 3300 } 3301 3302 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const { 3303 llvm::FoldingSetNodeID ID; 3304 AdjustedType::Profile(ID, Orig, New); 3305 void *InsertPos = nullptr; 3306 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3307 if (AT) 3308 return QualType(AT, 0); 3309 3310 QualType Canonical = getCanonicalType(New); 3311 3312 // Get the new insert position for the node we care about. 3313 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3314 assert(!AT && "Shouldn't be in the map!"); 3315 3316 AT = new (*this, TypeAlignment) 3317 AdjustedType(Type::Adjusted, Orig, New, Canonical); 3318 Types.push_back(AT); 3319 AdjustedTypes.InsertNode(AT, InsertPos); 3320 return QualType(AT, 0); 3321 } 3322 3323 QualType ASTContext::getDecayedType(QualType T) const { 3324 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay"); 3325 3326 QualType Decayed; 3327 3328 // C99 6.7.5.3p7: 3329 // A declaration of a parameter as "array of type" shall be 3330 // adjusted to "qualified pointer to type", where the type 3331 // qualifiers (if any) are those specified within the [ and ] of 3332 // the array type derivation. 3333 if (T->isArrayType()) 3334 Decayed = getArrayDecayedType(T); 3335 3336 // C99 6.7.5.3p8: 3337 // A declaration of a parameter as "function returning type" 3338 // shall be adjusted to "pointer to function returning type", as 3339 // in 6.3.2.1. 3340 if (T->isFunctionType()) 3341 Decayed = getPointerType(T); 3342 3343 llvm::FoldingSetNodeID ID; 3344 AdjustedType::Profile(ID, T, Decayed); 3345 void *InsertPos = nullptr; 3346 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3347 if (AT) 3348 return QualType(AT, 0); 3349 3350 QualType Canonical = getCanonicalType(Decayed); 3351 3352 // Get the new insert position for the node we care about. 3353 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3354 assert(!AT && "Shouldn't be in the map!"); 3355 3356 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical); 3357 Types.push_back(AT); 3358 AdjustedTypes.InsertNode(AT, InsertPos); 3359 return QualType(AT, 0); 3360 } 3361 3362 /// getBlockPointerType - Return the uniqued reference to the type for 3363 /// a pointer to the specified block. 3364 QualType ASTContext::getBlockPointerType(QualType T) const { 3365 assert(T->isFunctionType() && "block of function types only"); 3366 // Unique pointers, to guarantee there is only one block of a particular 3367 // structure. 3368 llvm::FoldingSetNodeID ID; 3369 BlockPointerType::Profile(ID, T); 3370 3371 void *InsertPos = nullptr; 3372 if (BlockPointerType *PT = 3373 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3374 return QualType(PT, 0); 3375 3376 // If the block pointee type isn't canonical, this won't be a canonical 3377 // type either so fill in the canonical type field. 3378 QualType Canonical; 3379 if (!T.isCanonical()) { 3380 Canonical = getBlockPointerType(getCanonicalType(T)); 3381 3382 // Get the new insert position for the node we care about. 3383 BlockPointerType *NewIP = 3384 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3385 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3386 } 3387 auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical); 3388 Types.push_back(New); 3389 BlockPointerTypes.InsertNode(New, InsertPos); 3390 return QualType(New, 0); 3391 } 3392 3393 /// getLValueReferenceType - Return the uniqued reference to the type for an 3394 /// lvalue reference to the specified type. 3395 QualType 3396 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const { 3397 assert((!T->isPlaceholderType() || 3398 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) && 3399 "Unresolved placeholder type"); 3400 3401 // Unique pointers, to guarantee there is only one pointer of a particular 3402 // structure. 3403 llvm::FoldingSetNodeID ID; 3404 ReferenceType::Profile(ID, T, SpelledAsLValue); 3405 3406 void *InsertPos = nullptr; 3407 if (LValueReferenceType *RT = 3408 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 3409 return QualType(RT, 0); 3410 3411 const auto *InnerRef = T->getAs<ReferenceType>(); 3412 3413 // If the referencee type isn't canonical, this won't be a canonical type 3414 // either, so fill in the canonical type field. 3415 QualType Canonical; 3416 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) { 3417 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 3418 Canonical = getLValueReferenceType(getCanonicalType(PointeeType)); 3419 3420 // Get the new insert position for the node we care about. 3421 LValueReferenceType *NewIP = 3422 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 3423 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3424 } 3425 3426 auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical, 3427 SpelledAsLValue); 3428 Types.push_back(New); 3429 LValueReferenceTypes.InsertNode(New, InsertPos); 3430 3431 return QualType(New, 0); 3432 } 3433 3434 /// getRValueReferenceType - Return the uniqued reference to the type for an 3435 /// rvalue reference to the specified type. 3436 QualType ASTContext::getRValueReferenceType(QualType T) const { 3437 assert((!T->isPlaceholderType() || 3438 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) && 3439 "Unresolved placeholder type"); 3440 3441 // Unique pointers, to guarantee there is only one pointer of a particular 3442 // structure. 3443 llvm::FoldingSetNodeID ID; 3444 ReferenceType::Profile(ID, T, false); 3445 3446 void *InsertPos = nullptr; 3447 if (RValueReferenceType *RT = 3448 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 3449 return QualType(RT, 0); 3450 3451 const auto *InnerRef = T->getAs<ReferenceType>(); 3452 3453 // If the referencee type isn't canonical, this won't be a canonical type 3454 // either, so fill in the canonical type field. 3455 QualType Canonical; 3456 if (InnerRef || !T.isCanonical()) { 3457 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 3458 Canonical = getRValueReferenceType(getCanonicalType(PointeeType)); 3459 3460 // Get the new insert position for the node we care about. 3461 RValueReferenceType *NewIP = 3462 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 3463 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3464 } 3465 3466 auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical); 3467 Types.push_back(New); 3468 RValueReferenceTypes.InsertNode(New, InsertPos); 3469 return QualType(New, 0); 3470 } 3471 3472 /// getMemberPointerType - Return the uniqued reference to the type for a 3473 /// member pointer to the specified type, in the specified class. 3474 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const { 3475 // Unique pointers, to guarantee there is only one pointer of a particular 3476 // structure. 3477 llvm::FoldingSetNodeID ID; 3478 MemberPointerType::Profile(ID, T, Cls); 3479 3480 void *InsertPos = nullptr; 3481 if (MemberPointerType *PT = 3482 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3483 return QualType(PT, 0); 3484 3485 // If the pointee or class type isn't canonical, this won't be a canonical 3486 // type either, so fill in the canonical type field. 3487 QualType Canonical; 3488 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) { 3489 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls)); 3490 3491 // Get the new insert position for the node we care about. 3492 MemberPointerType *NewIP = 3493 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3494 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3495 } 3496 auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical); 3497 Types.push_back(New); 3498 MemberPointerTypes.InsertNode(New, InsertPos); 3499 return QualType(New, 0); 3500 } 3501 3502 /// getConstantArrayType - Return the unique reference to the type for an 3503 /// array of the specified element type. 3504 QualType ASTContext::getConstantArrayType(QualType EltTy, 3505 const llvm::APInt &ArySizeIn, 3506 const Expr *SizeExpr, 3507 ArrayType::ArraySizeModifier ASM, 3508 unsigned IndexTypeQuals) const { 3509 assert((EltTy->isDependentType() || 3510 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) && 3511 "Constant array of VLAs is illegal!"); 3512 3513 // We only need the size as part of the type if it's instantiation-dependent. 3514 if (SizeExpr && !SizeExpr->isInstantiationDependent()) 3515 SizeExpr = nullptr; 3516 3517 // Convert the array size into a canonical width matching the pointer size for 3518 // the target. 3519 llvm::APInt ArySize(ArySizeIn); 3520 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth()); 3521 3522 llvm::FoldingSetNodeID ID; 3523 ConstantArrayType::Profile(ID, *this, EltTy, ArySize, SizeExpr, ASM, 3524 IndexTypeQuals); 3525 3526 void *InsertPos = nullptr; 3527 if (ConstantArrayType *ATP = 3528 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 3529 return QualType(ATP, 0); 3530 3531 // If the element type isn't canonical or has qualifiers, or the array bound 3532 // is instantiation-dependent, this won't be a canonical type either, so fill 3533 // in the canonical type field. 3534 QualType Canon; 3535 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) { 3536 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 3537 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr, 3538 ASM, IndexTypeQuals); 3539 Canon = getQualifiedType(Canon, canonSplit.Quals); 3540 3541 // Get the new insert position for the node we care about. 3542 ConstantArrayType *NewIP = 3543 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 3544 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3545 } 3546 3547 void *Mem = Allocate( 3548 ConstantArrayType::totalSizeToAlloc<const Expr *>(SizeExpr ? 1 : 0), 3549 TypeAlignment); 3550 auto *New = new (Mem) 3551 ConstantArrayType(EltTy, Canon, ArySize, SizeExpr, ASM, IndexTypeQuals); 3552 ConstantArrayTypes.InsertNode(New, InsertPos); 3553 Types.push_back(New); 3554 return QualType(New, 0); 3555 } 3556 3557 /// getVariableArrayDecayedType - Turns the given type, which may be 3558 /// variably-modified, into the corresponding type with all the known 3559 /// sizes replaced with [*]. 3560 QualType ASTContext::getVariableArrayDecayedType(QualType type) const { 3561 // Vastly most common case. 3562 if (!type->isVariablyModifiedType()) return type; 3563 3564 QualType result; 3565 3566 SplitQualType split = type.getSplitDesugaredType(); 3567 const Type *ty = split.Ty; 3568 switch (ty->getTypeClass()) { 3569 #define TYPE(Class, Base) 3570 #define ABSTRACT_TYPE(Class, Base) 3571 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 3572 #include "clang/AST/TypeNodes.inc" 3573 llvm_unreachable("didn't desugar past all non-canonical types?"); 3574 3575 // These types should never be variably-modified. 3576 case Type::Builtin: 3577 case Type::Complex: 3578 case Type::Vector: 3579 case Type::DependentVector: 3580 case Type::ExtVector: 3581 case Type::DependentSizedExtVector: 3582 case Type::ConstantMatrix: 3583 case Type::DependentSizedMatrix: 3584 case Type::DependentAddressSpace: 3585 case Type::ObjCObject: 3586 case Type::ObjCInterface: 3587 case Type::ObjCObjectPointer: 3588 case Type::Record: 3589 case Type::Enum: 3590 case Type::UnresolvedUsing: 3591 case Type::TypeOfExpr: 3592 case Type::TypeOf: 3593 case Type::Decltype: 3594 case Type::UnaryTransform: 3595 case Type::DependentName: 3596 case Type::InjectedClassName: 3597 case Type::TemplateSpecialization: 3598 case Type::DependentTemplateSpecialization: 3599 case Type::TemplateTypeParm: 3600 case Type::SubstTemplateTypeParmPack: 3601 case Type::Auto: 3602 case Type::DeducedTemplateSpecialization: 3603 case Type::PackExpansion: 3604 case Type::BitInt: 3605 case Type::DependentBitInt: 3606 llvm_unreachable("type should never be variably-modified"); 3607 3608 // These types can be variably-modified but should never need to 3609 // further decay. 3610 case Type::FunctionNoProto: 3611 case Type::FunctionProto: 3612 case Type::BlockPointer: 3613 case Type::MemberPointer: 3614 case Type::Pipe: 3615 return type; 3616 3617 // These types can be variably-modified. All these modifications 3618 // preserve structure except as noted by comments. 3619 // TODO: if we ever care about optimizing VLAs, there are no-op 3620 // optimizations available here. 3621 case Type::Pointer: 3622 result = getPointerType(getVariableArrayDecayedType( 3623 cast<PointerType>(ty)->getPointeeType())); 3624 break; 3625 3626 case Type::LValueReference: { 3627 const auto *lv = cast<LValueReferenceType>(ty); 3628 result = getLValueReferenceType( 3629 getVariableArrayDecayedType(lv->getPointeeType()), 3630 lv->isSpelledAsLValue()); 3631 break; 3632 } 3633 3634 case Type::RValueReference: { 3635 const auto *lv = cast<RValueReferenceType>(ty); 3636 result = getRValueReferenceType( 3637 getVariableArrayDecayedType(lv->getPointeeType())); 3638 break; 3639 } 3640 3641 case Type::Atomic: { 3642 const auto *at = cast<AtomicType>(ty); 3643 result = getAtomicType(getVariableArrayDecayedType(at->getValueType())); 3644 break; 3645 } 3646 3647 case Type::ConstantArray: { 3648 const auto *cat = cast<ConstantArrayType>(ty); 3649 result = getConstantArrayType( 3650 getVariableArrayDecayedType(cat->getElementType()), 3651 cat->getSize(), 3652 cat->getSizeExpr(), 3653 cat->getSizeModifier(), 3654 cat->getIndexTypeCVRQualifiers()); 3655 break; 3656 } 3657 3658 case Type::DependentSizedArray: { 3659 const auto *dat = cast<DependentSizedArrayType>(ty); 3660 result = getDependentSizedArrayType( 3661 getVariableArrayDecayedType(dat->getElementType()), 3662 dat->getSizeExpr(), 3663 dat->getSizeModifier(), 3664 dat->getIndexTypeCVRQualifiers(), 3665 dat->getBracketsRange()); 3666 break; 3667 } 3668 3669 // Turn incomplete types into [*] types. 3670 case Type::IncompleteArray: { 3671 const auto *iat = cast<IncompleteArrayType>(ty); 3672 result = getVariableArrayType( 3673 getVariableArrayDecayedType(iat->getElementType()), 3674 /*size*/ nullptr, 3675 ArrayType::Normal, 3676 iat->getIndexTypeCVRQualifiers(), 3677 SourceRange()); 3678 break; 3679 } 3680 3681 // Turn VLA types into [*] types. 3682 case Type::VariableArray: { 3683 const auto *vat = cast<VariableArrayType>(ty); 3684 result = getVariableArrayType( 3685 getVariableArrayDecayedType(vat->getElementType()), 3686 /*size*/ nullptr, 3687 ArrayType::Star, 3688 vat->getIndexTypeCVRQualifiers(), 3689 vat->getBracketsRange()); 3690 break; 3691 } 3692 } 3693 3694 // Apply the top-level qualifiers from the original. 3695 return getQualifiedType(result, split.Quals); 3696 } 3697 3698 /// getVariableArrayType - Returns a non-unique reference to the type for a 3699 /// variable array of the specified element type. 3700 QualType ASTContext::getVariableArrayType(QualType EltTy, 3701 Expr *NumElts, 3702 ArrayType::ArraySizeModifier ASM, 3703 unsigned IndexTypeQuals, 3704 SourceRange Brackets) const { 3705 // Since we don't unique expressions, it isn't possible to unique VLA's 3706 // that have an expression provided for their size. 3707 QualType Canon; 3708 3709 // Be sure to pull qualifiers off the element type. 3710 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) { 3711 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 3712 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM, 3713 IndexTypeQuals, Brackets); 3714 Canon = getQualifiedType(Canon, canonSplit.Quals); 3715 } 3716 3717 auto *New = new (*this, TypeAlignment) 3718 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets); 3719 3720 VariableArrayTypes.push_back(New); 3721 Types.push_back(New); 3722 return QualType(New, 0); 3723 } 3724 3725 /// getDependentSizedArrayType - Returns a non-unique reference to 3726 /// the type for a dependently-sized array of the specified element 3727 /// type. 3728 QualType ASTContext::getDependentSizedArrayType(QualType elementType, 3729 Expr *numElements, 3730 ArrayType::ArraySizeModifier ASM, 3731 unsigned elementTypeQuals, 3732 SourceRange brackets) const { 3733 assert((!numElements || numElements->isTypeDependent() || 3734 numElements->isValueDependent()) && 3735 "Size must be type- or value-dependent!"); 3736 3737 // Dependently-sized array types that do not have a specified number 3738 // of elements will have their sizes deduced from a dependent 3739 // initializer. We do no canonicalization here at all, which is okay 3740 // because they can't be used in most locations. 3741 if (!numElements) { 3742 auto *newType 3743 = new (*this, TypeAlignment) 3744 DependentSizedArrayType(*this, elementType, QualType(), 3745 numElements, ASM, elementTypeQuals, 3746 brackets); 3747 Types.push_back(newType); 3748 return QualType(newType, 0); 3749 } 3750 3751 // Otherwise, we actually build a new type every time, but we 3752 // also build a canonical type. 3753 3754 SplitQualType canonElementType = getCanonicalType(elementType).split(); 3755 3756 void *insertPos = nullptr; 3757 llvm::FoldingSetNodeID ID; 3758 DependentSizedArrayType::Profile(ID, *this, 3759 QualType(canonElementType.Ty, 0), 3760 ASM, elementTypeQuals, numElements); 3761 3762 // Look for an existing type with these properties. 3763 DependentSizedArrayType *canonTy = 3764 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos); 3765 3766 // If we don't have one, build one. 3767 if (!canonTy) { 3768 canonTy = new (*this, TypeAlignment) 3769 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0), 3770 QualType(), numElements, ASM, elementTypeQuals, 3771 brackets); 3772 DependentSizedArrayTypes.InsertNode(canonTy, insertPos); 3773 Types.push_back(canonTy); 3774 } 3775 3776 // Apply qualifiers from the element type to the array. 3777 QualType canon = getQualifiedType(QualType(canonTy,0), 3778 canonElementType.Quals); 3779 3780 // If we didn't need extra canonicalization for the element type or the size 3781 // expression, then just use that as our result. 3782 if (QualType(canonElementType.Ty, 0) == elementType && 3783 canonTy->getSizeExpr() == numElements) 3784 return canon; 3785 3786 // Otherwise, we need to build a type which follows the spelling 3787 // of the element type. 3788 auto *sugaredType 3789 = new (*this, TypeAlignment) 3790 DependentSizedArrayType(*this, elementType, canon, numElements, 3791 ASM, elementTypeQuals, brackets); 3792 Types.push_back(sugaredType); 3793 return QualType(sugaredType, 0); 3794 } 3795 3796 QualType ASTContext::getIncompleteArrayType(QualType elementType, 3797 ArrayType::ArraySizeModifier ASM, 3798 unsigned elementTypeQuals) const { 3799 llvm::FoldingSetNodeID ID; 3800 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals); 3801 3802 void *insertPos = nullptr; 3803 if (IncompleteArrayType *iat = 3804 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos)) 3805 return QualType(iat, 0); 3806 3807 // If the element type isn't canonical, this won't be a canonical type 3808 // either, so fill in the canonical type field. We also have to pull 3809 // qualifiers off the element type. 3810 QualType canon; 3811 3812 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) { 3813 SplitQualType canonSplit = getCanonicalType(elementType).split(); 3814 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0), 3815 ASM, elementTypeQuals); 3816 canon = getQualifiedType(canon, canonSplit.Quals); 3817 3818 // Get the new insert position for the node we care about. 3819 IncompleteArrayType *existing = 3820 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos); 3821 assert(!existing && "Shouldn't be in the map!"); (void) existing; 3822 } 3823 3824 auto *newType = new (*this, TypeAlignment) 3825 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals); 3826 3827 IncompleteArrayTypes.InsertNode(newType, insertPos); 3828 Types.push_back(newType); 3829 return QualType(newType, 0); 3830 } 3831 3832 ASTContext::BuiltinVectorTypeInfo 3833 ASTContext::getBuiltinVectorTypeInfo(const BuiltinType *Ty) const { 3834 #define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \ 3835 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \ 3836 NUMVECTORS}; 3837 3838 #define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \ 3839 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS}; 3840 3841 switch (Ty->getKind()) { 3842 default: 3843 llvm_unreachable("Unsupported builtin vector type"); 3844 case BuiltinType::SveInt8: 3845 return SVE_INT_ELTTY(8, 16, true, 1); 3846 case BuiltinType::SveUint8: 3847 return SVE_INT_ELTTY(8, 16, false, 1); 3848 case BuiltinType::SveInt8x2: 3849 return SVE_INT_ELTTY(8, 16, true, 2); 3850 case BuiltinType::SveUint8x2: 3851 return SVE_INT_ELTTY(8, 16, false, 2); 3852 case BuiltinType::SveInt8x3: 3853 return SVE_INT_ELTTY(8, 16, true, 3); 3854 case BuiltinType::SveUint8x3: 3855 return SVE_INT_ELTTY(8, 16, false, 3); 3856 case BuiltinType::SveInt8x4: 3857 return SVE_INT_ELTTY(8, 16, true, 4); 3858 case BuiltinType::SveUint8x4: 3859 return SVE_INT_ELTTY(8, 16, false, 4); 3860 case BuiltinType::SveInt16: 3861 return SVE_INT_ELTTY(16, 8, true, 1); 3862 case BuiltinType::SveUint16: 3863 return SVE_INT_ELTTY(16, 8, false, 1); 3864 case BuiltinType::SveInt16x2: 3865 return SVE_INT_ELTTY(16, 8, true, 2); 3866 case BuiltinType::SveUint16x2: 3867 return SVE_INT_ELTTY(16, 8, false, 2); 3868 case BuiltinType::SveInt16x3: 3869 return SVE_INT_ELTTY(16, 8, true, 3); 3870 case BuiltinType::SveUint16x3: 3871 return SVE_INT_ELTTY(16, 8, false, 3); 3872 case BuiltinType::SveInt16x4: 3873 return SVE_INT_ELTTY(16, 8, true, 4); 3874 case BuiltinType::SveUint16x4: 3875 return SVE_INT_ELTTY(16, 8, false, 4); 3876 case BuiltinType::SveInt32: 3877 return SVE_INT_ELTTY(32, 4, true, 1); 3878 case BuiltinType::SveUint32: 3879 return SVE_INT_ELTTY(32, 4, false, 1); 3880 case BuiltinType::SveInt32x2: 3881 return SVE_INT_ELTTY(32, 4, true, 2); 3882 case BuiltinType::SveUint32x2: 3883 return SVE_INT_ELTTY(32, 4, false, 2); 3884 case BuiltinType::SveInt32x3: 3885 return SVE_INT_ELTTY(32, 4, true, 3); 3886 case BuiltinType::SveUint32x3: 3887 return SVE_INT_ELTTY(32, 4, false, 3); 3888 case BuiltinType::SveInt32x4: 3889 return SVE_INT_ELTTY(32, 4, true, 4); 3890 case BuiltinType::SveUint32x4: 3891 return SVE_INT_ELTTY(32, 4, false, 4); 3892 case BuiltinType::SveInt64: 3893 return SVE_INT_ELTTY(64, 2, true, 1); 3894 case BuiltinType::SveUint64: 3895 return SVE_INT_ELTTY(64, 2, false, 1); 3896 case BuiltinType::SveInt64x2: 3897 return SVE_INT_ELTTY(64, 2, true, 2); 3898 case BuiltinType::SveUint64x2: 3899 return SVE_INT_ELTTY(64, 2, false, 2); 3900 case BuiltinType::SveInt64x3: 3901 return SVE_INT_ELTTY(64, 2, true, 3); 3902 case BuiltinType::SveUint64x3: 3903 return SVE_INT_ELTTY(64, 2, false, 3); 3904 case BuiltinType::SveInt64x4: 3905 return SVE_INT_ELTTY(64, 2, true, 4); 3906 case BuiltinType::SveUint64x4: 3907 return SVE_INT_ELTTY(64, 2, false, 4); 3908 case BuiltinType::SveBool: 3909 return SVE_ELTTY(BoolTy, 16, 1); 3910 case BuiltinType::SveFloat16: 3911 return SVE_ELTTY(HalfTy, 8, 1); 3912 case BuiltinType::SveFloat16x2: 3913 return SVE_ELTTY(HalfTy, 8, 2); 3914 case BuiltinType::SveFloat16x3: 3915 return SVE_ELTTY(HalfTy, 8, 3); 3916 case BuiltinType::SveFloat16x4: 3917 return SVE_ELTTY(HalfTy, 8, 4); 3918 case BuiltinType::SveFloat32: 3919 return SVE_ELTTY(FloatTy, 4, 1); 3920 case BuiltinType::SveFloat32x2: 3921 return SVE_ELTTY(FloatTy, 4, 2); 3922 case BuiltinType::SveFloat32x3: 3923 return SVE_ELTTY(FloatTy, 4, 3); 3924 case BuiltinType::SveFloat32x4: 3925 return SVE_ELTTY(FloatTy, 4, 4); 3926 case BuiltinType::SveFloat64: 3927 return SVE_ELTTY(DoubleTy, 2, 1); 3928 case BuiltinType::SveFloat64x2: 3929 return SVE_ELTTY(DoubleTy, 2, 2); 3930 case BuiltinType::SveFloat64x3: 3931 return SVE_ELTTY(DoubleTy, 2, 3); 3932 case BuiltinType::SveFloat64x4: 3933 return SVE_ELTTY(DoubleTy, 2, 4); 3934 case BuiltinType::SveBFloat16: 3935 return SVE_ELTTY(BFloat16Ty, 8, 1); 3936 case BuiltinType::SveBFloat16x2: 3937 return SVE_ELTTY(BFloat16Ty, 8, 2); 3938 case BuiltinType::SveBFloat16x3: 3939 return SVE_ELTTY(BFloat16Ty, 8, 3); 3940 case BuiltinType::SveBFloat16x4: 3941 return SVE_ELTTY(BFloat16Ty, 8, 4); 3942 #define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \ 3943 IsSigned) \ 3944 case BuiltinType::Id: \ 3945 return {getIntTypeForBitwidth(ElBits, IsSigned), \ 3946 llvm::ElementCount::getScalable(NumEls), NF}; 3947 #define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \ 3948 case BuiltinType::Id: \ 3949 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \ 3950 llvm::ElementCount::getScalable(NumEls), NF}; 3951 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \ 3952 case BuiltinType::Id: \ 3953 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1}; 3954 #include "clang/Basic/RISCVVTypes.def" 3955 } 3956 } 3957 3958 /// getScalableVectorType - Return the unique reference to a scalable vector 3959 /// type of the specified element type and size. VectorType must be a built-in 3960 /// type. 3961 QualType ASTContext::getScalableVectorType(QualType EltTy, 3962 unsigned NumElts) const { 3963 if (Target->hasAArch64SVETypes()) { 3964 uint64_t EltTySize = getTypeSize(EltTy); 3965 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \ 3966 IsSigned, IsFP, IsBF) \ 3967 if (!EltTy->isBooleanType() && \ 3968 ((EltTy->hasIntegerRepresentation() && \ 3969 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \ 3970 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \ 3971 IsFP && !IsBF) || \ 3972 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \ 3973 IsBF && !IsFP)) && \ 3974 EltTySize == ElBits && NumElts == NumEls) { \ 3975 return SingletonId; \ 3976 } 3977 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \ 3978 if (EltTy->isBooleanType() && NumElts == NumEls) \ 3979 return SingletonId; 3980 #include "clang/Basic/AArch64SVEACLETypes.def" 3981 } else if (Target->hasRISCVVTypes()) { 3982 uint64_t EltTySize = getTypeSize(EltTy); 3983 #define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \ 3984 IsFP) \ 3985 if (!EltTy->isBooleanType() && \ 3986 ((EltTy->hasIntegerRepresentation() && \ 3987 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \ 3988 (EltTy->hasFloatingRepresentation() && IsFP)) && \ 3989 EltTySize == ElBits && NumElts == NumEls) \ 3990 return SingletonId; 3991 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \ 3992 if (EltTy->isBooleanType() && NumElts == NumEls) \ 3993 return SingletonId; 3994 #include "clang/Basic/RISCVVTypes.def" 3995 } 3996 return QualType(); 3997 } 3998 3999 /// getVectorType - Return the unique reference to a vector type of 4000 /// the specified element type and size. VectorType must be a built-in type. 4001 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts, 4002 VectorType::VectorKind VecKind) const { 4003 assert(vecType->isBuiltinType()); 4004 4005 // Check if we've already instantiated a vector of this type. 4006 llvm::FoldingSetNodeID ID; 4007 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind); 4008 4009 void *InsertPos = nullptr; 4010 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 4011 return QualType(VTP, 0); 4012 4013 // If the element type isn't canonical, this won't be a canonical type either, 4014 // so fill in the canonical type field. 4015 QualType Canonical; 4016 if (!vecType.isCanonical()) { 4017 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind); 4018 4019 // Get the new insert position for the node we care about. 4020 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4021 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4022 } 4023 auto *New = new (*this, TypeAlignment) 4024 VectorType(vecType, NumElts, Canonical, VecKind); 4025 VectorTypes.InsertNode(New, InsertPos); 4026 Types.push_back(New); 4027 return QualType(New, 0); 4028 } 4029 4030 QualType 4031 ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr, 4032 SourceLocation AttrLoc, 4033 VectorType::VectorKind VecKind) const { 4034 llvm::FoldingSetNodeID ID; 4035 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr, 4036 VecKind); 4037 void *InsertPos = nullptr; 4038 DependentVectorType *Canon = 4039 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4040 DependentVectorType *New; 4041 4042 if (Canon) { 4043 New = new (*this, TypeAlignment) DependentVectorType( 4044 *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind); 4045 } else { 4046 QualType CanonVecTy = getCanonicalType(VecType); 4047 if (CanonVecTy == VecType) { 4048 New = new (*this, TypeAlignment) DependentVectorType( 4049 *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind); 4050 4051 DependentVectorType *CanonCheck = 4052 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4053 assert(!CanonCheck && 4054 "Dependent-sized vector_size canonical type broken"); 4055 (void)CanonCheck; 4056 DependentVectorTypes.InsertNode(New, InsertPos); 4057 } else { 4058 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr, 4059 SourceLocation(), VecKind); 4060 New = new (*this, TypeAlignment) DependentVectorType( 4061 *this, VecType, CanonTy, SizeExpr, AttrLoc, VecKind); 4062 } 4063 } 4064 4065 Types.push_back(New); 4066 return QualType(New, 0); 4067 } 4068 4069 /// getExtVectorType - Return the unique reference to an extended vector type of 4070 /// the specified element type and size. VectorType must be a built-in type. 4071 QualType 4072 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const { 4073 assert(vecType->isBuiltinType() || vecType->isDependentType()); 4074 4075 // Check if we've already instantiated a vector of this type. 4076 llvm::FoldingSetNodeID ID; 4077 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, 4078 VectorType::GenericVector); 4079 void *InsertPos = nullptr; 4080 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 4081 return QualType(VTP, 0); 4082 4083 // If the element type isn't canonical, this won't be a canonical type either, 4084 // so fill in the canonical type field. 4085 QualType Canonical; 4086 if (!vecType.isCanonical()) { 4087 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts); 4088 4089 // Get the new insert position for the node we care about. 4090 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4091 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4092 } 4093 auto *New = new (*this, TypeAlignment) 4094 ExtVectorType(vecType, NumElts, Canonical); 4095 VectorTypes.InsertNode(New, InsertPos); 4096 Types.push_back(New); 4097 return QualType(New, 0); 4098 } 4099 4100 QualType 4101 ASTContext::getDependentSizedExtVectorType(QualType vecType, 4102 Expr *SizeExpr, 4103 SourceLocation AttrLoc) const { 4104 llvm::FoldingSetNodeID ID; 4105 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType), 4106 SizeExpr); 4107 4108 void *InsertPos = nullptr; 4109 DependentSizedExtVectorType *Canon 4110 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4111 DependentSizedExtVectorType *New; 4112 if (Canon) { 4113 // We already have a canonical version of this array type; use it as 4114 // the canonical type for a newly-built type. 4115 New = new (*this, TypeAlignment) 4116 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0), 4117 SizeExpr, AttrLoc); 4118 } else { 4119 QualType CanonVecTy = getCanonicalType(vecType); 4120 if (CanonVecTy == vecType) { 4121 New = new (*this, TypeAlignment) 4122 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr, 4123 AttrLoc); 4124 4125 DependentSizedExtVectorType *CanonCheck 4126 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4127 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken"); 4128 (void)CanonCheck; 4129 DependentSizedExtVectorTypes.InsertNode(New, InsertPos); 4130 } else { 4131 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr, 4132 SourceLocation()); 4133 New = new (*this, TypeAlignment) DependentSizedExtVectorType( 4134 *this, vecType, CanonExtTy, SizeExpr, AttrLoc); 4135 } 4136 } 4137 4138 Types.push_back(New); 4139 return QualType(New, 0); 4140 } 4141 4142 QualType ASTContext::getConstantMatrixType(QualType ElementTy, unsigned NumRows, 4143 unsigned NumColumns) const { 4144 llvm::FoldingSetNodeID ID; 4145 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns, 4146 Type::ConstantMatrix); 4147 4148 assert(MatrixType::isValidElementType(ElementTy) && 4149 "need a valid element type"); 4150 assert(ConstantMatrixType::isDimensionValid(NumRows) && 4151 ConstantMatrixType::isDimensionValid(NumColumns) && 4152 "need valid matrix dimensions"); 4153 void *InsertPos = nullptr; 4154 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos)) 4155 return QualType(MTP, 0); 4156 4157 QualType Canonical; 4158 if (!ElementTy.isCanonical()) { 4159 Canonical = 4160 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns); 4161 4162 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos); 4163 assert(!NewIP && "Matrix type shouldn't already exist in the map"); 4164 (void)NewIP; 4165 } 4166 4167 auto *New = new (*this, TypeAlignment) 4168 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical); 4169 MatrixTypes.InsertNode(New, InsertPos); 4170 Types.push_back(New); 4171 return QualType(New, 0); 4172 } 4173 4174 QualType ASTContext::getDependentSizedMatrixType(QualType ElementTy, 4175 Expr *RowExpr, 4176 Expr *ColumnExpr, 4177 SourceLocation AttrLoc) const { 4178 QualType CanonElementTy = getCanonicalType(ElementTy); 4179 llvm::FoldingSetNodeID ID; 4180 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr, 4181 ColumnExpr); 4182 4183 void *InsertPos = nullptr; 4184 DependentSizedMatrixType *Canon = 4185 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos); 4186 4187 if (!Canon) { 4188 Canon = new (*this, TypeAlignment) DependentSizedMatrixType( 4189 *this, CanonElementTy, QualType(), RowExpr, ColumnExpr, AttrLoc); 4190 #ifndef NDEBUG 4191 DependentSizedMatrixType *CanonCheck = 4192 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos); 4193 assert(!CanonCheck && "Dependent-sized matrix canonical type broken"); 4194 #endif 4195 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos); 4196 Types.push_back(Canon); 4197 } 4198 4199 // Already have a canonical version of the matrix type 4200 // 4201 // If it exactly matches the requested type, use it directly. 4202 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr && 4203 Canon->getRowExpr() == ColumnExpr) 4204 return QualType(Canon, 0); 4205 4206 // Use Canon as the canonical type for newly-built type. 4207 DependentSizedMatrixType *New = new (*this, TypeAlignment) 4208 DependentSizedMatrixType(*this, ElementTy, QualType(Canon, 0), RowExpr, 4209 ColumnExpr, AttrLoc); 4210 Types.push_back(New); 4211 return QualType(New, 0); 4212 } 4213 4214 QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType, 4215 Expr *AddrSpaceExpr, 4216 SourceLocation AttrLoc) const { 4217 assert(AddrSpaceExpr->isInstantiationDependent()); 4218 4219 QualType canonPointeeType = getCanonicalType(PointeeType); 4220 4221 void *insertPos = nullptr; 4222 llvm::FoldingSetNodeID ID; 4223 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType, 4224 AddrSpaceExpr); 4225 4226 DependentAddressSpaceType *canonTy = 4227 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos); 4228 4229 if (!canonTy) { 4230 canonTy = new (*this, TypeAlignment) 4231 DependentAddressSpaceType(*this, canonPointeeType, 4232 QualType(), AddrSpaceExpr, AttrLoc); 4233 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos); 4234 Types.push_back(canonTy); 4235 } 4236 4237 if (canonPointeeType == PointeeType && 4238 canonTy->getAddrSpaceExpr() == AddrSpaceExpr) 4239 return QualType(canonTy, 0); 4240 4241 auto *sugaredType 4242 = new (*this, TypeAlignment) 4243 DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0), 4244 AddrSpaceExpr, AttrLoc); 4245 Types.push_back(sugaredType); 4246 return QualType(sugaredType, 0); 4247 } 4248 4249 /// Determine whether \p T is canonical as the result type of a function. 4250 static bool isCanonicalResultType(QualType T) { 4251 return T.isCanonical() && 4252 (T.getObjCLifetime() == Qualifiers::OCL_None || 4253 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone); 4254 } 4255 4256 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'. 4257 QualType 4258 ASTContext::getFunctionNoProtoType(QualType ResultTy, 4259 const FunctionType::ExtInfo &Info) const { 4260 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter 4261 // functionality creates a function without a prototype regardless of 4262 // language mode (so it makes them even in C++). Once the rewriter has been 4263 // fixed, this assertion can be enabled again. 4264 //assert(!LangOpts.requiresStrictPrototypes() && 4265 // "strict prototypes are disabled"); 4266 4267 // Unique functions, to guarantee there is only one function of a particular 4268 // structure. 4269 llvm::FoldingSetNodeID ID; 4270 FunctionNoProtoType::Profile(ID, ResultTy, Info); 4271 4272 void *InsertPos = nullptr; 4273 if (FunctionNoProtoType *FT = 4274 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 4275 return QualType(FT, 0); 4276 4277 QualType Canonical; 4278 if (!isCanonicalResultType(ResultTy)) { 4279 Canonical = 4280 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info); 4281 4282 // Get the new insert position for the node we care about. 4283 FunctionNoProtoType *NewIP = 4284 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 4285 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4286 } 4287 4288 auto *New = new (*this, TypeAlignment) 4289 FunctionNoProtoType(ResultTy, Canonical, Info); 4290 Types.push_back(New); 4291 FunctionNoProtoTypes.InsertNode(New, InsertPos); 4292 return QualType(New, 0); 4293 } 4294 4295 CanQualType 4296 ASTContext::getCanonicalFunctionResultType(QualType ResultType) const { 4297 CanQualType CanResultType = getCanonicalType(ResultType); 4298 4299 // Canonical result types do not have ARC lifetime qualifiers. 4300 if (CanResultType.getQualifiers().hasObjCLifetime()) { 4301 Qualifiers Qs = CanResultType.getQualifiers(); 4302 Qs.removeObjCLifetime(); 4303 return CanQualType::CreateUnsafe( 4304 getQualifiedType(CanResultType.getUnqualifiedType(), Qs)); 4305 } 4306 4307 return CanResultType; 4308 } 4309 4310 static bool isCanonicalExceptionSpecification( 4311 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) { 4312 if (ESI.Type == EST_None) 4313 return true; 4314 if (!NoexceptInType) 4315 return false; 4316 4317 // C++17 onwards: exception specification is part of the type, as a simple 4318 // boolean "can this function type throw". 4319 if (ESI.Type == EST_BasicNoexcept) 4320 return true; 4321 4322 // A noexcept(expr) specification is (possibly) canonical if expr is 4323 // value-dependent. 4324 if (ESI.Type == EST_DependentNoexcept) 4325 return true; 4326 4327 // A dynamic exception specification is canonical if it only contains pack 4328 // expansions (so we can't tell whether it's non-throwing) and all its 4329 // contained types are canonical. 4330 if (ESI.Type == EST_Dynamic) { 4331 bool AnyPackExpansions = false; 4332 for (QualType ET : ESI.Exceptions) { 4333 if (!ET.isCanonical()) 4334 return false; 4335 if (ET->getAs<PackExpansionType>()) 4336 AnyPackExpansions = true; 4337 } 4338 return AnyPackExpansions; 4339 } 4340 4341 return false; 4342 } 4343 4344 QualType ASTContext::getFunctionTypeInternal( 4345 QualType ResultTy, ArrayRef<QualType> ArgArray, 4346 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const { 4347 size_t NumArgs = ArgArray.size(); 4348 4349 // Unique functions, to guarantee there is only one function of a particular 4350 // structure. 4351 llvm::FoldingSetNodeID ID; 4352 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI, 4353 *this, true); 4354 4355 QualType Canonical; 4356 bool Unique = false; 4357 4358 void *InsertPos = nullptr; 4359 if (FunctionProtoType *FPT = 4360 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) { 4361 QualType Existing = QualType(FPT, 0); 4362 4363 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse 4364 // it so long as our exception specification doesn't contain a dependent 4365 // noexcept expression, or we're just looking for a canonical type. 4366 // Otherwise, we're going to need to create a type 4367 // sugar node to hold the concrete expression. 4368 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) || 4369 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr()) 4370 return Existing; 4371 4372 // We need a new type sugar node for this one, to hold the new noexcept 4373 // expression. We do no canonicalization here, but that's OK since we don't 4374 // expect to see the same noexcept expression much more than once. 4375 Canonical = getCanonicalType(Existing); 4376 Unique = true; 4377 } 4378 4379 bool NoexceptInType = getLangOpts().CPlusPlus17; 4380 bool IsCanonicalExceptionSpec = 4381 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType); 4382 4383 // Determine whether the type being created is already canonical or not. 4384 bool isCanonical = !Unique && IsCanonicalExceptionSpec && 4385 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn; 4386 for (unsigned i = 0; i != NumArgs && isCanonical; ++i) 4387 if (!ArgArray[i].isCanonicalAsParam()) 4388 isCanonical = false; 4389 4390 if (OnlyWantCanonical) 4391 assert(isCanonical && 4392 "given non-canonical parameters constructing canonical type"); 4393 4394 // If this type isn't canonical, get the canonical version of it if we don't 4395 // already have it. The exception spec is only partially part of the 4396 // canonical type, and only in C++17 onwards. 4397 if (!isCanonical && Canonical.isNull()) { 4398 SmallVector<QualType, 16> CanonicalArgs; 4399 CanonicalArgs.reserve(NumArgs); 4400 for (unsigned i = 0; i != NumArgs; ++i) 4401 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i])); 4402 4403 llvm::SmallVector<QualType, 8> ExceptionTypeStorage; 4404 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI; 4405 CanonicalEPI.HasTrailingReturn = false; 4406 4407 if (IsCanonicalExceptionSpec) { 4408 // Exception spec is already OK. 4409 } else if (NoexceptInType) { 4410 switch (EPI.ExceptionSpec.Type) { 4411 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated: 4412 // We don't know yet. It shouldn't matter what we pick here; no-one 4413 // should ever look at this. 4414 LLVM_FALLTHROUGH; 4415 case EST_None: case EST_MSAny: case EST_NoexceptFalse: 4416 CanonicalEPI.ExceptionSpec.Type = EST_None; 4417 break; 4418 4419 // A dynamic exception specification is almost always "not noexcept", 4420 // with the exception that a pack expansion might expand to no types. 4421 case EST_Dynamic: { 4422 bool AnyPacks = false; 4423 for (QualType ET : EPI.ExceptionSpec.Exceptions) { 4424 if (ET->getAs<PackExpansionType>()) 4425 AnyPacks = true; 4426 ExceptionTypeStorage.push_back(getCanonicalType(ET)); 4427 } 4428 if (!AnyPacks) 4429 CanonicalEPI.ExceptionSpec.Type = EST_None; 4430 else { 4431 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic; 4432 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage; 4433 } 4434 break; 4435 } 4436 4437 case EST_DynamicNone: 4438 case EST_BasicNoexcept: 4439 case EST_NoexceptTrue: 4440 case EST_NoThrow: 4441 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept; 4442 break; 4443 4444 case EST_DependentNoexcept: 4445 llvm_unreachable("dependent noexcept is already canonical"); 4446 } 4447 } else { 4448 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo(); 4449 } 4450 4451 // Adjust the canonical function result type. 4452 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy); 4453 Canonical = 4454 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true); 4455 4456 // Get the new insert position for the node we care about. 4457 FunctionProtoType *NewIP = 4458 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 4459 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4460 } 4461 4462 // Compute the needed size to hold this FunctionProtoType and the 4463 // various trailing objects. 4464 auto ESH = FunctionProtoType::getExceptionSpecSize( 4465 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size()); 4466 size_t Size = FunctionProtoType::totalSizeToAlloc< 4467 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields, 4468 FunctionType::ExceptionType, Expr *, FunctionDecl *, 4469 FunctionProtoType::ExtParameterInfo, Qualifiers>( 4470 NumArgs, EPI.Variadic, EPI.requiresFunctionProtoTypeExtraBitfields(), 4471 ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr, 4472 EPI.ExtParameterInfos ? NumArgs : 0, 4473 EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0); 4474 4475 auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment); 4476 FunctionProtoType::ExtProtoInfo newEPI = EPI; 4477 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI); 4478 Types.push_back(FTP); 4479 if (!Unique) 4480 FunctionProtoTypes.InsertNode(FTP, InsertPos); 4481 return QualType(FTP, 0); 4482 } 4483 4484 QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const { 4485 llvm::FoldingSetNodeID ID; 4486 PipeType::Profile(ID, T, ReadOnly); 4487 4488 void *InsertPos = nullptr; 4489 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos)) 4490 return QualType(PT, 0); 4491 4492 // If the pipe element type isn't canonical, this won't be a canonical type 4493 // either, so fill in the canonical type field. 4494 QualType Canonical; 4495 if (!T.isCanonical()) { 4496 Canonical = getPipeType(getCanonicalType(T), ReadOnly); 4497 4498 // Get the new insert position for the node we care about. 4499 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos); 4500 assert(!NewIP && "Shouldn't be in the map!"); 4501 (void)NewIP; 4502 } 4503 auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly); 4504 Types.push_back(New); 4505 PipeTypes.InsertNode(New, InsertPos); 4506 return QualType(New, 0); 4507 } 4508 4509 QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const { 4510 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 4511 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant) 4512 : Ty; 4513 } 4514 4515 QualType ASTContext::getReadPipeType(QualType T) const { 4516 return getPipeType(T, true); 4517 } 4518 4519 QualType ASTContext::getWritePipeType(QualType T) const { 4520 return getPipeType(T, false); 4521 } 4522 4523 QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const { 4524 llvm::FoldingSetNodeID ID; 4525 BitIntType::Profile(ID, IsUnsigned, NumBits); 4526 4527 void *InsertPos = nullptr; 4528 if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos)) 4529 return QualType(EIT, 0); 4530 4531 auto *New = new (*this, TypeAlignment) BitIntType(IsUnsigned, NumBits); 4532 BitIntTypes.InsertNode(New, InsertPos); 4533 Types.push_back(New); 4534 return QualType(New, 0); 4535 } 4536 4537 QualType ASTContext::getDependentBitIntType(bool IsUnsigned, 4538 Expr *NumBitsExpr) const { 4539 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent"); 4540 llvm::FoldingSetNodeID ID; 4541 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr); 4542 4543 void *InsertPos = nullptr; 4544 if (DependentBitIntType *Existing = 4545 DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos)) 4546 return QualType(Existing, 0); 4547 4548 auto *New = new (*this, TypeAlignment) 4549 DependentBitIntType(*this, IsUnsigned, NumBitsExpr); 4550 DependentBitIntTypes.InsertNode(New, InsertPos); 4551 4552 Types.push_back(New); 4553 return QualType(New, 0); 4554 } 4555 4556 #ifndef NDEBUG 4557 static bool NeedsInjectedClassNameType(const RecordDecl *D) { 4558 if (!isa<CXXRecordDecl>(D)) return false; 4559 const auto *RD = cast<CXXRecordDecl>(D); 4560 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) 4561 return true; 4562 if (RD->getDescribedClassTemplate() && 4563 !isa<ClassTemplateSpecializationDecl>(RD)) 4564 return true; 4565 return false; 4566 } 4567 #endif 4568 4569 /// getInjectedClassNameType - Return the unique reference to the 4570 /// injected class name type for the specified templated declaration. 4571 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl, 4572 QualType TST) const { 4573 assert(NeedsInjectedClassNameType(Decl)); 4574 if (Decl->TypeForDecl) { 4575 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 4576 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) { 4577 assert(PrevDecl->TypeForDecl && "previous declaration has no type"); 4578 Decl->TypeForDecl = PrevDecl->TypeForDecl; 4579 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 4580 } else { 4581 Type *newType = 4582 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST); 4583 Decl->TypeForDecl = newType; 4584 Types.push_back(newType); 4585 } 4586 return QualType(Decl->TypeForDecl, 0); 4587 } 4588 4589 /// getTypeDeclType - Return the unique reference to the type for the 4590 /// specified type declaration. 4591 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const { 4592 assert(Decl && "Passed null for Decl param"); 4593 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case"); 4594 4595 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl)) 4596 return getTypedefType(Typedef); 4597 4598 assert(!isa<TemplateTypeParmDecl>(Decl) && 4599 "Template type parameter types are always available."); 4600 4601 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) { 4602 assert(Record->isFirstDecl() && "struct/union has previous declaration"); 4603 assert(!NeedsInjectedClassNameType(Record)); 4604 return getRecordType(Record); 4605 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) { 4606 assert(Enum->isFirstDecl() && "enum has previous declaration"); 4607 return getEnumType(Enum); 4608 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) { 4609 return getUnresolvedUsingType(Using); 4610 } else 4611 llvm_unreachable("TypeDecl without a type?"); 4612 4613 return QualType(Decl->TypeForDecl, 0); 4614 } 4615 4616 /// getTypedefType - Return the unique reference to the type for the 4617 /// specified typedef name decl. 4618 QualType ASTContext::getTypedefType(const TypedefNameDecl *Decl, 4619 QualType Underlying) const { 4620 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 4621 4622 if (Underlying.isNull()) 4623 Underlying = Decl->getUnderlyingType(); 4624 QualType Canonical = getCanonicalType(Underlying); 4625 auto *newType = new (*this, TypeAlignment) 4626 TypedefType(Type::Typedef, Decl, Underlying, Canonical); 4627 Decl->TypeForDecl = newType; 4628 Types.push_back(newType); 4629 return QualType(newType, 0); 4630 } 4631 4632 QualType ASTContext::getUsingType(const UsingShadowDecl *Found, 4633 QualType Underlying) const { 4634 llvm::FoldingSetNodeID ID; 4635 UsingType::Profile(ID, Found); 4636 4637 void *InsertPos = nullptr; 4638 UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos); 4639 if (T) 4640 return QualType(T, 0); 4641 4642 assert(!Underlying.hasLocalQualifiers()); 4643 assert(Underlying == getTypeDeclType(cast<TypeDecl>(Found->getTargetDecl()))); 4644 QualType Canon = Underlying.getCanonicalType(); 4645 4646 UsingType *NewType = 4647 new (*this, TypeAlignment) UsingType(Found, Underlying, Canon); 4648 Types.push_back(NewType); 4649 UsingTypes.InsertNode(NewType, InsertPos); 4650 return QualType(NewType, 0); 4651 } 4652 4653 QualType ASTContext::getRecordType(const RecordDecl *Decl) const { 4654 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 4655 4656 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl()) 4657 if (PrevDecl->TypeForDecl) 4658 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 4659 4660 auto *newType = new (*this, TypeAlignment) RecordType(Decl); 4661 Decl->TypeForDecl = newType; 4662 Types.push_back(newType); 4663 return QualType(newType, 0); 4664 } 4665 4666 QualType ASTContext::getEnumType(const EnumDecl *Decl) const { 4667 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 4668 4669 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl()) 4670 if (PrevDecl->TypeForDecl) 4671 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 4672 4673 auto *newType = new (*this, TypeAlignment) EnumType(Decl); 4674 Decl->TypeForDecl = newType; 4675 Types.push_back(newType); 4676 return QualType(newType, 0); 4677 } 4678 4679 QualType ASTContext::getUnresolvedUsingType( 4680 const UnresolvedUsingTypenameDecl *Decl) const { 4681 if (Decl->TypeForDecl) 4682 return QualType(Decl->TypeForDecl, 0); 4683 4684 if (const UnresolvedUsingTypenameDecl *CanonicalDecl = 4685 Decl->getCanonicalDecl()) 4686 if (CanonicalDecl->TypeForDecl) 4687 return QualType(Decl->TypeForDecl = CanonicalDecl->TypeForDecl, 0); 4688 4689 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Decl); 4690 Decl->TypeForDecl = newType; 4691 Types.push_back(newType); 4692 return QualType(newType, 0); 4693 } 4694 4695 QualType ASTContext::getAttributedType(attr::Kind attrKind, 4696 QualType modifiedType, 4697 QualType equivalentType) { 4698 llvm::FoldingSetNodeID id; 4699 AttributedType::Profile(id, attrKind, modifiedType, equivalentType); 4700 4701 void *insertPos = nullptr; 4702 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos); 4703 if (type) return QualType(type, 0); 4704 4705 QualType canon = getCanonicalType(equivalentType); 4706 type = new (*this, TypeAlignment) 4707 AttributedType(canon, attrKind, modifiedType, equivalentType); 4708 4709 Types.push_back(type); 4710 AttributedTypes.InsertNode(type, insertPos); 4711 4712 return QualType(type, 0); 4713 } 4714 4715 QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr, 4716 QualType Wrapped) { 4717 llvm::FoldingSetNodeID ID; 4718 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr); 4719 4720 void *InsertPos = nullptr; 4721 BTFTagAttributedType *Ty = 4722 BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos); 4723 if (Ty) 4724 return QualType(Ty, 0); 4725 4726 QualType Canon = getCanonicalType(Wrapped); 4727 Ty = new (*this, TypeAlignment) BTFTagAttributedType(Canon, Wrapped, BTFAttr); 4728 4729 Types.push_back(Ty); 4730 BTFTagAttributedTypes.InsertNode(Ty, InsertPos); 4731 4732 return QualType(Ty, 0); 4733 } 4734 4735 /// Retrieve a substitution-result type. 4736 QualType 4737 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm, 4738 QualType Replacement) const { 4739 assert(Replacement.isCanonical() 4740 && "replacement types must always be canonical"); 4741 4742 llvm::FoldingSetNodeID ID; 4743 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement); 4744 void *InsertPos = nullptr; 4745 SubstTemplateTypeParmType *SubstParm 4746 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 4747 4748 if (!SubstParm) { 4749 SubstParm = new (*this, TypeAlignment) 4750 SubstTemplateTypeParmType(Parm, Replacement); 4751 Types.push_back(SubstParm); 4752 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos); 4753 } 4754 4755 return QualType(SubstParm, 0); 4756 } 4757 4758 /// Retrieve a 4759 QualType ASTContext::getSubstTemplateTypeParmPackType( 4760 const TemplateTypeParmType *Parm, 4761 const TemplateArgument &ArgPack) { 4762 #ifndef NDEBUG 4763 for (const auto &P : ArgPack.pack_elements()) { 4764 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type"); 4765 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type"); 4766 } 4767 #endif 4768 4769 llvm::FoldingSetNodeID ID; 4770 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack); 4771 void *InsertPos = nullptr; 4772 if (SubstTemplateTypeParmPackType *SubstParm 4773 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos)) 4774 return QualType(SubstParm, 0); 4775 4776 QualType Canon; 4777 if (!Parm->isCanonicalUnqualified()) { 4778 Canon = getCanonicalType(QualType(Parm, 0)); 4779 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon), 4780 ArgPack); 4781 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos); 4782 } 4783 4784 auto *SubstParm 4785 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon, 4786 ArgPack); 4787 Types.push_back(SubstParm); 4788 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos); 4789 return QualType(SubstParm, 0); 4790 } 4791 4792 /// Retrieve the template type parameter type for a template 4793 /// parameter or parameter pack with the given depth, index, and (optionally) 4794 /// name. 4795 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index, 4796 bool ParameterPack, 4797 TemplateTypeParmDecl *TTPDecl) const { 4798 llvm::FoldingSetNodeID ID; 4799 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl); 4800 void *InsertPos = nullptr; 4801 TemplateTypeParmType *TypeParm 4802 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 4803 4804 if (TypeParm) 4805 return QualType(TypeParm, 0); 4806 4807 if (TTPDecl) { 4808 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack); 4809 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon); 4810 4811 TemplateTypeParmType *TypeCheck 4812 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 4813 assert(!TypeCheck && "Template type parameter canonical type broken"); 4814 (void)TypeCheck; 4815 } else 4816 TypeParm = new (*this, TypeAlignment) 4817 TemplateTypeParmType(Depth, Index, ParameterPack); 4818 4819 Types.push_back(TypeParm); 4820 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos); 4821 4822 return QualType(TypeParm, 0); 4823 } 4824 4825 TypeSourceInfo * 4826 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name, 4827 SourceLocation NameLoc, 4828 const TemplateArgumentListInfo &Args, 4829 QualType Underlying) const { 4830 assert(!Name.getAsDependentTemplateName() && 4831 "No dependent template names here!"); 4832 QualType TST = getTemplateSpecializationType(Name, Args, Underlying); 4833 4834 TypeSourceInfo *DI = CreateTypeSourceInfo(TST); 4835 TemplateSpecializationTypeLoc TL = 4836 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>(); 4837 TL.setTemplateKeywordLoc(SourceLocation()); 4838 TL.setTemplateNameLoc(NameLoc); 4839 TL.setLAngleLoc(Args.getLAngleLoc()); 4840 TL.setRAngleLoc(Args.getRAngleLoc()); 4841 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 4842 TL.setArgLocInfo(i, Args[i].getLocInfo()); 4843 return DI; 4844 } 4845 4846 QualType 4847 ASTContext::getTemplateSpecializationType(TemplateName Template, 4848 const TemplateArgumentListInfo &Args, 4849 QualType Underlying) const { 4850 assert(!Template.getAsDependentTemplateName() && 4851 "No dependent template names here!"); 4852 4853 SmallVector<TemplateArgument, 4> ArgVec; 4854 ArgVec.reserve(Args.size()); 4855 for (const TemplateArgumentLoc &Arg : Args.arguments()) 4856 ArgVec.push_back(Arg.getArgument()); 4857 4858 return getTemplateSpecializationType(Template, ArgVec, Underlying); 4859 } 4860 4861 #ifndef NDEBUG 4862 static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) { 4863 for (const TemplateArgument &Arg : Args) 4864 if (Arg.isPackExpansion()) 4865 return true; 4866 4867 return true; 4868 } 4869 #endif 4870 4871 QualType 4872 ASTContext::getTemplateSpecializationType(TemplateName Template, 4873 ArrayRef<TemplateArgument> Args, 4874 QualType Underlying) const { 4875 assert(!Template.getAsDependentTemplateName() && 4876 "No dependent template names here!"); 4877 // Look through qualified template names. 4878 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 4879 Template = QTN->getUnderlyingTemplate(); 4880 4881 bool IsTypeAlias = 4882 isa_and_nonnull<TypeAliasTemplateDecl>(Template.getAsTemplateDecl()); 4883 QualType CanonType; 4884 if (!Underlying.isNull()) 4885 CanonType = getCanonicalType(Underlying); 4886 else { 4887 // We can get here with an alias template when the specialization contains 4888 // a pack expansion that does not match up with a parameter pack. 4889 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) && 4890 "Caller must compute aliased type"); 4891 IsTypeAlias = false; 4892 CanonType = getCanonicalTemplateSpecializationType(Template, Args); 4893 } 4894 4895 // Allocate the (non-canonical) template specialization type, but don't 4896 // try to unique it: these types typically have location information that 4897 // we don't unique and don't want to lose. 4898 void *Mem = Allocate(sizeof(TemplateSpecializationType) + 4899 sizeof(TemplateArgument) * Args.size() + 4900 (IsTypeAlias? sizeof(QualType) : 0), 4901 TypeAlignment); 4902 auto *Spec 4903 = new (Mem) TemplateSpecializationType(Template, Args, CanonType, 4904 IsTypeAlias ? Underlying : QualType()); 4905 4906 Types.push_back(Spec); 4907 return QualType(Spec, 0); 4908 } 4909 4910 static bool 4911 getCanonicalTemplateArguments(const ASTContext &C, 4912 ArrayRef<TemplateArgument> OrigArgs, 4913 SmallVectorImpl<TemplateArgument> &CanonArgs) { 4914 bool AnyNonCanonArgs = false; 4915 unsigned NumArgs = OrigArgs.size(); 4916 CanonArgs.resize(NumArgs); 4917 for (unsigned I = 0; I != NumArgs; ++I) { 4918 const TemplateArgument &OrigArg = OrigArgs[I]; 4919 TemplateArgument &CanonArg = CanonArgs[I]; 4920 CanonArg = C.getCanonicalTemplateArgument(OrigArg); 4921 if (!CanonArg.structurallyEquals(OrigArg)) 4922 AnyNonCanonArgs = true; 4923 } 4924 return AnyNonCanonArgs; 4925 } 4926 4927 QualType ASTContext::getCanonicalTemplateSpecializationType( 4928 TemplateName Template, ArrayRef<TemplateArgument> Args) const { 4929 assert(!Template.getAsDependentTemplateName() && 4930 "No dependent template names here!"); 4931 4932 // Look through qualified template names. 4933 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 4934 Template = TemplateName(QTN->getUnderlyingTemplate()); 4935 4936 // Build the canonical template specialization type. 4937 TemplateName CanonTemplate = getCanonicalTemplateName(Template); 4938 SmallVector<TemplateArgument, 4> CanonArgs; 4939 ::getCanonicalTemplateArguments(*this, Args, CanonArgs); 4940 4941 // Determine whether this canonical template specialization type already 4942 // exists. 4943 llvm::FoldingSetNodeID ID; 4944 TemplateSpecializationType::Profile(ID, CanonTemplate, 4945 CanonArgs, *this); 4946 4947 void *InsertPos = nullptr; 4948 TemplateSpecializationType *Spec 4949 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 4950 4951 if (!Spec) { 4952 // Allocate a new canonical template specialization type. 4953 void *Mem = Allocate((sizeof(TemplateSpecializationType) + 4954 sizeof(TemplateArgument) * CanonArgs.size()), 4955 TypeAlignment); 4956 Spec = new (Mem) TemplateSpecializationType(CanonTemplate, 4957 CanonArgs, 4958 QualType(), QualType()); 4959 Types.push_back(Spec); 4960 TemplateSpecializationTypes.InsertNode(Spec, InsertPos); 4961 } 4962 4963 assert(Spec->isDependentType() && 4964 "Non-dependent template-id type must have a canonical type"); 4965 return QualType(Spec, 0); 4966 } 4967 4968 QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword, 4969 NestedNameSpecifier *NNS, 4970 QualType NamedType, 4971 TagDecl *OwnedTagDecl) const { 4972 llvm::FoldingSetNodeID ID; 4973 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl); 4974 4975 void *InsertPos = nullptr; 4976 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 4977 if (T) 4978 return QualType(T, 0); 4979 4980 QualType Canon = NamedType; 4981 if (!Canon.isCanonical()) { 4982 Canon = getCanonicalType(NamedType); 4983 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 4984 assert(!CheckT && "Elaborated canonical type broken"); 4985 (void)CheckT; 4986 } 4987 4988 void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl), 4989 TypeAlignment); 4990 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl); 4991 4992 Types.push_back(T); 4993 ElaboratedTypes.InsertNode(T, InsertPos); 4994 return QualType(T, 0); 4995 } 4996 4997 QualType 4998 ASTContext::getParenType(QualType InnerType) const { 4999 llvm::FoldingSetNodeID ID; 5000 ParenType::Profile(ID, InnerType); 5001 5002 void *InsertPos = nullptr; 5003 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 5004 if (T) 5005 return QualType(T, 0); 5006 5007 QualType Canon = InnerType; 5008 if (!Canon.isCanonical()) { 5009 Canon = getCanonicalType(InnerType); 5010 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 5011 assert(!CheckT && "Paren canonical type broken"); 5012 (void)CheckT; 5013 } 5014 5015 T = new (*this, TypeAlignment) ParenType(InnerType, Canon); 5016 Types.push_back(T); 5017 ParenTypes.InsertNode(T, InsertPos); 5018 return QualType(T, 0); 5019 } 5020 5021 QualType 5022 ASTContext::getMacroQualifiedType(QualType UnderlyingTy, 5023 const IdentifierInfo *MacroII) const { 5024 QualType Canon = UnderlyingTy; 5025 if (!Canon.isCanonical()) 5026 Canon = getCanonicalType(UnderlyingTy); 5027 5028 auto *newType = new (*this, TypeAlignment) 5029 MacroQualifiedType(UnderlyingTy, Canon, MacroII); 5030 Types.push_back(newType); 5031 return QualType(newType, 0); 5032 } 5033 5034 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword, 5035 NestedNameSpecifier *NNS, 5036 const IdentifierInfo *Name, 5037 QualType Canon) const { 5038 if (Canon.isNull()) { 5039 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 5040 if (CanonNNS != NNS) 5041 Canon = getDependentNameType(Keyword, CanonNNS, Name); 5042 } 5043 5044 llvm::FoldingSetNodeID ID; 5045 DependentNameType::Profile(ID, Keyword, NNS, Name); 5046 5047 void *InsertPos = nullptr; 5048 DependentNameType *T 5049 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos); 5050 if (T) 5051 return QualType(T, 0); 5052 5053 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon); 5054 Types.push_back(T); 5055 DependentNameTypes.InsertNode(T, InsertPos); 5056 return QualType(T, 0); 5057 } 5058 5059 QualType 5060 ASTContext::getDependentTemplateSpecializationType( 5061 ElaboratedTypeKeyword Keyword, 5062 NestedNameSpecifier *NNS, 5063 const IdentifierInfo *Name, 5064 const TemplateArgumentListInfo &Args) const { 5065 // TODO: avoid this copy 5066 SmallVector<TemplateArgument, 16> ArgCopy; 5067 for (unsigned I = 0, E = Args.size(); I != E; ++I) 5068 ArgCopy.push_back(Args[I].getArgument()); 5069 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy); 5070 } 5071 5072 QualType 5073 ASTContext::getDependentTemplateSpecializationType( 5074 ElaboratedTypeKeyword Keyword, 5075 NestedNameSpecifier *NNS, 5076 const IdentifierInfo *Name, 5077 ArrayRef<TemplateArgument> Args) const { 5078 assert((!NNS || NNS->isDependent()) && 5079 "nested-name-specifier must be dependent"); 5080 5081 llvm::FoldingSetNodeID ID; 5082 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS, 5083 Name, Args); 5084 5085 void *InsertPos = nullptr; 5086 DependentTemplateSpecializationType *T 5087 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 5088 if (T) 5089 return QualType(T, 0); 5090 5091 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 5092 5093 ElaboratedTypeKeyword CanonKeyword = Keyword; 5094 if (Keyword == ETK_None) CanonKeyword = ETK_Typename; 5095 5096 SmallVector<TemplateArgument, 16> CanonArgs; 5097 bool AnyNonCanonArgs = 5098 ::getCanonicalTemplateArguments(*this, Args, CanonArgs); 5099 5100 QualType Canon; 5101 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) { 5102 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS, 5103 Name, 5104 CanonArgs); 5105 5106 // Find the insert position again. 5107 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 5108 } 5109 5110 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) + 5111 sizeof(TemplateArgument) * Args.size()), 5112 TypeAlignment); 5113 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS, 5114 Name, Args, Canon); 5115 Types.push_back(T); 5116 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos); 5117 return QualType(T, 0); 5118 } 5119 5120 TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) { 5121 TemplateArgument Arg; 5122 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) { 5123 QualType ArgType = getTypeDeclType(TTP); 5124 if (TTP->isParameterPack()) 5125 ArgType = getPackExpansionType(ArgType, None); 5126 5127 Arg = TemplateArgument(ArgType); 5128 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 5129 QualType T = 5130 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this); 5131 // For class NTTPs, ensure we include the 'const' so the type matches that 5132 // of a real template argument. 5133 // FIXME: It would be more faithful to model this as something like an 5134 // lvalue-to-rvalue conversion applied to a const-qualified lvalue. 5135 if (T->isRecordType()) 5136 T.addConst(); 5137 Expr *E = new (*this) DeclRefExpr( 5138 *this, NTTP, /*enclosing*/ false, T, 5139 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation()); 5140 5141 if (NTTP->isParameterPack()) 5142 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(), 5143 None); 5144 Arg = TemplateArgument(E); 5145 } else { 5146 auto *TTP = cast<TemplateTemplateParmDecl>(Param); 5147 if (TTP->isParameterPack()) 5148 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>()); 5149 else 5150 Arg = TemplateArgument(TemplateName(TTP)); 5151 } 5152 5153 if (Param->isTemplateParameterPack()) 5154 Arg = TemplateArgument::CreatePackCopy(*this, Arg); 5155 5156 return Arg; 5157 } 5158 5159 void 5160 ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params, 5161 SmallVectorImpl<TemplateArgument> &Args) { 5162 Args.reserve(Args.size() + Params->size()); 5163 5164 for (NamedDecl *Param : *Params) 5165 Args.push_back(getInjectedTemplateArg(Param)); 5166 } 5167 5168 QualType ASTContext::getPackExpansionType(QualType Pattern, 5169 Optional<unsigned> NumExpansions, 5170 bool ExpectPackInType) { 5171 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) && 5172 "Pack expansions must expand one or more parameter packs"); 5173 5174 llvm::FoldingSetNodeID ID; 5175 PackExpansionType::Profile(ID, Pattern, NumExpansions); 5176 5177 void *InsertPos = nullptr; 5178 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 5179 if (T) 5180 return QualType(T, 0); 5181 5182 QualType Canon; 5183 if (!Pattern.isCanonical()) { 5184 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions, 5185 /*ExpectPackInType=*/false); 5186 5187 // Find the insert position again, in case we inserted an element into 5188 // PackExpansionTypes and invalidated our insert position. 5189 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 5190 } 5191 5192 T = new (*this, TypeAlignment) 5193 PackExpansionType(Pattern, Canon, NumExpansions); 5194 Types.push_back(T); 5195 PackExpansionTypes.InsertNode(T, InsertPos); 5196 return QualType(T, 0); 5197 } 5198 5199 /// CmpProtocolNames - Comparison predicate for sorting protocols 5200 /// alphabetically. 5201 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS, 5202 ObjCProtocolDecl *const *RHS) { 5203 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName()); 5204 } 5205 5206 static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) { 5207 if (Protocols.empty()) return true; 5208 5209 if (Protocols[0]->getCanonicalDecl() != Protocols[0]) 5210 return false; 5211 5212 for (unsigned i = 1; i != Protocols.size(); ++i) 5213 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 || 5214 Protocols[i]->getCanonicalDecl() != Protocols[i]) 5215 return false; 5216 return true; 5217 } 5218 5219 static void 5220 SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) { 5221 // Sort protocols, keyed by name. 5222 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames); 5223 5224 // Canonicalize. 5225 for (ObjCProtocolDecl *&P : Protocols) 5226 P = P->getCanonicalDecl(); 5227 5228 // Remove duplicates. 5229 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end()); 5230 Protocols.erase(ProtocolsEnd, Protocols.end()); 5231 } 5232 5233 QualType ASTContext::getObjCObjectType(QualType BaseType, 5234 ObjCProtocolDecl * const *Protocols, 5235 unsigned NumProtocols) const { 5236 return getObjCObjectType(BaseType, {}, 5237 llvm::makeArrayRef(Protocols, NumProtocols), 5238 /*isKindOf=*/false); 5239 } 5240 5241 QualType ASTContext::getObjCObjectType( 5242 QualType baseType, 5243 ArrayRef<QualType> typeArgs, 5244 ArrayRef<ObjCProtocolDecl *> protocols, 5245 bool isKindOf) const { 5246 // If the base type is an interface and there aren't any protocols or 5247 // type arguments to add, then the interface type will do just fine. 5248 if (typeArgs.empty() && protocols.empty() && !isKindOf && 5249 isa<ObjCInterfaceType>(baseType)) 5250 return baseType; 5251 5252 // Look in the folding set for an existing type. 5253 llvm::FoldingSetNodeID ID; 5254 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf); 5255 void *InsertPos = nullptr; 5256 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos)) 5257 return QualType(QT, 0); 5258 5259 // Determine the type arguments to be used for canonicalization, 5260 // which may be explicitly specified here or written on the base 5261 // type. 5262 ArrayRef<QualType> effectiveTypeArgs = typeArgs; 5263 if (effectiveTypeArgs.empty()) { 5264 if (const auto *baseObject = baseType->getAs<ObjCObjectType>()) 5265 effectiveTypeArgs = baseObject->getTypeArgs(); 5266 } 5267 5268 // Build the canonical type, which has the canonical base type and a 5269 // sorted-and-uniqued list of protocols and the type arguments 5270 // canonicalized. 5271 QualType canonical; 5272 bool typeArgsAreCanonical = llvm::all_of( 5273 effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); }); 5274 bool protocolsSorted = areSortedAndUniqued(protocols); 5275 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) { 5276 // Determine the canonical type arguments. 5277 ArrayRef<QualType> canonTypeArgs; 5278 SmallVector<QualType, 4> canonTypeArgsVec; 5279 if (!typeArgsAreCanonical) { 5280 canonTypeArgsVec.reserve(effectiveTypeArgs.size()); 5281 for (auto typeArg : effectiveTypeArgs) 5282 canonTypeArgsVec.push_back(getCanonicalType(typeArg)); 5283 canonTypeArgs = canonTypeArgsVec; 5284 } else { 5285 canonTypeArgs = effectiveTypeArgs; 5286 } 5287 5288 ArrayRef<ObjCProtocolDecl *> canonProtocols; 5289 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec; 5290 if (!protocolsSorted) { 5291 canonProtocolsVec.append(protocols.begin(), protocols.end()); 5292 SortAndUniqueProtocols(canonProtocolsVec); 5293 canonProtocols = canonProtocolsVec; 5294 } else { 5295 canonProtocols = protocols; 5296 } 5297 5298 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs, 5299 canonProtocols, isKindOf); 5300 5301 // Regenerate InsertPos. 5302 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos); 5303 } 5304 5305 unsigned size = sizeof(ObjCObjectTypeImpl); 5306 size += typeArgs.size() * sizeof(QualType); 5307 size += protocols.size() * sizeof(ObjCProtocolDecl *); 5308 void *mem = Allocate(size, TypeAlignment); 5309 auto *T = 5310 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols, 5311 isKindOf); 5312 5313 Types.push_back(T); 5314 ObjCObjectTypes.InsertNode(T, InsertPos); 5315 return QualType(T, 0); 5316 } 5317 5318 /// Apply Objective-C protocol qualifiers to the given type. 5319 /// If this is for the canonical type of a type parameter, we can apply 5320 /// protocol qualifiers on the ObjCObjectPointerType. 5321 QualType 5322 ASTContext::applyObjCProtocolQualifiers(QualType type, 5323 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError, 5324 bool allowOnPointerType) const { 5325 hasError = false; 5326 5327 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) { 5328 return getObjCTypeParamType(objT->getDecl(), protocols); 5329 } 5330 5331 // Apply protocol qualifiers to ObjCObjectPointerType. 5332 if (allowOnPointerType) { 5333 if (const auto *objPtr = 5334 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) { 5335 const ObjCObjectType *objT = objPtr->getObjectType(); 5336 // Merge protocol lists and construct ObjCObjectType. 5337 SmallVector<ObjCProtocolDecl*, 8> protocolsVec; 5338 protocolsVec.append(objT->qual_begin(), 5339 objT->qual_end()); 5340 protocolsVec.append(protocols.begin(), protocols.end()); 5341 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec; 5342 type = getObjCObjectType( 5343 objT->getBaseType(), 5344 objT->getTypeArgsAsWritten(), 5345 protocols, 5346 objT->isKindOfTypeAsWritten()); 5347 return getObjCObjectPointerType(type); 5348 } 5349 } 5350 5351 // Apply protocol qualifiers to ObjCObjectType. 5352 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){ 5353 // FIXME: Check for protocols to which the class type is already 5354 // known to conform. 5355 5356 return getObjCObjectType(objT->getBaseType(), 5357 objT->getTypeArgsAsWritten(), 5358 protocols, 5359 objT->isKindOfTypeAsWritten()); 5360 } 5361 5362 // If the canonical type is ObjCObjectType, ... 5363 if (type->isObjCObjectType()) { 5364 // Silently overwrite any existing protocol qualifiers. 5365 // TODO: determine whether that's the right thing to do. 5366 5367 // FIXME: Check for protocols to which the class type is already 5368 // known to conform. 5369 return getObjCObjectType(type, {}, protocols, false); 5370 } 5371 5372 // id<protocol-list> 5373 if (type->isObjCIdType()) { 5374 const auto *objPtr = type->castAs<ObjCObjectPointerType>(); 5375 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols, 5376 objPtr->isKindOfType()); 5377 return getObjCObjectPointerType(type); 5378 } 5379 5380 // Class<protocol-list> 5381 if (type->isObjCClassType()) { 5382 const auto *objPtr = type->castAs<ObjCObjectPointerType>(); 5383 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols, 5384 objPtr->isKindOfType()); 5385 return getObjCObjectPointerType(type); 5386 } 5387 5388 hasError = true; 5389 return type; 5390 } 5391 5392 QualType 5393 ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl, 5394 ArrayRef<ObjCProtocolDecl *> protocols) const { 5395 // Look in the folding set for an existing type. 5396 llvm::FoldingSetNodeID ID; 5397 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols); 5398 void *InsertPos = nullptr; 5399 if (ObjCTypeParamType *TypeParam = 5400 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos)) 5401 return QualType(TypeParam, 0); 5402 5403 // We canonicalize to the underlying type. 5404 QualType Canonical = getCanonicalType(Decl->getUnderlyingType()); 5405 if (!protocols.empty()) { 5406 // Apply the protocol qualifers. 5407 bool hasError; 5408 Canonical = getCanonicalType(applyObjCProtocolQualifiers( 5409 Canonical, protocols, hasError, true /*allowOnPointerType*/)); 5410 assert(!hasError && "Error when apply protocol qualifier to bound type"); 5411 } 5412 5413 unsigned size = sizeof(ObjCTypeParamType); 5414 size += protocols.size() * sizeof(ObjCProtocolDecl *); 5415 void *mem = Allocate(size, TypeAlignment); 5416 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols); 5417 5418 Types.push_back(newType); 5419 ObjCTypeParamTypes.InsertNode(newType, InsertPos); 5420 return QualType(newType, 0); 5421 } 5422 5423 void ASTContext::adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig, 5424 ObjCTypeParamDecl *New) const { 5425 New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType())); 5426 // Update TypeForDecl after updating TypeSourceInfo. 5427 auto NewTypeParamTy = cast<ObjCTypeParamType>(New->getTypeForDecl()); 5428 SmallVector<ObjCProtocolDecl *, 8> protocols; 5429 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end()); 5430 QualType UpdatedTy = getObjCTypeParamType(New, protocols); 5431 New->setTypeForDecl(UpdatedTy.getTypePtr()); 5432 } 5433 5434 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's 5435 /// protocol list adopt all protocols in QT's qualified-id protocol 5436 /// list. 5437 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT, 5438 ObjCInterfaceDecl *IC) { 5439 if (!QT->isObjCQualifiedIdType()) 5440 return false; 5441 5442 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) { 5443 // If both the right and left sides have qualifiers. 5444 for (auto *Proto : OPT->quals()) { 5445 if (!IC->ClassImplementsProtocol(Proto, false)) 5446 return false; 5447 } 5448 return true; 5449 } 5450 return false; 5451 } 5452 5453 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in 5454 /// QT's qualified-id protocol list adopt all protocols in IDecl's list 5455 /// of protocols. 5456 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT, 5457 ObjCInterfaceDecl *IDecl) { 5458 if (!QT->isObjCQualifiedIdType()) 5459 return false; 5460 const auto *OPT = QT->getAs<ObjCObjectPointerType>(); 5461 if (!OPT) 5462 return false; 5463 if (!IDecl->hasDefinition()) 5464 return false; 5465 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols; 5466 CollectInheritedProtocols(IDecl, InheritedProtocols); 5467 if (InheritedProtocols.empty()) 5468 return false; 5469 // Check that if every protocol in list of id<plist> conforms to a protocol 5470 // of IDecl's, then bridge casting is ok. 5471 bool Conforms = false; 5472 for (auto *Proto : OPT->quals()) { 5473 Conforms = false; 5474 for (auto *PI : InheritedProtocols) { 5475 if (ProtocolCompatibleWithProtocol(Proto, PI)) { 5476 Conforms = true; 5477 break; 5478 } 5479 } 5480 if (!Conforms) 5481 break; 5482 } 5483 if (Conforms) 5484 return true; 5485 5486 for (auto *PI : InheritedProtocols) { 5487 // If both the right and left sides have qualifiers. 5488 bool Adopts = false; 5489 for (auto *Proto : OPT->quals()) { 5490 // return 'true' if 'PI' is in the inheritance hierarchy of Proto 5491 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto))) 5492 break; 5493 } 5494 if (!Adopts) 5495 return false; 5496 } 5497 return true; 5498 } 5499 5500 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for 5501 /// the given object type. 5502 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const { 5503 llvm::FoldingSetNodeID ID; 5504 ObjCObjectPointerType::Profile(ID, ObjectT); 5505 5506 void *InsertPos = nullptr; 5507 if (ObjCObjectPointerType *QT = 5508 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 5509 return QualType(QT, 0); 5510 5511 // Find the canonical object type. 5512 QualType Canonical; 5513 if (!ObjectT.isCanonical()) { 5514 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT)); 5515 5516 // Regenerate InsertPos. 5517 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 5518 } 5519 5520 // No match. 5521 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment); 5522 auto *QType = 5523 new (Mem) ObjCObjectPointerType(Canonical, ObjectT); 5524 5525 Types.push_back(QType); 5526 ObjCObjectPointerTypes.InsertNode(QType, InsertPos); 5527 return QualType(QType, 0); 5528 } 5529 5530 /// getObjCInterfaceType - Return the unique reference to the type for the 5531 /// specified ObjC interface decl. The list of protocols is optional. 5532 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl, 5533 ObjCInterfaceDecl *PrevDecl) const { 5534 if (Decl->TypeForDecl) 5535 return QualType(Decl->TypeForDecl, 0); 5536 5537 if (PrevDecl) { 5538 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl"); 5539 Decl->TypeForDecl = PrevDecl->TypeForDecl; 5540 return QualType(PrevDecl->TypeForDecl, 0); 5541 } 5542 5543 // Prefer the definition, if there is one. 5544 if (const ObjCInterfaceDecl *Def = Decl->getDefinition()) 5545 Decl = Def; 5546 5547 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment); 5548 auto *T = new (Mem) ObjCInterfaceType(Decl); 5549 Decl->TypeForDecl = T; 5550 Types.push_back(T); 5551 return QualType(T, 0); 5552 } 5553 5554 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique 5555 /// TypeOfExprType AST's (since expression's are never shared). For example, 5556 /// multiple declarations that refer to "typeof(x)" all contain different 5557 /// DeclRefExpr's. This doesn't effect the type checker, since it operates 5558 /// on canonical type's (which are always unique). 5559 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const { 5560 TypeOfExprType *toe; 5561 if (tofExpr->isTypeDependent()) { 5562 llvm::FoldingSetNodeID ID; 5563 DependentTypeOfExprType::Profile(ID, *this, tofExpr); 5564 5565 void *InsertPos = nullptr; 5566 DependentTypeOfExprType *Canon 5567 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos); 5568 if (Canon) { 5569 // We already have a "canonical" version of an identical, dependent 5570 // typeof(expr) type. Use that as our canonical type. 5571 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, 5572 QualType((TypeOfExprType*)Canon, 0)); 5573 } else { 5574 // Build a new, canonical typeof(expr) type. 5575 Canon 5576 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr); 5577 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos); 5578 toe = Canon; 5579 } 5580 } else { 5581 QualType Canonical = getCanonicalType(tofExpr->getType()); 5582 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical); 5583 } 5584 Types.push_back(toe); 5585 return QualType(toe, 0); 5586 } 5587 5588 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique 5589 /// TypeOfType nodes. The only motivation to unique these nodes would be 5590 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be 5591 /// an issue. This doesn't affect the type checker, since it operates 5592 /// on canonical types (which are always unique). 5593 QualType ASTContext::getTypeOfType(QualType tofType) const { 5594 QualType Canonical = getCanonicalType(tofType); 5595 auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical); 5596 Types.push_back(tot); 5597 return QualType(tot, 0); 5598 } 5599 5600 /// getReferenceQualifiedType - Given an expr, will return the type for 5601 /// that expression, as in [dcl.type.simple]p4 but without taking id-expressions 5602 /// and class member access into account. 5603 QualType ASTContext::getReferenceQualifiedType(const Expr *E) const { 5604 // C++11 [dcl.type.simple]p4: 5605 // [...] 5606 QualType T = E->getType(); 5607 switch (E->getValueKind()) { 5608 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the 5609 // type of e; 5610 case VK_XValue: 5611 return getRValueReferenceType(T); 5612 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the 5613 // type of e; 5614 case VK_LValue: 5615 return getLValueReferenceType(T); 5616 // - otherwise, decltype(e) is the type of e. 5617 case VK_PRValue: 5618 return T; 5619 } 5620 llvm_unreachable("Unknown value kind"); 5621 } 5622 5623 /// Unlike many "get<Type>" functions, we don't unique DecltypeType 5624 /// nodes. This would never be helpful, since each such type has its own 5625 /// expression, and would not give a significant memory saving, since there 5626 /// is an Expr tree under each such type. 5627 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const { 5628 DecltypeType *dt; 5629 5630 // C++11 [temp.type]p2: 5631 // If an expression e involves a template parameter, decltype(e) denotes a 5632 // unique dependent type. Two such decltype-specifiers refer to the same 5633 // type only if their expressions are equivalent (14.5.6.1). 5634 if (e->isInstantiationDependent()) { 5635 llvm::FoldingSetNodeID ID; 5636 DependentDecltypeType::Profile(ID, *this, e); 5637 5638 void *InsertPos = nullptr; 5639 DependentDecltypeType *Canon 5640 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos); 5641 if (!Canon) { 5642 // Build a new, canonical decltype(expr) type. 5643 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e); 5644 DependentDecltypeTypes.InsertNode(Canon, InsertPos); 5645 } 5646 dt = new (*this, TypeAlignment) 5647 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0)); 5648 } else { 5649 dt = new (*this, TypeAlignment) 5650 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType)); 5651 } 5652 Types.push_back(dt); 5653 return QualType(dt, 0); 5654 } 5655 5656 /// getUnaryTransformationType - We don't unique these, since the memory 5657 /// savings are minimal and these are rare. 5658 QualType ASTContext::getUnaryTransformType(QualType BaseType, 5659 QualType UnderlyingType, 5660 UnaryTransformType::UTTKind Kind) 5661 const { 5662 UnaryTransformType *ut = nullptr; 5663 5664 if (BaseType->isDependentType()) { 5665 // Look in the folding set for an existing type. 5666 llvm::FoldingSetNodeID ID; 5667 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind); 5668 5669 void *InsertPos = nullptr; 5670 DependentUnaryTransformType *Canon 5671 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos); 5672 5673 if (!Canon) { 5674 // Build a new, canonical __underlying_type(type) type. 5675 Canon = new (*this, TypeAlignment) 5676 DependentUnaryTransformType(*this, getCanonicalType(BaseType), 5677 Kind); 5678 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos); 5679 } 5680 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType, 5681 QualType(), Kind, 5682 QualType(Canon, 0)); 5683 } else { 5684 QualType CanonType = getCanonicalType(UnderlyingType); 5685 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType, 5686 UnderlyingType, Kind, 5687 CanonType); 5688 } 5689 Types.push_back(ut); 5690 return QualType(ut, 0); 5691 } 5692 5693 QualType ASTContext::getAutoTypeInternal( 5694 QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent, 5695 bool IsPack, ConceptDecl *TypeConstraintConcept, 5696 ArrayRef<TemplateArgument> TypeConstraintArgs, bool IsCanon) const { 5697 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && 5698 !TypeConstraintConcept && !IsDependent) 5699 return getAutoDeductType(); 5700 5701 // Look in the folding set for an existing type. 5702 void *InsertPos = nullptr; 5703 llvm::FoldingSetNodeID ID; 5704 AutoType::Profile(ID, *this, DeducedType, Keyword, IsDependent, 5705 TypeConstraintConcept, TypeConstraintArgs); 5706 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos)) 5707 return QualType(AT, 0); 5708 5709 QualType Canon; 5710 if (!IsCanon) { 5711 if (DeducedType.isNull()) { 5712 SmallVector<TemplateArgument, 4> CanonArgs; 5713 bool AnyNonCanonArgs = 5714 ::getCanonicalTemplateArguments(*this, TypeConstraintArgs, CanonArgs); 5715 if (AnyNonCanonArgs) { 5716 Canon = getAutoTypeInternal(QualType(), Keyword, IsDependent, IsPack, 5717 TypeConstraintConcept, CanonArgs, true); 5718 // Find the insert position again. 5719 AutoTypes.FindNodeOrInsertPos(ID, InsertPos); 5720 } 5721 } else { 5722 Canon = DeducedType.getCanonicalType(); 5723 } 5724 } 5725 5726 void *Mem = Allocate(sizeof(AutoType) + 5727 sizeof(TemplateArgument) * TypeConstraintArgs.size(), 5728 TypeAlignment); 5729 auto *AT = new (Mem) AutoType( 5730 DeducedType, Keyword, 5731 (IsDependent ? TypeDependence::DependentInstantiation 5732 : TypeDependence::None) | 5733 (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None), 5734 Canon, TypeConstraintConcept, TypeConstraintArgs); 5735 Types.push_back(AT); 5736 AutoTypes.InsertNode(AT, InsertPos); 5737 return QualType(AT, 0); 5738 } 5739 5740 /// getAutoType - Return the uniqued reference to the 'auto' type which has been 5741 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the 5742 /// canonical deduced-but-dependent 'auto' type. 5743 QualType 5744 ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, 5745 bool IsDependent, bool IsPack, 5746 ConceptDecl *TypeConstraintConcept, 5747 ArrayRef<TemplateArgument> TypeConstraintArgs) const { 5748 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack"); 5749 assert((!IsDependent || DeducedType.isNull()) && 5750 "A dependent auto should be undeduced"); 5751 return getAutoTypeInternal(DeducedType, Keyword, IsDependent, IsPack, 5752 TypeConstraintConcept, TypeConstraintArgs); 5753 } 5754 5755 /// Return the uniqued reference to the deduced template specialization type 5756 /// which has been deduced to the given type, or to the canonical undeduced 5757 /// such type, or the canonical deduced-but-dependent such type. 5758 QualType ASTContext::getDeducedTemplateSpecializationType( 5759 TemplateName Template, QualType DeducedType, bool IsDependent) const { 5760 // Look in the folding set for an existing type. 5761 void *InsertPos = nullptr; 5762 llvm::FoldingSetNodeID ID; 5763 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType, 5764 IsDependent); 5765 if (DeducedTemplateSpecializationType *DTST = 5766 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos)) 5767 return QualType(DTST, 0); 5768 5769 auto *DTST = new (*this, TypeAlignment) 5770 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent); 5771 llvm::FoldingSetNodeID TempID; 5772 DTST->Profile(TempID); 5773 assert(ID == TempID && "ID does not match"); 5774 Types.push_back(DTST); 5775 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos); 5776 return QualType(DTST, 0); 5777 } 5778 5779 /// getAtomicType - Return the uniqued reference to the atomic type for 5780 /// the given value type. 5781 QualType ASTContext::getAtomicType(QualType T) const { 5782 // Unique pointers, to guarantee there is only one pointer of a particular 5783 // structure. 5784 llvm::FoldingSetNodeID ID; 5785 AtomicType::Profile(ID, T); 5786 5787 void *InsertPos = nullptr; 5788 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos)) 5789 return QualType(AT, 0); 5790 5791 // If the atomic value type isn't canonical, this won't be a canonical type 5792 // either, so fill in the canonical type field. 5793 QualType Canonical; 5794 if (!T.isCanonical()) { 5795 Canonical = getAtomicType(getCanonicalType(T)); 5796 5797 // Get the new insert position for the node we care about. 5798 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos); 5799 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 5800 } 5801 auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical); 5802 Types.push_back(New); 5803 AtomicTypes.InsertNode(New, InsertPos); 5804 return QualType(New, 0); 5805 } 5806 5807 /// getAutoDeductType - Get type pattern for deducing against 'auto'. 5808 QualType ASTContext::getAutoDeductType() const { 5809 if (AutoDeductTy.isNull()) 5810 AutoDeductTy = QualType(new (*this, TypeAlignment) 5811 AutoType(QualType(), AutoTypeKeyword::Auto, 5812 TypeDependence::None, QualType(), 5813 /*concept*/ nullptr, /*args*/ {}), 5814 0); 5815 return AutoDeductTy; 5816 } 5817 5818 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'. 5819 QualType ASTContext::getAutoRRefDeductType() const { 5820 if (AutoRRefDeductTy.isNull()) 5821 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType()); 5822 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern"); 5823 return AutoRRefDeductTy; 5824 } 5825 5826 /// getTagDeclType - Return the unique reference to the type for the 5827 /// specified TagDecl (struct/union/class/enum) decl. 5828 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const { 5829 assert(Decl); 5830 // FIXME: What is the design on getTagDeclType when it requires casting 5831 // away const? mutable? 5832 return getTypeDeclType(const_cast<TagDecl*>(Decl)); 5833 } 5834 5835 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result 5836 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and 5837 /// needs to agree with the definition in <stddef.h>. 5838 CanQualType ASTContext::getSizeType() const { 5839 return getFromTargetType(Target->getSizeType()); 5840 } 5841 5842 /// Return the unique signed counterpart of the integer type 5843 /// corresponding to size_t. 5844 CanQualType ASTContext::getSignedSizeType() const { 5845 return getFromTargetType(Target->getSignedSizeType()); 5846 } 5847 5848 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5). 5849 CanQualType ASTContext::getIntMaxType() const { 5850 return getFromTargetType(Target->getIntMaxType()); 5851 } 5852 5853 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5). 5854 CanQualType ASTContext::getUIntMaxType() const { 5855 return getFromTargetType(Target->getUIntMaxType()); 5856 } 5857 5858 /// getSignedWCharType - Return the type of "signed wchar_t". 5859 /// Used when in C++, as a GCC extension. 5860 QualType ASTContext::getSignedWCharType() const { 5861 // FIXME: derive from "Target" ? 5862 return WCharTy; 5863 } 5864 5865 /// getUnsignedWCharType - Return the type of "unsigned wchar_t". 5866 /// Used when in C++, as a GCC extension. 5867 QualType ASTContext::getUnsignedWCharType() const { 5868 // FIXME: derive from "Target" ? 5869 return UnsignedIntTy; 5870 } 5871 5872 QualType ASTContext::getIntPtrType() const { 5873 return getFromTargetType(Target->getIntPtrType()); 5874 } 5875 5876 QualType ASTContext::getUIntPtrType() const { 5877 return getCorrespondingUnsignedType(getIntPtrType()); 5878 } 5879 5880 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17) 5881 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9). 5882 QualType ASTContext::getPointerDiffType() const { 5883 return getFromTargetType(Target->getPtrDiffType(0)); 5884 } 5885 5886 /// Return the unique unsigned counterpart of "ptrdiff_t" 5887 /// integer type. The standard (C11 7.21.6.1p7) refers to this type 5888 /// in the definition of %tu format specifier. 5889 QualType ASTContext::getUnsignedPointerDiffType() const { 5890 return getFromTargetType(Target->getUnsignedPtrDiffType(0)); 5891 } 5892 5893 /// Return the unique type for "pid_t" defined in 5894 /// <sys/types.h>. We need this to compute the correct type for vfork(). 5895 QualType ASTContext::getProcessIDType() const { 5896 return getFromTargetType(Target->getProcessIDType()); 5897 } 5898 5899 //===----------------------------------------------------------------------===// 5900 // Type Operators 5901 //===----------------------------------------------------------------------===// 5902 5903 CanQualType ASTContext::getCanonicalParamType(QualType T) const { 5904 // Push qualifiers into arrays, and then discard any remaining 5905 // qualifiers. 5906 T = getCanonicalType(T); 5907 T = getVariableArrayDecayedType(T); 5908 const Type *Ty = T.getTypePtr(); 5909 QualType Result; 5910 if (isa<ArrayType>(Ty)) { 5911 Result = getArrayDecayedType(QualType(Ty,0)); 5912 } else if (isa<FunctionType>(Ty)) { 5913 Result = getPointerType(QualType(Ty, 0)); 5914 } else { 5915 Result = QualType(Ty, 0); 5916 } 5917 5918 return CanQualType::CreateUnsafe(Result); 5919 } 5920 5921 QualType ASTContext::getUnqualifiedArrayType(QualType type, 5922 Qualifiers &quals) { 5923 SplitQualType splitType = type.getSplitUnqualifiedType(); 5924 5925 // FIXME: getSplitUnqualifiedType() actually walks all the way to 5926 // the unqualified desugared type and then drops it on the floor. 5927 // We then have to strip that sugar back off with 5928 // getUnqualifiedDesugaredType(), which is silly. 5929 const auto *AT = 5930 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType()); 5931 5932 // If we don't have an array, just use the results in splitType. 5933 if (!AT) { 5934 quals = splitType.Quals; 5935 return QualType(splitType.Ty, 0); 5936 } 5937 5938 // Otherwise, recurse on the array's element type. 5939 QualType elementType = AT->getElementType(); 5940 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals); 5941 5942 // If that didn't change the element type, AT has no qualifiers, so we 5943 // can just use the results in splitType. 5944 if (elementType == unqualElementType) { 5945 assert(quals.empty()); // from the recursive call 5946 quals = splitType.Quals; 5947 return QualType(splitType.Ty, 0); 5948 } 5949 5950 // Otherwise, add in the qualifiers from the outermost type, then 5951 // build the type back up. 5952 quals.addConsistentQualifiers(splitType.Quals); 5953 5954 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 5955 return getConstantArrayType(unqualElementType, CAT->getSize(), 5956 CAT->getSizeExpr(), CAT->getSizeModifier(), 0); 5957 } 5958 5959 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) { 5960 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0); 5961 } 5962 5963 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) { 5964 return getVariableArrayType(unqualElementType, 5965 VAT->getSizeExpr(), 5966 VAT->getSizeModifier(), 5967 VAT->getIndexTypeCVRQualifiers(), 5968 VAT->getBracketsRange()); 5969 } 5970 5971 const auto *DSAT = cast<DependentSizedArrayType>(AT); 5972 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(), 5973 DSAT->getSizeModifier(), 0, 5974 SourceRange()); 5975 } 5976 5977 /// Attempt to unwrap two types that may both be array types with the same bound 5978 /// (or both be array types of unknown bound) for the purpose of comparing the 5979 /// cv-decomposition of two types per C++ [conv.qual]. 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 void ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2, 5984 bool AllowPiMismatch) { 5985 while (true) { 5986 auto *AT1 = getAsArrayType(T1); 5987 if (!AT1) 5988 return; 5989 5990 auto *AT2 = getAsArrayType(T2); 5991 if (!AT2) 5992 return; 5993 5994 // If we don't have two array types with the same constant bound nor two 5995 // incomplete array types, we've unwrapped everything we can. 5996 // C++20 also permits one type to be a constant array type and the other 5997 // to be an incomplete array type. 5998 // FIXME: Consider also unwrapping array of unknown bound and VLA. 5999 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) { 6000 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2); 6001 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) || 6002 (AllowPiMismatch && getLangOpts().CPlusPlus20 && 6003 isa<IncompleteArrayType>(AT2)))) 6004 return; 6005 } else if (isa<IncompleteArrayType>(AT1)) { 6006 if (!(isa<IncompleteArrayType>(AT2) || 6007 (AllowPiMismatch && getLangOpts().CPlusPlus20 && 6008 isa<ConstantArrayType>(AT2)))) 6009 return; 6010 } else { 6011 return; 6012 } 6013 6014 T1 = AT1->getElementType(); 6015 T2 = AT2->getElementType(); 6016 } 6017 } 6018 6019 /// Attempt to unwrap two types that may be similar (C++ [conv.qual]). 6020 /// 6021 /// If T1 and T2 are both pointer types of the same kind, or both array types 6022 /// with the same bound, unwraps layers from T1 and T2 until a pointer type is 6023 /// unwrapped. Top-level qualifiers on T1 and T2 are ignored. 6024 /// 6025 /// This function will typically be called in a loop that successively 6026 /// "unwraps" pointer and pointer-to-member types to compare them at each 6027 /// level. 6028 /// 6029 /// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in 6030 /// C++20 [conv.qual], if permitted by the current language mode. 6031 /// 6032 /// \return \c true if a pointer type was unwrapped, \c false if we reached a 6033 /// pair of types that can't be unwrapped further. 6034 bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2, 6035 bool AllowPiMismatch) { 6036 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch); 6037 6038 const auto *T1PtrType = T1->getAs<PointerType>(); 6039 const auto *T2PtrType = T2->getAs<PointerType>(); 6040 if (T1PtrType && T2PtrType) { 6041 T1 = T1PtrType->getPointeeType(); 6042 T2 = T2PtrType->getPointeeType(); 6043 return true; 6044 } 6045 6046 const auto *T1MPType = T1->getAs<MemberPointerType>(); 6047 const auto *T2MPType = T2->getAs<MemberPointerType>(); 6048 if (T1MPType && T2MPType && 6049 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0), 6050 QualType(T2MPType->getClass(), 0))) { 6051 T1 = T1MPType->getPointeeType(); 6052 T2 = T2MPType->getPointeeType(); 6053 return true; 6054 } 6055 6056 if (getLangOpts().ObjC) { 6057 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>(); 6058 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>(); 6059 if (T1OPType && T2OPType) { 6060 T1 = T1OPType->getPointeeType(); 6061 T2 = T2OPType->getPointeeType(); 6062 return true; 6063 } 6064 } 6065 6066 // FIXME: Block pointers, too? 6067 6068 return false; 6069 } 6070 6071 bool ASTContext::hasSimilarType(QualType T1, QualType T2) { 6072 while (true) { 6073 Qualifiers Quals; 6074 T1 = getUnqualifiedArrayType(T1, Quals); 6075 T2 = getUnqualifiedArrayType(T2, Quals); 6076 if (hasSameType(T1, T2)) 6077 return true; 6078 if (!UnwrapSimilarTypes(T1, T2)) 6079 return false; 6080 } 6081 } 6082 6083 bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) { 6084 while (true) { 6085 Qualifiers Quals1, Quals2; 6086 T1 = getUnqualifiedArrayType(T1, Quals1); 6087 T2 = getUnqualifiedArrayType(T2, Quals2); 6088 6089 Quals1.removeCVRQualifiers(); 6090 Quals2.removeCVRQualifiers(); 6091 if (Quals1 != Quals2) 6092 return false; 6093 6094 if (hasSameType(T1, T2)) 6095 return true; 6096 6097 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false)) 6098 return false; 6099 } 6100 } 6101 6102 DeclarationNameInfo 6103 ASTContext::getNameForTemplate(TemplateName Name, 6104 SourceLocation NameLoc) const { 6105 switch (Name.getKind()) { 6106 case TemplateName::QualifiedTemplate: 6107 case TemplateName::Template: 6108 // DNInfo work in progress: CHECKME: what about DNLoc? 6109 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(), 6110 NameLoc); 6111 6112 case TemplateName::OverloadedTemplate: { 6113 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate(); 6114 // DNInfo work in progress: CHECKME: what about DNLoc? 6115 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc); 6116 } 6117 6118 case TemplateName::AssumedTemplate: { 6119 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName(); 6120 return DeclarationNameInfo(Storage->getDeclName(), NameLoc); 6121 } 6122 6123 case TemplateName::DependentTemplate: { 6124 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 6125 DeclarationName DName; 6126 if (DTN->isIdentifier()) { 6127 DName = DeclarationNames.getIdentifier(DTN->getIdentifier()); 6128 return DeclarationNameInfo(DName, NameLoc); 6129 } else { 6130 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator()); 6131 // DNInfo work in progress: FIXME: source locations? 6132 DeclarationNameLoc DNLoc = 6133 DeclarationNameLoc::makeCXXOperatorNameLoc(SourceRange()); 6134 return DeclarationNameInfo(DName, NameLoc, DNLoc); 6135 } 6136 } 6137 6138 case TemplateName::SubstTemplateTemplateParm: { 6139 SubstTemplateTemplateParmStorage *subst 6140 = Name.getAsSubstTemplateTemplateParm(); 6141 return DeclarationNameInfo(subst->getParameter()->getDeclName(), 6142 NameLoc); 6143 } 6144 6145 case TemplateName::SubstTemplateTemplateParmPack: { 6146 SubstTemplateTemplateParmPackStorage *subst 6147 = Name.getAsSubstTemplateTemplateParmPack(); 6148 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(), 6149 NameLoc); 6150 } 6151 case TemplateName::UsingTemplate: 6152 return DeclarationNameInfo(Name.getAsUsingShadowDecl()->getDeclName(), 6153 NameLoc); 6154 } 6155 6156 llvm_unreachable("bad template name kind!"); 6157 } 6158 6159 TemplateName 6160 ASTContext::getCanonicalTemplateName(const TemplateName &Name) const { 6161 switch (Name.getKind()) { 6162 case TemplateName::UsingTemplate: 6163 case TemplateName::QualifiedTemplate: 6164 case TemplateName::Template: { 6165 TemplateDecl *Template = Name.getAsTemplateDecl(); 6166 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template)) 6167 Template = getCanonicalTemplateTemplateParmDecl(TTP); 6168 6169 // The canonical template name is the canonical template declaration. 6170 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl())); 6171 } 6172 6173 case TemplateName::OverloadedTemplate: 6174 case TemplateName::AssumedTemplate: 6175 llvm_unreachable("cannot canonicalize unresolved template"); 6176 6177 case TemplateName::DependentTemplate: { 6178 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 6179 assert(DTN && "Non-dependent template names must refer to template decls."); 6180 return DTN->CanonicalTemplateName; 6181 } 6182 6183 case TemplateName::SubstTemplateTemplateParm: { 6184 SubstTemplateTemplateParmStorage *subst 6185 = Name.getAsSubstTemplateTemplateParm(); 6186 return getCanonicalTemplateName(subst->getReplacement()); 6187 } 6188 6189 case TemplateName::SubstTemplateTemplateParmPack: { 6190 SubstTemplateTemplateParmPackStorage *subst 6191 = Name.getAsSubstTemplateTemplateParmPack(); 6192 TemplateTemplateParmDecl *canonParameter 6193 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack()); 6194 TemplateArgument canonArgPack 6195 = getCanonicalTemplateArgument(subst->getArgumentPack()); 6196 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack); 6197 } 6198 } 6199 6200 llvm_unreachable("bad template name!"); 6201 } 6202 6203 bool ASTContext::hasSameTemplateName(const TemplateName &X, 6204 const TemplateName &Y) const { 6205 return getCanonicalTemplateName(X).getAsVoidPointer() == 6206 getCanonicalTemplateName(Y).getAsVoidPointer(); 6207 } 6208 6209 bool ASTContext::isSameTemplateParameter(const NamedDecl *X, 6210 const NamedDecl *Y) { 6211 if (X->getKind() != Y->getKind()) 6212 return false; 6213 6214 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) { 6215 auto *TY = cast<TemplateTypeParmDecl>(Y); 6216 if (TX->isParameterPack() != TY->isParameterPack()) 6217 return false; 6218 if (TX->hasTypeConstraint() != TY->hasTypeConstraint()) 6219 return false; 6220 const TypeConstraint *TXTC = TX->getTypeConstraint(); 6221 const TypeConstraint *TYTC = TY->getTypeConstraint(); 6222 if (!TXTC != !TYTC) 6223 return false; 6224 if (TXTC && TYTC) { 6225 auto *NCX = TXTC->getNamedConcept(); 6226 auto *NCY = TYTC->getNamedConcept(); 6227 if (!NCX || !NCY || !isSameEntity(NCX, NCY)) 6228 return false; 6229 if (TXTC->hasExplicitTemplateArgs() != TYTC->hasExplicitTemplateArgs()) 6230 return false; 6231 if (TXTC->hasExplicitTemplateArgs()) { 6232 auto *TXTCArgs = TXTC->getTemplateArgsAsWritten(); 6233 auto *TYTCArgs = TYTC->getTemplateArgsAsWritten(); 6234 if (TXTCArgs->NumTemplateArgs != TYTCArgs->NumTemplateArgs) 6235 return false; 6236 llvm::FoldingSetNodeID XID, YID; 6237 for (auto &ArgLoc : TXTCArgs->arguments()) 6238 ArgLoc.getArgument().Profile(XID, X->getASTContext()); 6239 for (auto &ArgLoc : TYTCArgs->arguments()) 6240 ArgLoc.getArgument().Profile(YID, Y->getASTContext()); 6241 if (XID != YID) 6242 return false; 6243 } 6244 } 6245 return true; 6246 } 6247 6248 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) { 6249 auto *TY = cast<NonTypeTemplateParmDecl>(Y); 6250 return TX->isParameterPack() == TY->isParameterPack() && 6251 TX->getASTContext().hasSameType(TX->getType(), TY->getType()); 6252 } 6253 6254 auto *TX = cast<TemplateTemplateParmDecl>(X); 6255 auto *TY = cast<TemplateTemplateParmDecl>(Y); 6256 return TX->isParameterPack() == TY->isParameterPack() && 6257 isSameTemplateParameterList(TX->getTemplateParameters(), 6258 TY->getTemplateParameters()); 6259 } 6260 6261 bool ASTContext::isSameTemplateParameterList(const TemplateParameterList *X, 6262 const TemplateParameterList *Y) { 6263 if (X->size() != Y->size()) 6264 return false; 6265 6266 for (unsigned I = 0, N = X->size(); I != N; ++I) 6267 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I))) 6268 return false; 6269 6270 const Expr *XRC = X->getRequiresClause(); 6271 const Expr *YRC = Y->getRequiresClause(); 6272 if (!XRC != !YRC) 6273 return false; 6274 if (XRC) { 6275 llvm::FoldingSetNodeID XRCID, YRCID; 6276 XRC->Profile(XRCID, *this, /*Canonical=*/true); 6277 YRC->Profile(YRCID, *this, /*Canonical=*/true); 6278 if (XRCID != YRCID) 6279 return false; 6280 } 6281 6282 return true; 6283 } 6284 6285 static NamespaceDecl *getNamespace(const NestedNameSpecifier *X) { 6286 if (auto *NS = X->getAsNamespace()) 6287 return NS; 6288 if (auto *NAS = X->getAsNamespaceAlias()) 6289 return NAS->getNamespace(); 6290 return nullptr; 6291 } 6292 6293 static bool isSameQualifier(const NestedNameSpecifier *X, 6294 const NestedNameSpecifier *Y) { 6295 if (auto *NSX = getNamespace(X)) { 6296 auto *NSY = getNamespace(Y); 6297 if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl()) 6298 return false; 6299 } else if (X->getKind() != Y->getKind()) 6300 return false; 6301 6302 // FIXME: For namespaces and types, we're permitted to check that the entity 6303 // is named via the same tokens. We should probably do so. 6304 switch (X->getKind()) { 6305 case NestedNameSpecifier::Identifier: 6306 if (X->getAsIdentifier() != Y->getAsIdentifier()) 6307 return false; 6308 break; 6309 case NestedNameSpecifier::Namespace: 6310 case NestedNameSpecifier::NamespaceAlias: 6311 // We've already checked that we named the same namespace. 6312 break; 6313 case NestedNameSpecifier::TypeSpec: 6314 case NestedNameSpecifier::TypeSpecWithTemplate: 6315 if (X->getAsType()->getCanonicalTypeInternal() != 6316 Y->getAsType()->getCanonicalTypeInternal()) 6317 return false; 6318 break; 6319 case NestedNameSpecifier::Global: 6320 case NestedNameSpecifier::Super: 6321 return true; 6322 } 6323 6324 // Recurse into earlier portion of NNS, if any. 6325 auto *PX = X->getPrefix(); 6326 auto *PY = Y->getPrefix(); 6327 if (PX && PY) 6328 return isSameQualifier(PX, PY); 6329 return !PX && !PY; 6330 } 6331 6332 /// Determine whether the attributes we can overload on are identical for A and 6333 /// B. Will ignore any overloadable attrs represented in the type of A and B. 6334 static bool hasSameOverloadableAttrs(const FunctionDecl *A, 6335 const FunctionDecl *B) { 6336 // Note that pass_object_size attributes are represented in the function's 6337 // ExtParameterInfo, so we don't need to check them here. 6338 6339 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 6340 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>(); 6341 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>(); 6342 6343 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) { 6344 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); 6345 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); 6346 6347 // Return false if the number of enable_if attributes is different. 6348 if (!Cand1A || !Cand2A) 6349 return false; 6350 6351 Cand1ID.clear(); 6352 Cand2ID.clear(); 6353 6354 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true); 6355 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true); 6356 6357 // Return false if any of the enable_if expressions of A and B are 6358 // different. 6359 if (Cand1ID != Cand2ID) 6360 return false; 6361 } 6362 return true; 6363 } 6364 6365 bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) { 6366 if (X == Y) 6367 return true; 6368 6369 if (X->getDeclName() != Y->getDeclName()) 6370 return false; 6371 6372 // Must be in the same context. 6373 // 6374 // Note that we can't use DeclContext::Equals here, because the DeclContexts 6375 // could be two different declarations of the same function. (We will fix the 6376 // semantic DC to refer to the primary definition after merging.) 6377 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()), 6378 cast<Decl>(Y->getDeclContext()->getRedeclContext()))) 6379 return false; 6380 6381 // Two typedefs refer to the same entity if they have the same underlying 6382 // type. 6383 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X)) 6384 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y)) 6385 return hasSameType(TypedefX->getUnderlyingType(), 6386 TypedefY->getUnderlyingType()); 6387 6388 // Must have the same kind. 6389 if (X->getKind() != Y->getKind()) 6390 return false; 6391 6392 // Objective-C classes and protocols with the same name always match. 6393 if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X)) 6394 return true; 6395 6396 if (isa<ClassTemplateSpecializationDecl>(X)) { 6397 // No need to handle these here: we merge them when adding them to the 6398 // template. 6399 return false; 6400 } 6401 6402 // Compatible tags match. 6403 if (const auto *TagX = dyn_cast<TagDecl>(X)) { 6404 const auto *TagY = cast<TagDecl>(Y); 6405 return (TagX->getTagKind() == TagY->getTagKind()) || 6406 ((TagX->getTagKind() == TTK_Struct || 6407 TagX->getTagKind() == TTK_Class || 6408 TagX->getTagKind() == TTK_Interface) && 6409 (TagY->getTagKind() == TTK_Struct || 6410 TagY->getTagKind() == TTK_Class || 6411 TagY->getTagKind() == TTK_Interface)); 6412 } 6413 6414 // Functions with the same type and linkage match. 6415 // FIXME: This needs to cope with merging of prototyped/non-prototyped 6416 // functions, etc. 6417 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) { 6418 const auto *FuncY = cast<FunctionDecl>(Y); 6419 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) { 6420 const auto *CtorY = cast<CXXConstructorDecl>(Y); 6421 if (CtorX->getInheritedConstructor() && 6422 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(), 6423 CtorY->getInheritedConstructor().getConstructor())) 6424 return false; 6425 } 6426 6427 if (FuncX->isMultiVersion() != FuncY->isMultiVersion()) 6428 return false; 6429 6430 // Multiversioned functions with different feature strings are represented 6431 // as separate declarations. 6432 if (FuncX->isMultiVersion()) { 6433 const auto *TAX = FuncX->getAttr<TargetAttr>(); 6434 const auto *TAY = FuncY->getAttr<TargetAttr>(); 6435 assert(TAX && TAY && "Multiversion Function without target attribute"); 6436 6437 if (TAX->getFeaturesStr() != TAY->getFeaturesStr()) 6438 return false; 6439 } 6440 6441 const Expr *XRC = FuncX->getTrailingRequiresClause(); 6442 const Expr *YRC = FuncY->getTrailingRequiresClause(); 6443 if (!XRC != !YRC) 6444 return false; 6445 if (XRC) { 6446 llvm::FoldingSetNodeID XRCID, YRCID; 6447 XRC->Profile(XRCID, *this, /*Canonical=*/true); 6448 YRC->Profile(YRCID, *this, /*Canonical=*/true); 6449 if (XRCID != YRCID) 6450 return false; 6451 } 6452 6453 auto GetTypeAsWritten = [](const FunctionDecl *FD) { 6454 // Map to the first declaration that we've already merged into this one. 6455 // The TSI of redeclarations might not match (due to calling conventions 6456 // being inherited onto the type but not the TSI), but the TSI type of 6457 // the first declaration of the function should match across modules. 6458 FD = FD->getCanonicalDecl(); 6459 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType() 6460 : FD->getType(); 6461 }; 6462 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY); 6463 if (!hasSameType(XT, YT)) { 6464 // We can get functions with different types on the redecl chain in C++17 6465 // if they have differing exception specifications and at least one of 6466 // the excpetion specs is unresolved. 6467 auto *XFPT = XT->getAs<FunctionProtoType>(); 6468 auto *YFPT = YT->getAs<FunctionProtoType>(); 6469 if (getLangOpts().CPlusPlus17 && XFPT && YFPT && 6470 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) || 6471 isUnresolvedExceptionSpec(YFPT->getExceptionSpecType())) && 6472 // FIXME: We could make isSameEntity const after we make 6473 // hasSameFunctionTypeIgnoringExceptionSpec const. 6474 hasSameFunctionTypeIgnoringExceptionSpec(XT, YT)) 6475 return true; 6476 return false; 6477 } 6478 6479 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() && 6480 hasSameOverloadableAttrs(FuncX, FuncY); 6481 } 6482 6483 // Variables with the same type and linkage match. 6484 if (const auto *VarX = dyn_cast<VarDecl>(X)) { 6485 const auto *VarY = cast<VarDecl>(Y); 6486 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) { 6487 if (hasSameType(VarX->getType(), VarY->getType())) 6488 return true; 6489 6490 // We can get decls with different types on the redecl chain. Eg. 6491 // template <typename T> struct S { static T Var[]; }; // #1 6492 // template <typename T> T S<T>::Var[sizeof(T)]; // #2 6493 // Only? happens when completing an incomplete array type. In this case 6494 // when comparing #1 and #2 we should go through their element type. 6495 const ArrayType *VarXTy = getAsArrayType(VarX->getType()); 6496 const ArrayType *VarYTy = getAsArrayType(VarY->getType()); 6497 if (!VarXTy || !VarYTy) 6498 return false; 6499 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType()) 6500 return hasSameType(VarXTy->getElementType(), VarYTy->getElementType()); 6501 } 6502 return false; 6503 } 6504 6505 // Namespaces with the same name and inlinedness match. 6506 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) { 6507 const auto *NamespaceY = cast<NamespaceDecl>(Y); 6508 return NamespaceX->isInline() == NamespaceY->isInline(); 6509 } 6510 6511 // Identical template names and kinds match if their template parameter lists 6512 // and patterns match. 6513 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) { 6514 const auto *TemplateY = cast<TemplateDecl>(Y); 6515 return isSameEntity(TemplateX->getTemplatedDecl(), 6516 TemplateY->getTemplatedDecl()) && 6517 isSameTemplateParameterList(TemplateX->getTemplateParameters(), 6518 TemplateY->getTemplateParameters()); 6519 } 6520 6521 // Fields with the same name and the same type match. 6522 if (const auto *FDX = dyn_cast<FieldDecl>(X)) { 6523 const auto *FDY = cast<FieldDecl>(Y); 6524 // FIXME: Also check the bitwidth is odr-equivalent, if any. 6525 return hasSameType(FDX->getType(), FDY->getType()); 6526 } 6527 6528 // Indirect fields with the same target field match. 6529 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) { 6530 const auto *IFDY = cast<IndirectFieldDecl>(Y); 6531 return IFDX->getAnonField()->getCanonicalDecl() == 6532 IFDY->getAnonField()->getCanonicalDecl(); 6533 } 6534 6535 // Enumerators with the same name match. 6536 if (isa<EnumConstantDecl>(X)) 6537 // FIXME: Also check the value is odr-equivalent. 6538 return true; 6539 6540 // Using shadow declarations with the same target match. 6541 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) { 6542 const auto *USY = cast<UsingShadowDecl>(Y); 6543 return USX->getTargetDecl() == USY->getTargetDecl(); 6544 } 6545 6546 // Using declarations with the same qualifier match. (We already know that 6547 // the name matches.) 6548 if (const auto *UX = dyn_cast<UsingDecl>(X)) { 6549 const auto *UY = cast<UsingDecl>(Y); 6550 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) && 6551 UX->hasTypename() == UY->hasTypename() && 6552 UX->isAccessDeclaration() == UY->isAccessDeclaration(); 6553 } 6554 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) { 6555 const auto *UY = cast<UnresolvedUsingValueDecl>(Y); 6556 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) && 6557 UX->isAccessDeclaration() == UY->isAccessDeclaration(); 6558 } 6559 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) { 6560 return isSameQualifier( 6561 UX->getQualifier(), 6562 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier()); 6563 } 6564 6565 // Using-pack declarations are only created by instantiation, and match if 6566 // they're instantiated from matching UnresolvedUsing...Decls. 6567 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) { 6568 return declaresSameEntity( 6569 UX->getInstantiatedFromUsingDecl(), 6570 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl()); 6571 } 6572 6573 // Namespace alias definitions with the same target match. 6574 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) { 6575 const auto *NAY = cast<NamespaceAliasDecl>(Y); 6576 return NAX->getNamespace()->Equals(NAY->getNamespace()); 6577 } 6578 6579 return false; 6580 } 6581 6582 TemplateArgument 6583 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const { 6584 switch (Arg.getKind()) { 6585 case TemplateArgument::Null: 6586 return Arg; 6587 6588 case TemplateArgument::Expression: 6589 return Arg; 6590 6591 case TemplateArgument::Declaration: { 6592 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl()); 6593 return TemplateArgument(D, Arg.getParamTypeForDecl()); 6594 } 6595 6596 case TemplateArgument::NullPtr: 6597 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()), 6598 /*isNullPtr*/true); 6599 6600 case TemplateArgument::Template: 6601 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate())); 6602 6603 case TemplateArgument::TemplateExpansion: 6604 return TemplateArgument(getCanonicalTemplateName( 6605 Arg.getAsTemplateOrTemplatePattern()), 6606 Arg.getNumTemplateExpansions()); 6607 6608 case TemplateArgument::Integral: 6609 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType())); 6610 6611 case TemplateArgument::Type: 6612 return TemplateArgument(getCanonicalType(Arg.getAsType())); 6613 6614 case TemplateArgument::Pack: { 6615 if (Arg.pack_size() == 0) 6616 return Arg; 6617 6618 auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()]; 6619 unsigned Idx = 0; 6620 for (TemplateArgument::pack_iterator A = Arg.pack_begin(), 6621 AEnd = Arg.pack_end(); 6622 A != AEnd; (void)++A, ++Idx) 6623 CanonArgs[Idx] = getCanonicalTemplateArgument(*A); 6624 6625 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size())); 6626 } 6627 } 6628 6629 // Silence GCC warning 6630 llvm_unreachable("Unhandled template argument kind"); 6631 } 6632 6633 NestedNameSpecifier * 6634 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const { 6635 if (!NNS) 6636 return nullptr; 6637 6638 switch (NNS->getKind()) { 6639 case NestedNameSpecifier::Identifier: 6640 // Canonicalize the prefix but keep the identifier the same. 6641 return NestedNameSpecifier::Create(*this, 6642 getCanonicalNestedNameSpecifier(NNS->getPrefix()), 6643 NNS->getAsIdentifier()); 6644 6645 case NestedNameSpecifier::Namespace: 6646 // A namespace is canonical; build a nested-name-specifier with 6647 // this namespace and no prefix. 6648 return NestedNameSpecifier::Create(*this, nullptr, 6649 NNS->getAsNamespace()->getOriginalNamespace()); 6650 6651 case NestedNameSpecifier::NamespaceAlias: 6652 // A namespace is canonical; build a nested-name-specifier with 6653 // this namespace and no prefix. 6654 return NestedNameSpecifier::Create(*this, nullptr, 6655 NNS->getAsNamespaceAlias()->getNamespace() 6656 ->getOriginalNamespace()); 6657 6658 // The difference between TypeSpec and TypeSpecWithTemplate is that the 6659 // latter will have the 'template' keyword when printed. 6660 case NestedNameSpecifier::TypeSpec: 6661 case NestedNameSpecifier::TypeSpecWithTemplate: { 6662 const Type *T = getCanonicalType(NNS->getAsType()); 6663 6664 // If we have some kind of dependent-named type (e.g., "typename T::type"), 6665 // break it apart into its prefix and identifier, then reconsititute those 6666 // as the canonical nested-name-specifier. This is required to canonicalize 6667 // a dependent nested-name-specifier involving typedefs of dependent-name 6668 // types, e.g., 6669 // typedef typename T::type T1; 6670 // typedef typename T1::type T2; 6671 if (const auto *DNT = T->getAs<DependentNameType>()) 6672 return NestedNameSpecifier::Create( 6673 *this, DNT->getQualifier(), 6674 const_cast<IdentifierInfo *>(DNT->getIdentifier())); 6675 if (const auto *DTST = T->getAs<DependentTemplateSpecializationType>()) 6676 return NestedNameSpecifier::Create(*this, DTST->getQualifier(), true, 6677 const_cast<Type *>(T)); 6678 6679 // TODO: Set 'Template' parameter to true for other template types. 6680 return NestedNameSpecifier::Create(*this, nullptr, false, 6681 const_cast<Type *>(T)); 6682 } 6683 6684 case NestedNameSpecifier::Global: 6685 case NestedNameSpecifier::Super: 6686 // The global specifier and __super specifer are canonical and unique. 6687 return NNS; 6688 } 6689 6690 llvm_unreachable("Invalid NestedNameSpecifier::Kind!"); 6691 } 6692 6693 const ArrayType *ASTContext::getAsArrayType(QualType T) const { 6694 // Handle the non-qualified case efficiently. 6695 if (!T.hasLocalQualifiers()) { 6696 // Handle the common positive case fast. 6697 if (const auto *AT = dyn_cast<ArrayType>(T)) 6698 return AT; 6699 } 6700 6701 // Handle the common negative case fast. 6702 if (!isa<ArrayType>(T.getCanonicalType())) 6703 return nullptr; 6704 6705 // Apply any qualifiers from the array type to the element type. This 6706 // implements C99 6.7.3p8: "If the specification of an array type includes 6707 // any type qualifiers, the element type is so qualified, not the array type." 6708 6709 // If we get here, we either have type qualifiers on the type, or we have 6710 // sugar such as a typedef in the way. If we have type qualifiers on the type 6711 // we must propagate them down into the element type. 6712 6713 SplitQualType split = T.getSplitDesugaredType(); 6714 Qualifiers qs = split.Quals; 6715 6716 // If we have a simple case, just return now. 6717 const auto *ATy = dyn_cast<ArrayType>(split.Ty); 6718 if (!ATy || qs.empty()) 6719 return ATy; 6720 6721 // Otherwise, we have an array and we have qualifiers on it. Push the 6722 // qualifiers into the array element type and return a new array type. 6723 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs); 6724 6725 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy)) 6726 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(), 6727 CAT->getSizeExpr(), 6728 CAT->getSizeModifier(), 6729 CAT->getIndexTypeCVRQualifiers())); 6730 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy)) 6731 return cast<ArrayType>(getIncompleteArrayType(NewEltTy, 6732 IAT->getSizeModifier(), 6733 IAT->getIndexTypeCVRQualifiers())); 6734 6735 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy)) 6736 return cast<ArrayType>( 6737 getDependentSizedArrayType(NewEltTy, 6738 DSAT->getSizeExpr(), 6739 DSAT->getSizeModifier(), 6740 DSAT->getIndexTypeCVRQualifiers(), 6741 DSAT->getBracketsRange())); 6742 6743 const auto *VAT = cast<VariableArrayType>(ATy); 6744 return cast<ArrayType>(getVariableArrayType(NewEltTy, 6745 VAT->getSizeExpr(), 6746 VAT->getSizeModifier(), 6747 VAT->getIndexTypeCVRQualifiers(), 6748 VAT->getBracketsRange())); 6749 } 6750 6751 QualType ASTContext::getAdjustedParameterType(QualType T) const { 6752 if (T->isArrayType() || T->isFunctionType()) 6753 return getDecayedType(T); 6754 return T; 6755 } 6756 6757 QualType ASTContext::getSignatureParameterType(QualType T) const { 6758 T = getVariableArrayDecayedType(T); 6759 T = getAdjustedParameterType(T); 6760 return T.getUnqualifiedType(); 6761 } 6762 6763 QualType ASTContext::getExceptionObjectType(QualType T) const { 6764 // C++ [except.throw]p3: 6765 // A throw-expression initializes a temporary object, called the exception 6766 // object, the type of which is determined by removing any top-level 6767 // cv-qualifiers from the static type of the operand of throw and adjusting 6768 // the type from "array of T" or "function returning T" to "pointer to T" 6769 // or "pointer to function returning T", [...] 6770 T = getVariableArrayDecayedType(T); 6771 if (T->isArrayType() || T->isFunctionType()) 6772 T = getDecayedType(T); 6773 return T.getUnqualifiedType(); 6774 } 6775 6776 /// getArrayDecayedType - Return the properly qualified result of decaying the 6777 /// specified array type to a pointer. This operation is non-trivial when 6778 /// handling typedefs etc. The canonical type of "T" must be an array type, 6779 /// this returns a pointer to a properly qualified element of the array. 6780 /// 6781 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3. 6782 QualType ASTContext::getArrayDecayedType(QualType Ty) const { 6783 // Get the element type with 'getAsArrayType' so that we don't lose any 6784 // typedefs in the element type of the array. This also handles propagation 6785 // of type qualifiers from the array type into the element type if present 6786 // (C99 6.7.3p8). 6787 const ArrayType *PrettyArrayType = getAsArrayType(Ty); 6788 assert(PrettyArrayType && "Not an array type!"); 6789 6790 QualType PtrTy = getPointerType(PrettyArrayType->getElementType()); 6791 6792 // int x[restrict 4] -> int *restrict 6793 QualType Result = getQualifiedType(PtrTy, 6794 PrettyArrayType->getIndexTypeQualifiers()); 6795 6796 // int x[_Nullable] -> int * _Nullable 6797 if (auto Nullability = Ty->getNullability(*this)) { 6798 Result = const_cast<ASTContext *>(this)->getAttributedType( 6799 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result); 6800 } 6801 return Result; 6802 } 6803 6804 QualType ASTContext::getBaseElementType(const ArrayType *array) const { 6805 return getBaseElementType(array->getElementType()); 6806 } 6807 6808 QualType ASTContext::getBaseElementType(QualType type) const { 6809 Qualifiers qs; 6810 while (true) { 6811 SplitQualType split = type.getSplitDesugaredType(); 6812 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe(); 6813 if (!array) break; 6814 6815 type = array->getElementType(); 6816 qs.addConsistentQualifiers(split.Quals); 6817 } 6818 6819 return getQualifiedType(type, qs); 6820 } 6821 6822 /// getConstantArrayElementCount - Returns number of constant array elements. 6823 uint64_t 6824 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const { 6825 uint64_t ElementCount = 1; 6826 do { 6827 ElementCount *= CA->getSize().getZExtValue(); 6828 CA = dyn_cast_or_null<ConstantArrayType>( 6829 CA->getElementType()->getAsArrayTypeUnsafe()); 6830 } while (CA); 6831 return ElementCount; 6832 } 6833 6834 /// getFloatingRank - Return a relative rank for floating point types. 6835 /// This routine will assert if passed a built-in type that isn't a float. 6836 static FloatingRank getFloatingRank(QualType T) { 6837 if (const auto *CT = T->getAs<ComplexType>()) 6838 return getFloatingRank(CT->getElementType()); 6839 6840 switch (T->castAs<BuiltinType>()->getKind()) { 6841 default: llvm_unreachable("getFloatingRank(): not a floating type"); 6842 case BuiltinType::Float16: return Float16Rank; 6843 case BuiltinType::Half: return HalfRank; 6844 case BuiltinType::Float: return FloatRank; 6845 case BuiltinType::Double: return DoubleRank; 6846 case BuiltinType::LongDouble: return LongDoubleRank; 6847 case BuiltinType::Float128: return Float128Rank; 6848 case BuiltinType::BFloat16: return BFloat16Rank; 6849 case BuiltinType::Ibm128: return Ibm128Rank; 6850 } 6851 } 6852 6853 /// getFloatingTypeOrder - Compare the rank of the two specified floating 6854 /// point types, ignoring the domain of the type (i.e. 'double' == 6855 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If 6856 /// LHS < RHS, return -1. 6857 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const { 6858 FloatingRank LHSR = getFloatingRank(LHS); 6859 FloatingRank RHSR = getFloatingRank(RHS); 6860 6861 if (LHSR == RHSR) 6862 return 0; 6863 if (LHSR > RHSR) 6864 return 1; 6865 return -1; 6866 } 6867 6868 int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const { 6869 if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS)) 6870 return 0; 6871 return getFloatingTypeOrder(LHS, RHS); 6872 } 6873 6874 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This 6875 /// routine will assert if passed a built-in type that isn't an integer or enum, 6876 /// or if it is not canonicalized. 6877 unsigned ASTContext::getIntegerRank(const Type *T) const { 6878 assert(T->isCanonicalUnqualified() && "T should be canonicalized"); 6879 6880 // Results in this 'losing' to any type of the same size, but winning if 6881 // larger. 6882 if (const auto *EIT = dyn_cast<BitIntType>(T)) 6883 return 0 + (EIT->getNumBits() << 3); 6884 6885 switch (cast<BuiltinType>(T)->getKind()) { 6886 default: llvm_unreachable("getIntegerRank(): not a built-in integer"); 6887 case BuiltinType::Bool: 6888 return 1 + (getIntWidth(BoolTy) << 3); 6889 case BuiltinType::Char_S: 6890 case BuiltinType::Char_U: 6891 case BuiltinType::SChar: 6892 case BuiltinType::UChar: 6893 return 2 + (getIntWidth(CharTy) << 3); 6894 case BuiltinType::Short: 6895 case BuiltinType::UShort: 6896 return 3 + (getIntWidth(ShortTy) << 3); 6897 case BuiltinType::Int: 6898 case BuiltinType::UInt: 6899 return 4 + (getIntWidth(IntTy) << 3); 6900 case BuiltinType::Long: 6901 case BuiltinType::ULong: 6902 return 5 + (getIntWidth(LongTy) << 3); 6903 case BuiltinType::LongLong: 6904 case BuiltinType::ULongLong: 6905 return 6 + (getIntWidth(LongLongTy) << 3); 6906 case BuiltinType::Int128: 6907 case BuiltinType::UInt128: 6908 return 7 + (getIntWidth(Int128Ty) << 3); 6909 } 6910 } 6911 6912 /// Whether this is a promotable bitfield reference according 6913 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions). 6914 /// 6915 /// \returns the type this bit-field will promote to, or NULL if no 6916 /// promotion occurs. 6917 QualType ASTContext::isPromotableBitField(Expr *E) const { 6918 if (E->isTypeDependent() || E->isValueDependent()) 6919 return {}; 6920 6921 // C++ [conv.prom]p5: 6922 // If the bit-field has an enumerated type, it is treated as any other 6923 // value of that type for promotion purposes. 6924 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType()) 6925 return {}; 6926 6927 // FIXME: We should not do this unless E->refersToBitField() is true. This 6928 // matters in C where getSourceBitField() will find bit-fields for various 6929 // cases where the source expression is not a bit-field designator. 6930 6931 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields? 6932 if (!Field) 6933 return {}; 6934 6935 QualType FT = Field->getType(); 6936 6937 uint64_t BitWidth = Field->getBitWidthValue(*this); 6938 uint64_t IntSize = getTypeSize(IntTy); 6939 // C++ [conv.prom]p5: 6940 // A prvalue for an integral bit-field can be converted to a prvalue of type 6941 // int if int can represent all the values of the bit-field; otherwise, it 6942 // can be converted to unsigned int if unsigned int can represent all the 6943 // values of the bit-field. If the bit-field is larger yet, no integral 6944 // promotion applies to it. 6945 // C11 6.3.1.1/2: 6946 // [For a bit-field of type _Bool, int, signed int, or unsigned int:] 6947 // If an int can represent all values of the original type (as restricted by 6948 // the width, for a bit-field), the value is converted to an int; otherwise, 6949 // it is converted to an unsigned int. 6950 // 6951 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int. 6952 // We perform that promotion here to match GCC and C++. 6953 // FIXME: C does not permit promotion of an enum bit-field whose rank is 6954 // greater than that of 'int'. We perform that promotion to match GCC. 6955 if (BitWidth < IntSize) 6956 return IntTy; 6957 6958 if (BitWidth == IntSize) 6959 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy; 6960 6961 // Bit-fields wider than int are not subject to promotions, and therefore act 6962 // like the base type. GCC has some weird bugs in this area that we 6963 // deliberately do not follow (GCC follows a pre-standard resolution to 6964 // C's DR315 which treats bit-width as being part of the type, and this leaks 6965 // into their semantics in some cases). 6966 return {}; 6967 } 6968 6969 /// getPromotedIntegerType - Returns the type that Promotable will 6970 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable 6971 /// integer type. 6972 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const { 6973 assert(!Promotable.isNull()); 6974 assert(Promotable->isPromotableIntegerType()); 6975 if (const auto *ET = Promotable->getAs<EnumType>()) 6976 return ET->getDecl()->getPromotionType(); 6977 6978 if (const auto *BT = Promotable->getAs<BuiltinType>()) { 6979 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t 6980 // (3.9.1) can be converted to a prvalue of the first of the following 6981 // types that can represent all the values of its underlying type: 6982 // int, unsigned int, long int, unsigned long int, long long int, or 6983 // unsigned long long int [...] 6984 // FIXME: Is there some better way to compute this? 6985 if (BT->getKind() == BuiltinType::WChar_S || 6986 BT->getKind() == BuiltinType::WChar_U || 6987 BT->getKind() == BuiltinType::Char8 || 6988 BT->getKind() == BuiltinType::Char16 || 6989 BT->getKind() == BuiltinType::Char32) { 6990 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S; 6991 uint64_t FromSize = getTypeSize(BT); 6992 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy, 6993 LongLongTy, UnsignedLongLongTy }; 6994 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) { 6995 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]); 6996 if (FromSize < ToSize || 6997 (FromSize == ToSize && 6998 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) 6999 return PromoteTypes[Idx]; 7000 } 7001 llvm_unreachable("char type should fit into long long"); 7002 } 7003 } 7004 7005 // At this point, we should have a signed or unsigned integer type. 7006 if (Promotable->isSignedIntegerType()) 7007 return IntTy; 7008 uint64_t PromotableSize = getIntWidth(Promotable); 7009 uint64_t IntSize = getIntWidth(IntTy); 7010 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize); 7011 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy; 7012 } 7013 7014 /// Recurses in pointer/array types until it finds an objc retainable 7015 /// type and returns its ownership. 7016 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const { 7017 while (!T.isNull()) { 7018 if (T.getObjCLifetime() != Qualifiers::OCL_None) 7019 return T.getObjCLifetime(); 7020 if (T->isArrayType()) 7021 T = getBaseElementType(T); 7022 else if (const auto *PT = T->getAs<PointerType>()) 7023 T = PT->getPointeeType(); 7024 else if (const auto *RT = T->getAs<ReferenceType>()) 7025 T = RT->getPointeeType(); 7026 else 7027 break; 7028 } 7029 7030 return Qualifiers::OCL_None; 7031 } 7032 7033 static const Type *getIntegerTypeForEnum(const EnumType *ET) { 7034 // Incomplete enum types are not treated as integer types. 7035 // FIXME: In C++, enum types are never integer types. 7036 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped()) 7037 return ET->getDecl()->getIntegerType().getTypePtr(); 7038 return nullptr; 7039 } 7040 7041 /// getIntegerTypeOrder - Returns the highest ranked integer type: 7042 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If 7043 /// LHS < RHS, return -1. 7044 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const { 7045 const Type *LHSC = getCanonicalType(LHS).getTypePtr(); 7046 const Type *RHSC = getCanonicalType(RHS).getTypePtr(); 7047 7048 // Unwrap enums to their underlying type. 7049 if (const auto *ET = dyn_cast<EnumType>(LHSC)) 7050 LHSC = getIntegerTypeForEnum(ET); 7051 if (const auto *ET = dyn_cast<EnumType>(RHSC)) 7052 RHSC = getIntegerTypeForEnum(ET); 7053 7054 if (LHSC == RHSC) return 0; 7055 7056 bool LHSUnsigned = LHSC->isUnsignedIntegerType(); 7057 bool RHSUnsigned = RHSC->isUnsignedIntegerType(); 7058 7059 unsigned LHSRank = getIntegerRank(LHSC); 7060 unsigned RHSRank = getIntegerRank(RHSC); 7061 7062 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned. 7063 if (LHSRank == RHSRank) return 0; 7064 return LHSRank > RHSRank ? 1 : -1; 7065 } 7066 7067 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa. 7068 if (LHSUnsigned) { 7069 // If the unsigned [LHS] type is larger, return it. 7070 if (LHSRank >= RHSRank) 7071 return 1; 7072 7073 // If the signed type can represent all values of the unsigned type, it 7074 // wins. Because we are dealing with 2's complement and types that are 7075 // powers of two larger than each other, this is always safe. 7076 return -1; 7077 } 7078 7079 // If the unsigned [RHS] type is larger, return it. 7080 if (RHSRank >= LHSRank) 7081 return -1; 7082 7083 // If the signed type can represent all values of the unsigned type, it 7084 // wins. Because we are dealing with 2's complement and types that are 7085 // powers of two larger than each other, this is always safe. 7086 return 1; 7087 } 7088 7089 TypedefDecl *ASTContext::getCFConstantStringDecl() const { 7090 if (CFConstantStringTypeDecl) 7091 return CFConstantStringTypeDecl; 7092 7093 assert(!CFConstantStringTagDecl && 7094 "tag and typedef should be initialized together"); 7095 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag"); 7096 CFConstantStringTagDecl->startDefinition(); 7097 7098 struct { 7099 QualType Type; 7100 const char *Name; 7101 } Fields[5]; 7102 unsigned Count = 0; 7103 7104 /// Objective-C ABI 7105 /// 7106 /// typedef struct __NSConstantString_tag { 7107 /// const int *isa; 7108 /// int flags; 7109 /// const char *str; 7110 /// long length; 7111 /// } __NSConstantString; 7112 /// 7113 /// Swift ABI (4.1, 4.2) 7114 /// 7115 /// typedef struct __NSConstantString_tag { 7116 /// uintptr_t _cfisa; 7117 /// uintptr_t _swift_rc; 7118 /// _Atomic(uint64_t) _cfinfoa; 7119 /// const char *_ptr; 7120 /// uint32_t _length; 7121 /// } __NSConstantString; 7122 /// 7123 /// Swift ABI (5.0) 7124 /// 7125 /// typedef struct __NSConstantString_tag { 7126 /// uintptr_t _cfisa; 7127 /// uintptr_t _swift_rc; 7128 /// _Atomic(uint64_t) _cfinfoa; 7129 /// const char *_ptr; 7130 /// uintptr_t _length; 7131 /// } __NSConstantString; 7132 7133 const auto CFRuntime = getLangOpts().CFRuntime; 7134 if (static_cast<unsigned>(CFRuntime) < 7135 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) { 7136 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" }; 7137 Fields[Count++] = { IntTy, "flags" }; 7138 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" }; 7139 Fields[Count++] = { LongTy, "length" }; 7140 } else { 7141 Fields[Count++] = { getUIntPtrType(), "_cfisa" }; 7142 Fields[Count++] = { getUIntPtrType(), "_swift_rc" }; 7143 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" }; 7144 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" }; 7145 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 || 7146 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2) 7147 Fields[Count++] = { IntTy, "_ptr" }; 7148 else 7149 Fields[Count++] = { getUIntPtrType(), "_ptr" }; 7150 } 7151 7152 // Create fields 7153 for (unsigned i = 0; i < Count; ++i) { 7154 FieldDecl *Field = 7155 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(), 7156 SourceLocation(), &Idents.get(Fields[i].Name), 7157 Fields[i].Type, /*TInfo=*/nullptr, 7158 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); 7159 Field->setAccess(AS_public); 7160 CFConstantStringTagDecl->addDecl(Field); 7161 } 7162 7163 CFConstantStringTagDecl->completeDefinition(); 7164 // This type is designed to be compatible with NSConstantString, but cannot 7165 // use the same name, since NSConstantString is an interface. 7166 auto tagType = getTagDeclType(CFConstantStringTagDecl); 7167 CFConstantStringTypeDecl = 7168 buildImplicitTypedef(tagType, "__NSConstantString"); 7169 7170 return CFConstantStringTypeDecl; 7171 } 7172 7173 RecordDecl *ASTContext::getCFConstantStringTagDecl() const { 7174 if (!CFConstantStringTagDecl) 7175 getCFConstantStringDecl(); // Build the tag and the typedef. 7176 return CFConstantStringTagDecl; 7177 } 7178 7179 // getCFConstantStringType - Return the type used for constant CFStrings. 7180 QualType ASTContext::getCFConstantStringType() const { 7181 return getTypedefType(getCFConstantStringDecl()); 7182 } 7183 7184 QualType ASTContext::getObjCSuperType() const { 7185 if (ObjCSuperType.isNull()) { 7186 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super"); 7187 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl); 7188 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl); 7189 } 7190 return ObjCSuperType; 7191 } 7192 7193 void ASTContext::setCFConstantStringType(QualType T) { 7194 const auto *TD = T->castAs<TypedefType>(); 7195 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl()); 7196 const auto *TagType = 7197 CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>(); 7198 CFConstantStringTagDecl = TagType->getDecl(); 7199 } 7200 7201 QualType ASTContext::getBlockDescriptorType() const { 7202 if (BlockDescriptorType) 7203 return getTagDeclType(BlockDescriptorType); 7204 7205 RecordDecl *RD; 7206 // FIXME: Needs the FlagAppleBlock bit. 7207 RD = buildImplicitRecord("__block_descriptor"); 7208 RD->startDefinition(); 7209 7210 QualType FieldTypes[] = { 7211 UnsignedLongTy, 7212 UnsignedLongTy, 7213 }; 7214 7215 static const char *const FieldNames[] = { 7216 "reserved", 7217 "Size" 7218 }; 7219 7220 for (size_t i = 0; i < 2; ++i) { 7221 FieldDecl *Field = FieldDecl::Create( 7222 *this, RD, SourceLocation(), SourceLocation(), 7223 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, 7224 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); 7225 Field->setAccess(AS_public); 7226 RD->addDecl(Field); 7227 } 7228 7229 RD->completeDefinition(); 7230 7231 BlockDescriptorType = RD; 7232 7233 return getTagDeclType(BlockDescriptorType); 7234 } 7235 7236 QualType ASTContext::getBlockDescriptorExtendedType() const { 7237 if (BlockDescriptorExtendedType) 7238 return getTagDeclType(BlockDescriptorExtendedType); 7239 7240 RecordDecl *RD; 7241 // FIXME: Needs the FlagAppleBlock bit. 7242 RD = buildImplicitRecord("__block_descriptor_withcopydispose"); 7243 RD->startDefinition(); 7244 7245 QualType FieldTypes[] = { 7246 UnsignedLongTy, 7247 UnsignedLongTy, 7248 getPointerType(VoidPtrTy), 7249 getPointerType(VoidPtrTy) 7250 }; 7251 7252 static const char *const FieldNames[] = { 7253 "reserved", 7254 "Size", 7255 "CopyFuncPtr", 7256 "DestroyFuncPtr" 7257 }; 7258 7259 for (size_t i = 0; i < 4; ++i) { 7260 FieldDecl *Field = FieldDecl::Create( 7261 *this, RD, SourceLocation(), SourceLocation(), 7262 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, 7263 /*BitWidth=*/nullptr, 7264 /*Mutable=*/false, ICIS_NoInit); 7265 Field->setAccess(AS_public); 7266 RD->addDecl(Field); 7267 } 7268 7269 RD->completeDefinition(); 7270 7271 BlockDescriptorExtendedType = RD; 7272 return getTagDeclType(BlockDescriptorExtendedType); 7273 } 7274 7275 OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const { 7276 const auto *BT = dyn_cast<BuiltinType>(T); 7277 7278 if (!BT) { 7279 if (isa<PipeType>(T)) 7280 return OCLTK_Pipe; 7281 7282 return OCLTK_Default; 7283 } 7284 7285 switch (BT->getKind()) { 7286 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 7287 case BuiltinType::Id: \ 7288 return OCLTK_Image; 7289 #include "clang/Basic/OpenCLImageTypes.def" 7290 7291 case BuiltinType::OCLClkEvent: 7292 return OCLTK_ClkEvent; 7293 7294 case BuiltinType::OCLEvent: 7295 return OCLTK_Event; 7296 7297 case BuiltinType::OCLQueue: 7298 return OCLTK_Queue; 7299 7300 case BuiltinType::OCLReserveID: 7301 return OCLTK_ReserveID; 7302 7303 case BuiltinType::OCLSampler: 7304 return OCLTK_Sampler; 7305 7306 default: 7307 return OCLTK_Default; 7308 } 7309 } 7310 7311 LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const { 7312 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)); 7313 } 7314 7315 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty" 7316 /// requires copy/dispose. Note that this must match the logic 7317 /// in buildByrefHelpers. 7318 bool ASTContext::BlockRequiresCopying(QualType Ty, 7319 const VarDecl *D) { 7320 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) { 7321 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr(); 7322 if (!copyExpr && record->hasTrivialDestructor()) return false; 7323 7324 return true; 7325 } 7326 7327 // The block needs copy/destroy helpers if Ty is non-trivial to destructively 7328 // move or destroy. 7329 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType()) 7330 return true; 7331 7332 if (!Ty->isObjCRetainableType()) return false; 7333 7334 Qualifiers qs = Ty.getQualifiers(); 7335 7336 // If we have lifetime, that dominates. 7337 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) { 7338 switch (lifetime) { 7339 case Qualifiers::OCL_None: llvm_unreachable("impossible"); 7340 7341 // These are just bits as far as the runtime is concerned. 7342 case Qualifiers::OCL_ExplicitNone: 7343 case Qualifiers::OCL_Autoreleasing: 7344 return false; 7345 7346 // These cases should have been taken care of when checking the type's 7347 // non-triviality. 7348 case Qualifiers::OCL_Weak: 7349 case Qualifiers::OCL_Strong: 7350 llvm_unreachable("impossible"); 7351 } 7352 llvm_unreachable("fell out of lifetime switch!"); 7353 } 7354 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) || 7355 Ty->isObjCObjectPointerType()); 7356 } 7357 7358 bool ASTContext::getByrefLifetime(QualType Ty, 7359 Qualifiers::ObjCLifetime &LifeTime, 7360 bool &HasByrefExtendedLayout) const { 7361 if (!getLangOpts().ObjC || 7362 getLangOpts().getGC() != LangOptions::NonGC) 7363 return false; 7364 7365 HasByrefExtendedLayout = false; 7366 if (Ty->isRecordType()) { 7367 HasByrefExtendedLayout = true; 7368 LifeTime = Qualifiers::OCL_None; 7369 } else if ((LifeTime = Ty.getObjCLifetime())) { 7370 // Honor the ARC qualifiers. 7371 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) { 7372 // The MRR rule. 7373 LifeTime = Qualifiers::OCL_ExplicitNone; 7374 } else { 7375 LifeTime = Qualifiers::OCL_None; 7376 } 7377 return true; 7378 } 7379 7380 CanQualType ASTContext::getNSUIntegerType() const { 7381 assert(Target && "Expected target to be initialized"); 7382 const llvm::Triple &T = Target->getTriple(); 7383 // Windows is LLP64 rather than LP64 7384 if (T.isOSWindows() && T.isArch64Bit()) 7385 return UnsignedLongLongTy; 7386 return UnsignedLongTy; 7387 } 7388 7389 CanQualType ASTContext::getNSIntegerType() const { 7390 assert(Target && "Expected target to be initialized"); 7391 const llvm::Triple &T = Target->getTriple(); 7392 // Windows is LLP64 rather than LP64 7393 if (T.isOSWindows() && T.isArch64Bit()) 7394 return LongLongTy; 7395 return LongTy; 7396 } 7397 7398 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() { 7399 if (!ObjCInstanceTypeDecl) 7400 ObjCInstanceTypeDecl = 7401 buildImplicitTypedef(getObjCIdType(), "instancetype"); 7402 return ObjCInstanceTypeDecl; 7403 } 7404 7405 // This returns true if a type has been typedefed to BOOL: 7406 // typedef <type> BOOL; 7407 static bool isTypeTypedefedAsBOOL(QualType T) { 7408 if (const auto *TT = dyn_cast<TypedefType>(T)) 7409 if (IdentifierInfo *II = TT->getDecl()->getIdentifier()) 7410 return II->isStr("BOOL"); 7411 7412 return false; 7413 } 7414 7415 /// getObjCEncodingTypeSize returns size of type for objective-c encoding 7416 /// purpose. 7417 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const { 7418 if (!type->isIncompleteArrayType() && type->isIncompleteType()) 7419 return CharUnits::Zero(); 7420 7421 CharUnits sz = getTypeSizeInChars(type); 7422 7423 // Make all integer and enum types at least as large as an int 7424 if (sz.isPositive() && type->isIntegralOrEnumerationType()) 7425 sz = std::max(sz, getTypeSizeInChars(IntTy)); 7426 // Treat arrays as pointers, since that's how they're passed in. 7427 else if (type->isArrayType()) 7428 sz = getTypeSizeInChars(VoidPtrTy); 7429 return sz; 7430 } 7431 7432 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const { 7433 return getTargetInfo().getCXXABI().isMicrosoft() && 7434 VD->isStaticDataMember() && 7435 VD->getType()->isIntegralOrEnumerationType() && 7436 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit(); 7437 } 7438 7439 ASTContext::InlineVariableDefinitionKind 7440 ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const { 7441 if (!VD->isInline()) 7442 return InlineVariableDefinitionKind::None; 7443 7444 // In almost all cases, it's a weak definition. 7445 auto *First = VD->getFirstDecl(); 7446 if (First->isInlineSpecified() || !First->isStaticDataMember()) 7447 return InlineVariableDefinitionKind::Weak; 7448 7449 // If there's a file-context declaration in this translation unit, it's a 7450 // non-discardable definition. 7451 for (auto *D : VD->redecls()) 7452 if (D->getLexicalDeclContext()->isFileContext() && 7453 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr())) 7454 return InlineVariableDefinitionKind::Strong; 7455 7456 // If we've not seen one yet, we don't know. 7457 return InlineVariableDefinitionKind::WeakUnknown; 7458 } 7459 7460 static std::string charUnitsToString(const CharUnits &CU) { 7461 return llvm::itostr(CU.getQuantity()); 7462 } 7463 7464 /// getObjCEncodingForBlock - Return the encoded type for this block 7465 /// declaration. 7466 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const { 7467 std::string S; 7468 7469 const BlockDecl *Decl = Expr->getBlockDecl(); 7470 QualType BlockTy = 7471 Expr->getType()->castAs<BlockPointerType>()->getPointeeType(); 7472 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType(); 7473 // Encode result type. 7474 if (getLangOpts().EncodeExtendedBlockSig) 7475 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, BlockReturnTy, S, 7476 true /*Extended*/); 7477 else 7478 getObjCEncodingForType(BlockReturnTy, S); 7479 // Compute size of all parameters. 7480 // Start with computing size of a pointer in number of bytes. 7481 // FIXME: There might(should) be a better way of doing this computation! 7482 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 7483 CharUnits ParmOffset = PtrSize; 7484 for (auto PI : Decl->parameters()) { 7485 QualType PType = PI->getType(); 7486 CharUnits sz = getObjCEncodingTypeSize(PType); 7487 if (sz.isZero()) 7488 continue; 7489 assert(sz.isPositive() && "BlockExpr - Incomplete param type"); 7490 ParmOffset += sz; 7491 } 7492 // Size of the argument frame 7493 S += charUnitsToString(ParmOffset); 7494 // Block pointer and offset. 7495 S += "@?0"; 7496 7497 // Argument types. 7498 ParmOffset = PtrSize; 7499 for (auto PVDecl : Decl->parameters()) { 7500 QualType PType = PVDecl->getOriginalType(); 7501 if (const auto *AT = 7502 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 7503 // Use array's original type only if it has known number of 7504 // elements. 7505 if (!isa<ConstantArrayType>(AT)) 7506 PType = PVDecl->getType(); 7507 } else if (PType->isFunctionType()) 7508 PType = PVDecl->getType(); 7509 if (getLangOpts().EncodeExtendedBlockSig) 7510 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType, 7511 S, true /*Extended*/); 7512 else 7513 getObjCEncodingForType(PType, S); 7514 S += charUnitsToString(ParmOffset); 7515 ParmOffset += getObjCEncodingTypeSize(PType); 7516 } 7517 7518 return S; 7519 } 7520 7521 std::string 7522 ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const { 7523 std::string S; 7524 // Encode result type. 7525 getObjCEncodingForType(Decl->getReturnType(), S); 7526 CharUnits ParmOffset; 7527 // Compute size of all parameters. 7528 for (auto PI : Decl->parameters()) { 7529 QualType PType = PI->getType(); 7530 CharUnits sz = getObjCEncodingTypeSize(PType); 7531 if (sz.isZero()) 7532 continue; 7533 7534 assert(sz.isPositive() && 7535 "getObjCEncodingForFunctionDecl - Incomplete param type"); 7536 ParmOffset += sz; 7537 } 7538 S += charUnitsToString(ParmOffset); 7539 ParmOffset = CharUnits::Zero(); 7540 7541 // Argument types. 7542 for (auto PVDecl : Decl->parameters()) { 7543 QualType PType = PVDecl->getOriginalType(); 7544 if (const auto *AT = 7545 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 7546 // Use array's original type only if it has known number of 7547 // elements. 7548 if (!isa<ConstantArrayType>(AT)) 7549 PType = PVDecl->getType(); 7550 } else if (PType->isFunctionType()) 7551 PType = PVDecl->getType(); 7552 getObjCEncodingForType(PType, S); 7553 S += charUnitsToString(ParmOffset); 7554 ParmOffset += getObjCEncodingTypeSize(PType); 7555 } 7556 7557 return S; 7558 } 7559 7560 /// getObjCEncodingForMethodParameter - Return the encoded type for a single 7561 /// method parameter or return type. If Extended, include class names and 7562 /// block object types. 7563 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, 7564 QualType T, std::string& S, 7565 bool Extended) const { 7566 // Encode type qualifier, 'in', 'inout', etc. for the parameter. 7567 getObjCEncodingForTypeQualifier(QT, S); 7568 // Encode parameter type. 7569 ObjCEncOptions Options = ObjCEncOptions() 7570 .setExpandPointedToStructures() 7571 .setExpandStructures() 7572 .setIsOutermostType(); 7573 if (Extended) 7574 Options.setEncodeBlockParameters().setEncodeClassNames(); 7575 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr); 7576 } 7577 7578 /// getObjCEncodingForMethodDecl - Return the encoded type for this method 7579 /// declaration. 7580 std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, 7581 bool Extended) const { 7582 // FIXME: This is not very efficient. 7583 // Encode return type. 7584 std::string S; 7585 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(), 7586 Decl->getReturnType(), S, Extended); 7587 // Compute size of all parameters. 7588 // Start with computing size of a pointer in number of bytes. 7589 // FIXME: There might(should) be a better way of doing this computation! 7590 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 7591 // The first two arguments (self and _cmd) are pointers; account for 7592 // their size. 7593 CharUnits ParmOffset = 2 * PtrSize; 7594 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 7595 E = Decl->sel_param_end(); PI != E; ++PI) { 7596 QualType PType = (*PI)->getType(); 7597 CharUnits sz = getObjCEncodingTypeSize(PType); 7598 if (sz.isZero()) 7599 continue; 7600 7601 assert(sz.isPositive() && 7602 "getObjCEncodingForMethodDecl - Incomplete param type"); 7603 ParmOffset += sz; 7604 } 7605 S += charUnitsToString(ParmOffset); 7606 S += "@0:"; 7607 S += charUnitsToString(PtrSize); 7608 7609 // Argument types. 7610 ParmOffset = 2 * PtrSize; 7611 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 7612 E = Decl->sel_param_end(); PI != E; ++PI) { 7613 const ParmVarDecl *PVDecl = *PI; 7614 QualType PType = PVDecl->getOriginalType(); 7615 if (const auto *AT = 7616 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 7617 // Use array's original type only if it has known number of 7618 // elements. 7619 if (!isa<ConstantArrayType>(AT)) 7620 PType = PVDecl->getType(); 7621 } else if (PType->isFunctionType()) 7622 PType = PVDecl->getType(); 7623 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(), 7624 PType, S, Extended); 7625 S += charUnitsToString(ParmOffset); 7626 ParmOffset += getObjCEncodingTypeSize(PType); 7627 } 7628 7629 return S; 7630 } 7631 7632 ObjCPropertyImplDecl * 7633 ASTContext::getObjCPropertyImplDeclForPropertyDecl( 7634 const ObjCPropertyDecl *PD, 7635 const Decl *Container) const { 7636 if (!Container) 7637 return nullptr; 7638 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) { 7639 for (auto *PID : CID->property_impls()) 7640 if (PID->getPropertyDecl() == PD) 7641 return PID; 7642 } else { 7643 const auto *OID = cast<ObjCImplementationDecl>(Container); 7644 for (auto *PID : OID->property_impls()) 7645 if (PID->getPropertyDecl() == PD) 7646 return PID; 7647 } 7648 return nullptr; 7649 } 7650 7651 /// getObjCEncodingForPropertyDecl - Return the encoded type for this 7652 /// property declaration. If non-NULL, Container must be either an 7653 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be 7654 /// NULL when getting encodings for protocol properties. 7655 /// Property attributes are stored as a comma-delimited C string. The simple 7656 /// attributes readonly and bycopy are encoded as single characters. The 7657 /// parametrized attributes, getter=name, setter=name, and ivar=name, are 7658 /// encoded as single characters, followed by an identifier. Property types 7659 /// are also encoded as a parametrized attribute. The characters used to encode 7660 /// these attributes are defined by the following enumeration: 7661 /// @code 7662 /// enum PropertyAttributes { 7663 /// kPropertyReadOnly = 'R', // property is read-only. 7664 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned 7665 /// kPropertyByref = '&', // property is a reference to the value last assigned 7666 /// kPropertyDynamic = 'D', // property is dynamic 7667 /// kPropertyGetter = 'G', // followed by getter selector name 7668 /// kPropertySetter = 'S', // followed by setter selector name 7669 /// kPropertyInstanceVariable = 'V' // followed by instance variable name 7670 /// kPropertyType = 'T' // followed by old-style type encoding. 7671 /// kPropertyWeak = 'W' // 'weak' property 7672 /// kPropertyStrong = 'P' // property GC'able 7673 /// kPropertyNonAtomic = 'N' // property non-atomic 7674 /// }; 7675 /// @endcode 7676 std::string 7677 ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, 7678 const Decl *Container) const { 7679 // Collect information from the property implementation decl(s). 7680 bool Dynamic = false; 7681 ObjCPropertyImplDecl *SynthesizePID = nullptr; 7682 7683 if (ObjCPropertyImplDecl *PropertyImpDecl = 7684 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) { 7685 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) 7686 Dynamic = true; 7687 else 7688 SynthesizePID = PropertyImpDecl; 7689 } 7690 7691 // FIXME: This is not very efficient. 7692 std::string S = "T"; 7693 7694 // Encode result type. 7695 // GCC has some special rules regarding encoding of properties which 7696 // closely resembles encoding of ivars. 7697 getObjCEncodingForPropertyType(PD->getType(), S); 7698 7699 if (PD->isReadOnly()) { 7700 S += ",R"; 7701 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy) 7702 S += ",C"; 7703 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain) 7704 S += ",&"; 7705 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak) 7706 S += ",W"; 7707 } else { 7708 switch (PD->getSetterKind()) { 7709 case ObjCPropertyDecl::Assign: break; 7710 case ObjCPropertyDecl::Copy: S += ",C"; break; 7711 case ObjCPropertyDecl::Retain: S += ",&"; break; 7712 case ObjCPropertyDecl::Weak: S += ",W"; break; 7713 } 7714 } 7715 7716 // It really isn't clear at all what this means, since properties 7717 // are "dynamic by default". 7718 if (Dynamic) 7719 S += ",D"; 7720 7721 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_nonatomic) 7722 S += ",N"; 7723 7724 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) { 7725 S += ",G"; 7726 S += PD->getGetterName().getAsString(); 7727 } 7728 7729 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) { 7730 S += ",S"; 7731 S += PD->getSetterName().getAsString(); 7732 } 7733 7734 if (SynthesizePID) { 7735 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl(); 7736 S += ",V"; 7737 S += OID->getNameAsString(); 7738 } 7739 7740 // FIXME: OBJCGC: weak & strong 7741 return S; 7742 } 7743 7744 /// getLegacyIntegralTypeEncoding - 7745 /// Another legacy compatibility encoding: 32-bit longs are encoded as 7746 /// 'l' or 'L' , but not always. For typedefs, we need to use 7747 /// 'i' or 'I' instead if encoding a struct field, or a pointer! 7748 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const { 7749 if (isa<TypedefType>(PointeeTy.getTypePtr())) { 7750 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) { 7751 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32) 7752 PointeeTy = UnsignedIntTy; 7753 else 7754 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32) 7755 PointeeTy = IntTy; 7756 } 7757 } 7758 } 7759 7760 void ASTContext::getObjCEncodingForType(QualType T, std::string& S, 7761 const FieldDecl *Field, 7762 QualType *NotEncodedT) const { 7763 // We follow the behavior of gcc, expanding structures which are 7764 // directly pointed to, and expanding embedded structures. Note that 7765 // these rules are sufficient to prevent recursive encoding of the 7766 // same type. 7767 getObjCEncodingForTypeImpl(T, S, 7768 ObjCEncOptions() 7769 .setExpandPointedToStructures() 7770 .setExpandStructures() 7771 .setIsOutermostType(), 7772 Field, NotEncodedT); 7773 } 7774 7775 void ASTContext::getObjCEncodingForPropertyType(QualType T, 7776 std::string& S) const { 7777 // Encode result type. 7778 // GCC has some special rules regarding encoding of properties which 7779 // closely resembles encoding of ivars. 7780 getObjCEncodingForTypeImpl(T, S, 7781 ObjCEncOptions() 7782 .setExpandPointedToStructures() 7783 .setExpandStructures() 7784 .setIsOutermostType() 7785 .setEncodingProperty(), 7786 /*Field=*/nullptr); 7787 } 7788 7789 static char getObjCEncodingForPrimitiveType(const ASTContext *C, 7790 const BuiltinType *BT) { 7791 BuiltinType::Kind kind = BT->getKind(); 7792 switch (kind) { 7793 case BuiltinType::Void: return 'v'; 7794 case BuiltinType::Bool: return 'B'; 7795 case BuiltinType::Char8: 7796 case BuiltinType::Char_U: 7797 case BuiltinType::UChar: return 'C'; 7798 case BuiltinType::Char16: 7799 case BuiltinType::UShort: return 'S'; 7800 case BuiltinType::Char32: 7801 case BuiltinType::UInt: return 'I'; 7802 case BuiltinType::ULong: 7803 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q'; 7804 case BuiltinType::UInt128: return 'T'; 7805 case BuiltinType::ULongLong: return 'Q'; 7806 case BuiltinType::Char_S: 7807 case BuiltinType::SChar: return 'c'; 7808 case BuiltinType::Short: return 's'; 7809 case BuiltinType::WChar_S: 7810 case BuiltinType::WChar_U: 7811 case BuiltinType::Int: return 'i'; 7812 case BuiltinType::Long: 7813 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q'; 7814 case BuiltinType::LongLong: return 'q'; 7815 case BuiltinType::Int128: return 't'; 7816 case BuiltinType::Float: return 'f'; 7817 case BuiltinType::Double: return 'd'; 7818 case BuiltinType::LongDouble: return 'D'; 7819 case BuiltinType::NullPtr: return '*'; // like char* 7820 7821 case BuiltinType::BFloat16: 7822 case BuiltinType::Float16: 7823 case BuiltinType::Float128: 7824 case BuiltinType::Ibm128: 7825 case BuiltinType::Half: 7826 case BuiltinType::ShortAccum: 7827 case BuiltinType::Accum: 7828 case BuiltinType::LongAccum: 7829 case BuiltinType::UShortAccum: 7830 case BuiltinType::UAccum: 7831 case BuiltinType::ULongAccum: 7832 case BuiltinType::ShortFract: 7833 case BuiltinType::Fract: 7834 case BuiltinType::LongFract: 7835 case BuiltinType::UShortFract: 7836 case BuiltinType::UFract: 7837 case BuiltinType::ULongFract: 7838 case BuiltinType::SatShortAccum: 7839 case BuiltinType::SatAccum: 7840 case BuiltinType::SatLongAccum: 7841 case BuiltinType::SatUShortAccum: 7842 case BuiltinType::SatUAccum: 7843 case BuiltinType::SatULongAccum: 7844 case BuiltinType::SatShortFract: 7845 case BuiltinType::SatFract: 7846 case BuiltinType::SatLongFract: 7847 case BuiltinType::SatUShortFract: 7848 case BuiltinType::SatUFract: 7849 case BuiltinType::SatULongFract: 7850 // FIXME: potentially need @encodes for these! 7851 return ' '; 7852 7853 #define SVE_TYPE(Name, Id, SingletonId) \ 7854 case BuiltinType::Id: 7855 #include "clang/Basic/AArch64SVEACLETypes.def" 7856 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 7857 #include "clang/Basic/RISCVVTypes.def" 7858 { 7859 DiagnosticsEngine &Diags = C->getDiagnostics(); 7860 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 7861 "cannot yet @encode type %0"); 7862 Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy()); 7863 return ' '; 7864 } 7865 7866 case BuiltinType::ObjCId: 7867 case BuiltinType::ObjCClass: 7868 case BuiltinType::ObjCSel: 7869 llvm_unreachable("@encoding ObjC primitive type"); 7870 7871 // OpenCL and placeholder types don't need @encodings. 7872 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 7873 case BuiltinType::Id: 7874 #include "clang/Basic/OpenCLImageTypes.def" 7875 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 7876 case BuiltinType::Id: 7877 #include "clang/Basic/OpenCLExtensionTypes.def" 7878 case BuiltinType::OCLEvent: 7879 case BuiltinType::OCLClkEvent: 7880 case BuiltinType::OCLQueue: 7881 case BuiltinType::OCLReserveID: 7882 case BuiltinType::OCLSampler: 7883 case BuiltinType::Dependent: 7884 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 7885 case BuiltinType::Id: 7886 #include "clang/Basic/PPCTypes.def" 7887 #define BUILTIN_TYPE(KIND, ID) 7888 #define PLACEHOLDER_TYPE(KIND, ID) \ 7889 case BuiltinType::KIND: 7890 #include "clang/AST/BuiltinTypes.def" 7891 llvm_unreachable("invalid builtin type for @encode"); 7892 } 7893 llvm_unreachable("invalid BuiltinType::Kind value"); 7894 } 7895 7896 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) { 7897 EnumDecl *Enum = ET->getDecl(); 7898 7899 // The encoding of an non-fixed enum type is always 'i', regardless of size. 7900 if (!Enum->isFixed()) 7901 return 'i'; 7902 7903 // The encoding of a fixed enum type matches its fixed underlying type. 7904 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>(); 7905 return getObjCEncodingForPrimitiveType(C, BT); 7906 } 7907 7908 static void EncodeBitField(const ASTContext *Ctx, std::string& S, 7909 QualType T, const FieldDecl *FD) { 7910 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl"); 7911 S += 'b'; 7912 // The NeXT runtime encodes bit fields as b followed by the number of bits. 7913 // The GNU runtime requires more information; bitfields are encoded as b, 7914 // then the offset (in bits) of the first element, then the type of the 7915 // bitfield, then the size in bits. For example, in this structure: 7916 // 7917 // struct 7918 // { 7919 // int integer; 7920 // int flags:2; 7921 // }; 7922 // On a 32-bit system, the encoding for flags would be b2 for the NeXT 7923 // runtime, but b32i2 for the GNU runtime. The reason for this extra 7924 // information is not especially sensible, but we're stuck with it for 7925 // compatibility with GCC, although providing it breaks anything that 7926 // actually uses runtime introspection and wants to work on both runtimes... 7927 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) { 7928 uint64_t Offset; 7929 7930 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) { 7931 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr, 7932 IVD); 7933 } else { 7934 const RecordDecl *RD = FD->getParent(); 7935 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD); 7936 Offset = RL.getFieldOffset(FD->getFieldIndex()); 7937 } 7938 7939 S += llvm::utostr(Offset); 7940 7941 if (const auto *ET = T->getAs<EnumType>()) 7942 S += ObjCEncodingForEnumType(Ctx, ET); 7943 else { 7944 const auto *BT = T->castAs<BuiltinType>(); 7945 S += getObjCEncodingForPrimitiveType(Ctx, BT); 7946 } 7947 } 7948 S += llvm::utostr(FD->getBitWidthValue(*Ctx)); 7949 } 7950 7951 // Helper function for determining whether the encoded type string would include 7952 // a template specialization type. 7953 static bool hasTemplateSpecializationInEncodedString(const Type *T, 7954 bool VisitBasesAndFields) { 7955 T = T->getBaseElementTypeUnsafe(); 7956 7957 if (auto *PT = T->getAs<PointerType>()) 7958 return hasTemplateSpecializationInEncodedString( 7959 PT->getPointeeType().getTypePtr(), false); 7960 7961 auto *CXXRD = T->getAsCXXRecordDecl(); 7962 7963 if (!CXXRD) 7964 return false; 7965 7966 if (isa<ClassTemplateSpecializationDecl>(CXXRD)) 7967 return true; 7968 7969 if (!CXXRD->hasDefinition() || !VisitBasesAndFields) 7970 return false; 7971 7972 for (auto B : CXXRD->bases()) 7973 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(), 7974 true)) 7975 return true; 7976 7977 for (auto *FD : CXXRD->fields()) 7978 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(), 7979 true)) 7980 return true; 7981 7982 return false; 7983 } 7984 7985 // FIXME: Use SmallString for accumulating string. 7986 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S, 7987 const ObjCEncOptions Options, 7988 const FieldDecl *FD, 7989 QualType *NotEncodedT) const { 7990 CanQualType CT = getCanonicalType(T); 7991 switch (CT->getTypeClass()) { 7992 case Type::Builtin: 7993 case Type::Enum: 7994 if (FD && FD->isBitField()) 7995 return EncodeBitField(this, S, T, FD); 7996 if (const auto *BT = dyn_cast<BuiltinType>(CT)) 7997 S += getObjCEncodingForPrimitiveType(this, BT); 7998 else 7999 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT)); 8000 return; 8001 8002 case Type::Complex: 8003 S += 'j'; 8004 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S, 8005 ObjCEncOptions(), 8006 /*Field=*/nullptr); 8007 return; 8008 8009 case Type::Atomic: 8010 S += 'A'; 8011 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S, 8012 ObjCEncOptions(), 8013 /*Field=*/nullptr); 8014 return; 8015 8016 // encoding for pointer or reference types. 8017 case Type::Pointer: 8018 case Type::LValueReference: 8019 case Type::RValueReference: { 8020 QualType PointeeTy; 8021 if (isa<PointerType>(CT)) { 8022 const auto *PT = T->castAs<PointerType>(); 8023 if (PT->isObjCSelType()) { 8024 S += ':'; 8025 return; 8026 } 8027 PointeeTy = PT->getPointeeType(); 8028 } else { 8029 PointeeTy = T->castAs<ReferenceType>()->getPointeeType(); 8030 } 8031 8032 bool isReadOnly = false; 8033 // For historical/compatibility reasons, the read-only qualifier of the 8034 // pointee gets emitted _before_ the '^'. The read-only qualifier of 8035 // the pointer itself gets ignored, _unless_ we are looking at a typedef! 8036 // Also, do not emit the 'r' for anything but the outermost type! 8037 if (isa<TypedefType>(T.getTypePtr())) { 8038 if (Options.IsOutermostType() && T.isConstQualified()) { 8039 isReadOnly = true; 8040 S += 'r'; 8041 } 8042 } else if (Options.IsOutermostType()) { 8043 QualType P = PointeeTy; 8044 while (auto PT = P->getAs<PointerType>()) 8045 P = PT->getPointeeType(); 8046 if (P.isConstQualified()) { 8047 isReadOnly = true; 8048 S += 'r'; 8049 } 8050 } 8051 if (isReadOnly) { 8052 // Another legacy compatibility encoding. Some ObjC qualifier and type 8053 // combinations need to be rearranged. 8054 // Rewrite "in const" from "nr" to "rn" 8055 if (StringRef(S).endswith("nr")) 8056 S.replace(S.end()-2, S.end(), "rn"); 8057 } 8058 8059 if (PointeeTy->isCharType()) { 8060 // char pointer types should be encoded as '*' unless it is a 8061 // type that has been typedef'd to 'BOOL'. 8062 if (!isTypeTypedefedAsBOOL(PointeeTy)) { 8063 S += '*'; 8064 return; 8065 } 8066 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) { 8067 // GCC binary compat: Need to convert "struct objc_class *" to "#". 8068 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) { 8069 S += '#'; 8070 return; 8071 } 8072 // GCC binary compat: Need to convert "struct objc_object *" to "@". 8073 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) { 8074 S += '@'; 8075 return; 8076 } 8077 // If the encoded string for the class includes template names, just emit 8078 // "^v" for pointers to the class. 8079 if (getLangOpts().CPlusPlus && 8080 (!getLangOpts().EncodeCXXClassTemplateSpec && 8081 hasTemplateSpecializationInEncodedString( 8082 RTy, Options.ExpandPointedToStructures()))) { 8083 S += "^v"; 8084 return; 8085 } 8086 // fall through... 8087 } 8088 S += '^'; 8089 getLegacyIntegralTypeEncoding(PointeeTy); 8090 8091 ObjCEncOptions NewOptions; 8092 if (Options.ExpandPointedToStructures()) 8093 NewOptions.setExpandStructures(); 8094 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions, 8095 /*Field=*/nullptr, NotEncodedT); 8096 return; 8097 } 8098 8099 case Type::ConstantArray: 8100 case Type::IncompleteArray: 8101 case Type::VariableArray: { 8102 const auto *AT = cast<ArrayType>(CT); 8103 8104 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) { 8105 // Incomplete arrays are encoded as a pointer to the array element. 8106 S += '^'; 8107 8108 getObjCEncodingForTypeImpl( 8109 AT->getElementType(), S, 8110 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD); 8111 } else { 8112 S += '['; 8113 8114 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) 8115 S += llvm::utostr(CAT->getSize().getZExtValue()); 8116 else { 8117 //Variable length arrays are encoded as a regular array with 0 elements. 8118 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) && 8119 "Unknown array type!"); 8120 S += '0'; 8121 } 8122 8123 getObjCEncodingForTypeImpl( 8124 AT->getElementType(), S, 8125 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD, 8126 NotEncodedT); 8127 S += ']'; 8128 } 8129 return; 8130 } 8131 8132 case Type::FunctionNoProto: 8133 case Type::FunctionProto: 8134 S += '?'; 8135 return; 8136 8137 case Type::Record: { 8138 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl(); 8139 S += RDecl->isUnion() ? '(' : '{'; 8140 // Anonymous structures print as '?' 8141 if (const IdentifierInfo *II = RDecl->getIdentifier()) { 8142 S += II->getName(); 8143 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) { 8144 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 8145 llvm::raw_string_ostream OS(S); 8146 printTemplateArgumentList(OS, TemplateArgs.asArray(), 8147 getPrintingPolicy()); 8148 } 8149 } else { 8150 S += '?'; 8151 } 8152 if (Options.ExpandStructures()) { 8153 S += '='; 8154 if (!RDecl->isUnion()) { 8155 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT); 8156 } else { 8157 for (const auto *Field : RDecl->fields()) { 8158 if (FD) { 8159 S += '"'; 8160 S += Field->getNameAsString(); 8161 S += '"'; 8162 } 8163 8164 // Special case bit-fields. 8165 if (Field->isBitField()) { 8166 getObjCEncodingForTypeImpl(Field->getType(), S, 8167 ObjCEncOptions().setExpandStructures(), 8168 Field); 8169 } else { 8170 QualType qt = Field->getType(); 8171 getLegacyIntegralTypeEncoding(qt); 8172 getObjCEncodingForTypeImpl( 8173 qt, S, 8174 ObjCEncOptions().setExpandStructures().setIsStructField(), FD, 8175 NotEncodedT); 8176 } 8177 } 8178 } 8179 } 8180 S += RDecl->isUnion() ? ')' : '}'; 8181 return; 8182 } 8183 8184 case Type::BlockPointer: { 8185 const auto *BT = T->castAs<BlockPointerType>(); 8186 S += "@?"; // Unlike a pointer-to-function, which is "^?". 8187 if (Options.EncodeBlockParameters()) { 8188 const auto *FT = BT->getPointeeType()->castAs<FunctionType>(); 8189 8190 S += '<'; 8191 // Block return type 8192 getObjCEncodingForTypeImpl(FT->getReturnType(), S, 8193 Options.forComponentType(), FD, NotEncodedT); 8194 // Block self 8195 S += "@?"; 8196 // Block parameters 8197 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) { 8198 for (const auto &I : FPT->param_types()) 8199 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD, 8200 NotEncodedT); 8201 } 8202 S += '>'; 8203 } 8204 return; 8205 } 8206 8207 case Type::ObjCObject: { 8208 // hack to match legacy encoding of *id and *Class 8209 QualType Ty = getObjCObjectPointerType(CT); 8210 if (Ty->isObjCIdType()) { 8211 S += "{objc_object=}"; 8212 return; 8213 } 8214 else if (Ty->isObjCClassType()) { 8215 S += "{objc_class=}"; 8216 return; 8217 } 8218 // TODO: Double check to make sure this intentionally falls through. 8219 LLVM_FALLTHROUGH; 8220 } 8221 8222 case Type::ObjCInterface: { 8223 // Ignore protocol qualifiers when mangling at this level. 8224 // @encode(class_name) 8225 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface(); 8226 S += '{'; 8227 S += OI->getObjCRuntimeNameAsString(); 8228 if (Options.ExpandStructures()) { 8229 S += '='; 8230 SmallVector<const ObjCIvarDecl*, 32> Ivars; 8231 DeepCollectObjCIvars(OI, true, Ivars); 8232 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) { 8233 const FieldDecl *Field = Ivars[i]; 8234 if (Field->isBitField()) 8235 getObjCEncodingForTypeImpl(Field->getType(), S, 8236 ObjCEncOptions().setExpandStructures(), 8237 Field); 8238 else 8239 getObjCEncodingForTypeImpl(Field->getType(), S, 8240 ObjCEncOptions().setExpandStructures(), FD, 8241 NotEncodedT); 8242 } 8243 } 8244 S += '}'; 8245 return; 8246 } 8247 8248 case Type::ObjCObjectPointer: { 8249 const auto *OPT = T->castAs<ObjCObjectPointerType>(); 8250 if (OPT->isObjCIdType()) { 8251 S += '@'; 8252 return; 8253 } 8254 8255 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) { 8256 // FIXME: Consider if we need to output qualifiers for 'Class<p>'. 8257 // Since this is a binary compatibility issue, need to consult with 8258 // runtime folks. Fortunately, this is a *very* obscure construct. 8259 S += '#'; 8260 return; 8261 } 8262 8263 if (OPT->isObjCQualifiedIdType()) { 8264 getObjCEncodingForTypeImpl( 8265 getObjCIdType(), S, 8266 Options.keepingOnly(ObjCEncOptions() 8267 .setExpandPointedToStructures() 8268 .setExpandStructures()), 8269 FD); 8270 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) { 8271 // Note that we do extended encoding of protocol qualifier list 8272 // Only when doing ivar or property encoding. 8273 S += '"'; 8274 for (const auto *I : OPT->quals()) { 8275 S += '<'; 8276 S += I->getObjCRuntimeNameAsString(); 8277 S += '>'; 8278 } 8279 S += '"'; 8280 } 8281 return; 8282 } 8283 8284 S += '@'; 8285 if (OPT->getInterfaceDecl() && 8286 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) { 8287 S += '"'; 8288 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString(); 8289 for (const auto *I : OPT->quals()) { 8290 S += '<'; 8291 S += I->getObjCRuntimeNameAsString(); 8292 S += '>'; 8293 } 8294 S += '"'; 8295 } 8296 return; 8297 } 8298 8299 // gcc just blithely ignores member pointers. 8300 // FIXME: we should do better than that. 'M' is available. 8301 case Type::MemberPointer: 8302 // This matches gcc's encoding, even though technically it is insufficient. 8303 //FIXME. We should do a better job than gcc. 8304 case Type::Vector: 8305 case Type::ExtVector: 8306 // Until we have a coherent encoding of these three types, issue warning. 8307 if (NotEncodedT) 8308 *NotEncodedT = T; 8309 return; 8310 8311 case Type::ConstantMatrix: 8312 if (NotEncodedT) 8313 *NotEncodedT = T; 8314 return; 8315 8316 case Type::BitInt: 8317 if (NotEncodedT) 8318 *NotEncodedT = T; 8319 return; 8320 8321 // We could see an undeduced auto type here during error recovery. 8322 // Just ignore it. 8323 case Type::Auto: 8324 case Type::DeducedTemplateSpecialization: 8325 return; 8326 8327 case Type::Pipe: 8328 #define ABSTRACT_TYPE(KIND, BASE) 8329 #define TYPE(KIND, BASE) 8330 #define DEPENDENT_TYPE(KIND, BASE) \ 8331 case Type::KIND: 8332 #define NON_CANONICAL_TYPE(KIND, BASE) \ 8333 case Type::KIND: 8334 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \ 8335 case Type::KIND: 8336 #include "clang/AST/TypeNodes.inc" 8337 llvm_unreachable("@encode for dependent type!"); 8338 } 8339 llvm_unreachable("bad type kind!"); 8340 } 8341 8342 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl, 8343 std::string &S, 8344 const FieldDecl *FD, 8345 bool includeVBases, 8346 QualType *NotEncodedT) const { 8347 assert(RDecl && "Expected non-null RecordDecl"); 8348 assert(!RDecl->isUnion() && "Should not be called for unions"); 8349 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl()) 8350 return; 8351 8352 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl); 8353 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets; 8354 const ASTRecordLayout &layout = getASTRecordLayout(RDecl); 8355 8356 if (CXXRec) { 8357 for (const auto &BI : CXXRec->bases()) { 8358 if (!BI.isVirtual()) { 8359 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); 8360 if (base->isEmpty()) 8361 continue; 8362 uint64_t offs = toBits(layout.getBaseClassOffset(base)); 8363 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 8364 std::make_pair(offs, base)); 8365 } 8366 } 8367 } 8368 8369 unsigned i = 0; 8370 for (FieldDecl *Field : RDecl->fields()) { 8371 if (!Field->isZeroLengthBitField(*this) && Field->isZeroSize(*this)) 8372 continue; 8373 uint64_t offs = layout.getFieldOffset(i); 8374 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 8375 std::make_pair(offs, Field)); 8376 ++i; 8377 } 8378 8379 if (CXXRec && includeVBases) { 8380 for (const auto &BI : CXXRec->vbases()) { 8381 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); 8382 if (base->isEmpty()) 8383 continue; 8384 uint64_t offs = toBits(layout.getVBaseClassOffset(base)); 8385 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) && 8386 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end()) 8387 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(), 8388 std::make_pair(offs, base)); 8389 } 8390 } 8391 8392 CharUnits size; 8393 if (CXXRec) { 8394 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize(); 8395 } else { 8396 size = layout.getSize(); 8397 } 8398 8399 #ifndef NDEBUG 8400 uint64_t CurOffs = 0; 8401 #endif 8402 std::multimap<uint64_t, NamedDecl *>::iterator 8403 CurLayObj = FieldOrBaseOffsets.begin(); 8404 8405 if (CXXRec && CXXRec->isDynamicClass() && 8406 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) { 8407 if (FD) { 8408 S += "\"_vptr$"; 8409 std::string recname = CXXRec->getNameAsString(); 8410 if (recname.empty()) recname = "?"; 8411 S += recname; 8412 S += '"'; 8413 } 8414 S += "^^?"; 8415 #ifndef NDEBUG 8416 CurOffs += getTypeSize(VoidPtrTy); 8417 #endif 8418 } 8419 8420 if (!RDecl->hasFlexibleArrayMember()) { 8421 // Mark the end of the structure. 8422 uint64_t offs = toBits(size); 8423 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 8424 std::make_pair(offs, nullptr)); 8425 } 8426 8427 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) { 8428 #ifndef NDEBUG 8429 assert(CurOffs <= CurLayObj->first); 8430 if (CurOffs < CurLayObj->first) { 8431 uint64_t padding = CurLayObj->first - CurOffs; 8432 // FIXME: There doesn't seem to be a way to indicate in the encoding that 8433 // packing/alignment of members is different that normal, in which case 8434 // the encoding will be out-of-sync with the real layout. 8435 // If the runtime switches to just consider the size of types without 8436 // taking into account alignment, we could make padding explicit in the 8437 // encoding (e.g. using arrays of chars). The encoding strings would be 8438 // longer then though. 8439 CurOffs += padding; 8440 } 8441 #endif 8442 8443 NamedDecl *dcl = CurLayObj->second; 8444 if (!dcl) 8445 break; // reached end of structure. 8446 8447 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) { 8448 // We expand the bases without their virtual bases since those are going 8449 // in the initial structure. Note that this differs from gcc which 8450 // expands virtual bases each time one is encountered in the hierarchy, 8451 // making the encoding type bigger than it really is. 8452 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false, 8453 NotEncodedT); 8454 assert(!base->isEmpty()); 8455 #ifndef NDEBUG 8456 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize()); 8457 #endif 8458 } else { 8459 const auto *field = cast<FieldDecl>(dcl); 8460 if (FD) { 8461 S += '"'; 8462 S += field->getNameAsString(); 8463 S += '"'; 8464 } 8465 8466 if (field->isBitField()) { 8467 EncodeBitField(this, S, field->getType(), field); 8468 #ifndef NDEBUG 8469 CurOffs += field->getBitWidthValue(*this); 8470 #endif 8471 } else { 8472 QualType qt = field->getType(); 8473 getLegacyIntegralTypeEncoding(qt); 8474 getObjCEncodingForTypeImpl( 8475 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(), 8476 FD, NotEncodedT); 8477 #ifndef NDEBUG 8478 CurOffs += getTypeSize(field->getType()); 8479 #endif 8480 } 8481 } 8482 } 8483 } 8484 8485 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, 8486 std::string& S) const { 8487 if (QT & Decl::OBJC_TQ_In) 8488 S += 'n'; 8489 if (QT & Decl::OBJC_TQ_Inout) 8490 S += 'N'; 8491 if (QT & Decl::OBJC_TQ_Out) 8492 S += 'o'; 8493 if (QT & Decl::OBJC_TQ_Bycopy) 8494 S += 'O'; 8495 if (QT & Decl::OBJC_TQ_Byref) 8496 S += 'R'; 8497 if (QT & Decl::OBJC_TQ_Oneway) 8498 S += 'V'; 8499 } 8500 8501 TypedefDecl *ASTContext::getObjCIdDecl() const { 8502 if (!ObjCIdDecl) { 8503 QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {}); 8504 T = getObjCObjectPointerType(T); 8505 ObjCIdDecl = buildImplicitTypedef(T, "id"); 8506 } 8507 return ObjCIdDecl; 8508 } 8509 8510 TypedefDecl *ASTContext::getObjCSelDecl() const { 8511 if (!ObjCSelDecl) { 8512 QualType T = getPointerType(ObjCBuiltinSelTy); 8513 ObjCSelDecl = buildImplicitTypedef(T, "SEL"); 8514 } 8515 return ObjCSelDecl; 8516 } 8517 8518 TypedefDecl *ASTContext::getObjCClassDecl() const { 8519 if (!ObjCClassDecl) { 8520 QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {}); 8521 T = getObjCObjectPointerType(T); 8522 ObjCClassDecl = buildImplicitTypedef(T, "Class"); 8523 } 8524 return ObjCClassDecl; 8525 } 8526 8527 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const { 8528 if (!ObjCProtocolClassDecl) { 8529 ObjCProtocolClassDecl 8530 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(), 8531 SourceLocation(), 8532 &Idents.get("Protocol"), 8533 /*typeParamList=*/nullptr, 8534 /*PrevDecl=*/nullptr, 8535 SourceLocation(), true); 8536 } 8537 8538 return ObjCProtocolClassDecl; 8539 } 8540 8541 //===----------------------------------------------------------------------===// 8542 // __builtin_va_list Construction Functions 8543 //===----------------------------------------------------------------------===// 8544 8545 static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context, 8546 StringRef Name) { 8547 // typedef char* __builtin[_ms]_va_list; 8548 QualType T = Context->getPointerType(Context->CharTy); 8549 return Context->buildImplicitTypedef(T, Name); 8550 } 8551 8552 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) { 8553 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list"); 8554 } 8555 8556 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) { 8557 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list"); 8558 } 8559 8560 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) { 8561 // typedef void* __builtin_va_list; 8562 QualType T = Context->getPointerType(Context->VoidTy); 8563 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 8564 } 8565 8566 static TypedefDecl * 8567 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) { 8568 // struct __va_list 8569 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list"); 8570 if (Context->getLangOpts().CPlusPlus) { 8571 // namespace std { struct __va_list { 8572 auto *NS = NamespaceDecl::Create( 8573 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(), 8574 /*Inline*/ false, SourceLocation(), SourceLocation(), 8575 &Context->Idents.get("std"), 8576 /*PrevDecl*/ nullptr); 8577 NS->setImplicit(); 8578 VaListTagDecl->setDeclContext(NS); 8579 } 8580 8581 VaListTagDecl->startDefinition(); 8582 8583 const size_t NumFields = 5; 8584 QualType FieldTypes[NumFields]; 8585 const char *FieldNames[NumFields]; 8586 8587 // void *__stack; 8588 FieldTypes[0] = Context->getPointerType(Context->VoidTy); 8589 FieldNames[0] = "__stack"; 8590 8591 // void *__gr_top; 8592 FieldTypes[1] = Context->getPointerType(Context->VoidTy); 8593 FieldNames[1] = "__gr_top"; 8594 8595 // void *__vr_top; 8596 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8597 FieldNames[2] = "__vr_top"; 8598 8599 // int __gr_offs; 8600 FieldTypes[3] = Context->IntTy; 8601 FieldNames[3] = "__gr_offs"; 8602 8603 // int __vr_offs; 8604 FieldTypes[4] = Context->IntTy; 8605 FieldNames[4] = "__vr_offs"; 8606 8607 // Create fields 8608 for (unsigned i = 0; i < NumFields; ++i) { 8609 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8610 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 // } __builtin_va_list; 8626 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list"); 8627 } 8628 8629 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) { 8630 // typedef struct __va_list_tag { 8631 RecordDecl *VaListTagDecl; 8632 8633 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8634 VaListTagDecl->startDefinition(); 8635 8636 const size_t NumFields = 5; 8637 QualType FieldTypes[NumFields]; 8638 const char *FieldNames[NumFields]; 8639 8640 // unsigned char gpr; 8641 FieldTypes[0] = Context->UnsignedCharTy; 8642 FieldNames[0] = "gpr"; 8643 8644 // unsigned char fpr; 8645 FieldTypes[1] = Context->UnsignedCharTy; 8646 FieldNames[1] = "fpr"; 8647 8648 // unsigned short reserved; 8649 FieldTypes[2] = Context->UnsignedShortTy; 8650 FieldNames[2] = "reserved"; 8651 8652 // void* overflow_arg_area; 8653 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 8654 FieldNames[3] = "overflow_arg_area"; 8655 8656 // void* reg_save_area; 8657 FieldTypes[4] = Context->getPointerType(Context->VoidTy); 8658 FieldNames[4] = "reg_save_area"; 8659 8660 // Create fields 8661 for (unsigned i = 0; i < NumFields; ++i) { 8662 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl, 8663 SourceLocation(), 8664 SourceLocation(), 8665 &Context->Idents.get(FieldNames[i]), 8666 FieldTypes[i], /*TInfo=*/nullptr, 8667 /*BitWidth=*/nullptr, 8668 /*Mutable=*/false, 8669 ICIS_NoInit); 8670 Field->setAccess(AS_public); 8671 VaListTagDecl->addDecl(Field); 8672 } 8673 VaListTagDecl->completeDefinition(); 8674 Context->VaListTagDecl = VaListTagDecl; 8675 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8676 8677 // } __va_list_tag; 8678 TypedefDecl *VaListTagTypedefDecl = 8679 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); 8680 8681 QualType VaListTagTypedefType = 8682 Context->getTypedefType(VaListTagTypedefDecl); 8683 8684 // typedef __va_list_tag __builtin_va_list[1]; 8685 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8686 QualType VaListTagArrayType 8687 = Context->getConstantArrayType(VaListTagTypedefType, 8688 Size, nullptr, ArrayType::Normal, 0); 8689 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8690 } 8691 8692 static TypedefDecl * 8693 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) { 8694 // struct __va_list_tag { 8695 RecordDecl *VaListTagDecl; 8696 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8697 VaListTagDecl->startDefinition(); 8698 8699 const size_t NumFields = 4; 8700 QualType FieldTypes[NumFields]; 8701 const char *FieldNames[NumFields]; 8702 8703 // unsigned gp_offset; 8704 FieldTypes[0] = Context->UnsignedIntTy; 8705 FieldNames[0] = "gp_offset"; 8706 8707 // unsigned fp_offset; 8708 FieldTypes[1] = Context->UnsignedIntTy; 8709 FieldNames[1] = "fp_offset"; 8710 8711 // void* overflow_arg_area; 8712 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8713 FieldNames[2] = "overflow_arg_area"; 8714 8715 // void* reg_save_area; 8716 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 8717 FieldNames[3] = "reg_save_area"; 8718 8719 // Create fields 8720 for (unsigned i = 0; i < NumFields; ++i) { 8721 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8722 VaListTagDecl, 8723 SourceLocation(), 8724 SourceLocation(), 8725 &Context->Idents.get(FieldNames[i]), 8726 FieldTypes[i], /*TInfo=*/nullptr, 8727 /*BitWidth=*/nullptr, 8728 /*Mutable=*/false, 8729 ICIS_NoInit); 8730 Field->setAccess(AS_public); 8731 VaListTagDecl->addDecl(Field); 8732 } 8733 VaListTagDecl->completeDefinition(); 8734 Context->VaListTagDecl = VaListTagDecl; 8735 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8736 8737 // }; 8738 8739 // typedef struct __va_list_tag __builtin_va_list[1]; 8740 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8741 QualType VaListTagArrayType = Context->getConstantArrayType( 8742 VaListTagType, Size, nullptr, ArrayType::Normal, 0); 8743 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8744 } 8745 8746 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) { 8747 // typedef int __builtin_va_list[4]; 8748 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4); 8749 QualType IntArrayType = Context->getConstantArrayType( 8750 Context->IntTy, Size, nullptr, ArrayType::Normal, 0); 8751 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list"); 8752 } 8753 8754 static TypedefDecl * 8755 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) { 8756 // struct __va_list 8757 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list"); 8758 if (Context->getLangOpts().CPlusPlus) { 8759 // namespace std { struct __va_list { 8760 NamespaceDecl *NS; 8761 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context), 8762 Context->getTranslationUnitDecl(), 8763 /*Inline*/false, SourceLocation(), 8764 SourceLocation(), &Context->Idents.get("std"), 8765 /*PrevDecl*/ nullptr); 8766 NS->setImplicit(); 8767 VaListDecl->setDeclContext(NS); 8768 } 8769 8770 VaListDecl->startDefinition(); 8771 8772 // void * __ap; 8773 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8774 VaListDecl, 8775 SourceLocation(), 8776 SourceLocation(), 8777 &Context->Idents.get("__ap"), 8778 Context->getPointerType(Context->VoidTy), 8779 /*TInfo=*/nullptr, 8780 /*BitWidth=*/nullptr, 8781 /*Mutable=*/false, 8782 ICIS_NoInit); 8783 Field->setAccess(AS_public); 8784 VaListDecl->addDecl(Field); 8785 8786 // }; 8787 VaListDecl->completeDefinition(); 8788 Context->VaListTagDecl = VaListDecl; 8789 8790 // typedef struct __va_list __builtin_va_list; 8791 QualType T = Context->getRecordType(VaListDecl); 8792 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 8793 } 8794 8795 static TypedefDecl * 8796 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) { 8797 // struct __va_list_tag { 8798 RecordDecl *VaListTagDecl; 8799 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8800 VaListTagDecl->startDefinition(); 8801 8802 const size_t NumFields = 4; 8803 QualType FieldTypes[NumFields]; 8804 const char *FieldNames[NumFields]; 8805 8806 // long __gpr; 8807 FieldTypes[0] = Context->LongTy; 8808 FieldNames[0] = "__gpr"; 8809 8810 // long __fpr; 8811 FieldTypes[1] = Context->LongTy; 8812 FieldNames[1] = "__fpr"; 8813 8814 // void *__overflow_arg_area; 8815 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8816 FieldNames[2] = "__overflow_arg_area"; 8817 8818 // void *__reg_save_area; 8819 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 8820 FieldNames[3] = "__reg_save_area"; 8821 8822 // Create fields 8823 for (unsigned i = 0; i < NumFields; ++i) { 8824 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8825 VaListTagDecl, 8826 SourceLocation(), 8827 SourceLocation(), 8828 &Context->Idents.get(FieldNames[i]), 8829 FieldTypes[i], /*TInfo=*/nullptr, 8830 /*BitWidth=*/nullptr, 8831 /*Mutable=*/false, 8832 ICIS_NoInit); 8833 Field->setAccess(AS_public); 8834 VaListTagDecl->addDecl(Field); 8835 } 8836 VaListTagDecl->completeDefinition(); 8837 Context->VaListTagDecl = VaListTagDecl; 8838 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8839 8840 // }; 8841 8842 // typedef __va_list_tag __builtin_va_list[1]; 8843 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8844 QualType VaListTagArrayType = Context->getConstantArrayType( 8845 VaListTagType, Size, nullptr, ArrayType::Normal, 0); 8846 8847 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8848 } 8849 8850 static TypedefDecl *CreateHexagonBuiltinVaListDecl(const ASTContext *Context) { 8851 // typedef struct __va_list_tag { 8852 RecordDecl *VaListTagDecl; 8853 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8854 VaListTagDecl->startDefinition(); 8855 8856 const size_t NumFields = 3; 8857 QualType FieldTypes[NumFields]; 8858 const char *FieldNames[NumFields]; 8859 8860 // void *CurrentSavedRegisterArea; 8861 FieldTypes[0] = Context->getPointerType(Context->VoidTy); 8862 FieldNames[0] = "__current_saved_reg_area_pointer"; 8863 8864 // void *SavedRegAreaEnd; 8865 FieldTypes[1] = Context->getPointerType(Context->VoidTy); 8866 FieldNames[1] = "__saved_reg_area_end_pointer"; 8867 8868 // void *OverflowArea; 8869 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8870 FieldNames[2] = "__overflow_area_pointer"; 8871 8872 // Create fields 8873 for (unsigned i = 0; i < NumFields; ++i) { 8874 FieldDecl *Field = FieldDecl::Create( 8875 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(), 8876 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i], 8877 /*TInfo=*/nullptr, 8878 /*BitWidth=*/nullptr, 8879 /*Mutable=*/false, ICIS_NoInit); 8880 Field->setAccess(AS_public); 8881 VaListTagDecl->addDecl(Field); 8882 } 8883 VaListTagDecl->completeDefinition(); 8884 Context->VaListTagDecl = VaListTagDecl; 8885 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8886 8887 // } __va_list_tag; 8888 TypedefDecl *VaListTagTypedefDecl = 8889 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); 8890 8891 QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl); 8892 8893 // typedef __va_list_tag __builtin_va_list[1]; 8894 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8895 QualType VaListTagArrayType = Context->getConstantArrayType( 8896 VaListTagTypedefType, Size, nullptr, ArrayType::Normal, 0); 8897 8898 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8899 } 8900 8901 static TypedefDecl *CreateVaListDecl(const ASTContext *Context, 8902 TargetInfo::BuiltinVaListKind Kind) { 8903 switch (Kind) { 8904 case TargetInfo::CharPtrBuiltinVaList: 8905 return CreateCharPtrBuiltinVaListDecl(Context); 8906 case TargetInfo::VoidPtrBuiltinVaList: 8907 return CreateVoidPtrBuiltinVaListDecl(Context); 8908 case TargetInfo::AArch64ABIBuiltinVaList: 8909 return CreateAArch64ABIBuiltinVaListDecl(Context); 8910 case TargetInfo::PowerABIBuiltinVaList: 8911 return CreatePowerABIBuiltinVaListDecl(Context); 8912 case TargetInfo::X86_64ABIBuiltinVaList: 8913 return CreateX86_64ABIBuiltinVaListDecl(Context); 8914 case TargetInfo::PNaClABIBuiltinVaList: 8915 return CreatePNaClABIBuiltinVaListDecl(Context); 8916 case TargetInfo::AAPCSABIBuiltinVaList: 8917 return CreateAAPCSABIBuiltinVaListDecl(Context); 8918 case TargetInfo::SystemZBuiltinVaList: 8919 return CreateSystemZBuiltinVaListDecl(Context); 8920 case TargetInfo::HexagonBuiltinVaList: 8921 return CreateHexagonBuiltinVaListDecl(Context); 8922 } 8923 8924 llvm_unreachable("Unhandled __builtin_va_list type kind"); 8925 } 8926 8927 TypedefDecl *ASTContext::getBuiltinVaListDecl() const { 8928 if (!BuiltinVaListDecl) { 8929 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind()); 8930 assert(BuiltinVaListDecl->isImplicit()); 8931 } 8932 8933 return BuiltinVaListDecl; 8934 } 8935 8936 Decl *ASTContext::getVaListTagDecl() const { 8937 // Force the creation of VaListTagDecl by building the __builtin_va_list 8938 // declaration. 8939 if (!VaListTagDecl) 8940 (void)getBuiltinVaListDecl(); 8941 8942 return VaListTagDecl; 8943 } 8944 8945 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const { 8946 if (!BuiltinMSVaListDecl) 8947 BuiltinMSVaListDecl = CreateMSVaListDecl(this); 8948 8949 return BuiltinMSVaListDecl; 8950 } 8951 8952 bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const { 8953 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID()); 8954 } 8955 8956 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) { 8957 assert(ObjCConstantStringType.isNull() && 8958 "'NSConstantString' type already set!"); 8959 8960 ObjCConstantStringType = getObjCInterfaceType(Decl); 8961 } 8962 8963 /// Retrieve the template name that corresponds to a non-empty 8964 /// lookup. 8965 TemplateName 8966 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin, 8967 UnresolvedSetIterator End) const { 8968 unsigned size = End - Begin; 8969 assert(size > 1 && "set is not overloaded!"); 8970 8971 void *memory = Allocate(sizeof(OverloadedTemplateStorage) + 8972 size * sizeof(FunctionTemplateDecl*)); 8973 auto *OT = new (memory) OverloadedTemplateStorage(size); 8974 8975 NamedDecl **Storage = OT->getStorage(); 8976 for (UnresolvedSetIterator I = Begin; I != End; ++I) { 8977 NamedDecl *D = *I; 8978 assert(isa<FunctionTemplateDecl>(D) || 8979 isa<UnresolvedUsingValueDecl>(D) || 8980 (isa<UsingShadowDecl>(D) && 8981 isa<FunctionTemplateDecl>(D->getUnderlyingDecl()))); 8982 *Storage++ = D; 8983 } 8984 8985 return TemplateName(OT); 8986 } 8987 8988 /// Retrieve a template name representing an unqualified-id that has been 8989 /// assumed to name a template for ADL purposes. 8990 TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const { 8991 auto *OT = new (*this) AssumedTemplateStorage(Name); 8992 return TemplateName(OT); 8993 } 8994 8995 /// Retrieve the template name that represents a qualified 8996 /// template name such as \c std::vector. 8997 TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, 8998 bool TemplateKeyword, 8999 TemplateName Template) const { 9000 assert(NNS && "Missing nested-name-specifier in qualified template name"); 9001 9002 // FIXME: Canonicalization? 9003 llvm::FoldingSetNodeID ID; 9004 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template); 9005 9006 void *InsertPos = nullptr; 9007 QualifiedTemplateName *QTN = 9008 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 9009 if (!QTN) { 9010 QTN = new (*this, alignof(QualifiedTemplateName)) 9011 QualifiedTemplateName(NNS, TemplateKeyword, Template); 9012 QualifiedTemplateNames.InsertNode(QTN, InsertPos); 9013 } 9014 9015 return TemplateName(QTN); 9016 } 9017 9018 /// Retrieve the template name that represents a dependent 9019 /// template name such as \c MetaFun::template apply. 9020 TemplateName 9021 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 9022 const IdentifierInfo *Name) const { 9023 assert((!NNS || NNS->isDependent()) && 9024 "Nested name specifier must be dependent"); 9025 9026 llvm::FoldingSetNodeID ID; 9027 DependentTemplateName::Profile(ID, NNS, Name); 9028 9029 void *InsertPos = nullptr; 9030 DependentTemplateName *QTN = 9031 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 9032 9033 if (QTN) 9034 return TemplateName(QTN); 9035 9036 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 9037 if (CanonNNS == NNS) { 9038 QTN = new (*this, alignof(DependentTemplateName)) 9039 DependentTemplateName(NNS, Name); 9040 } else { 9041 TemplateName Canon = getDependentTemplateName(CanonNNS, Name); 9042 QTN = new (*this, alignof(DependentTemplateName)) 9043 DependentTemplateName(NNS, Name, Canon); 9044 DependentTemplateName *CheckQTN = 9045 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 9046 assert(!CheckQTN && "Dependent type name canonicalization broken"); 9047 (void)CheckQTN; 9048 } 9049 9050 DependentTemplateNames.InsertNode(QTN, InsertPos); 9051 return TemplateName(QTN); 9052 } 9053 9054 /// Retrieve the template name that represents a dependent 9055 /// template name such as \c MetaFun::template operator+. 9056 TemplateName 9057 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 9058 OverloadedOperatorKind Operator) const { 9059 assert((!NNS || NNS->isDependent()) && 9060 "Nested name specifier must be dependent"); 9061 9062 llvm::FoldingSetNodeID ID; 9063 DependentTemplateName::Profile(ID, NNS, Operator); 9064 9065 void *InsertPos = nullptr; 9066 DependentTemplateName *QTN 9067 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 9068 9069 if (QTN) 9070 return TemplateName(QTN); 9071 9072 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 9073 if (CanonNNS == NNS) { 9074 QTN = new (*this, alignof(DependentTemplateName)) 9075 DependentTemplateName(NNS, Operator); 9076 } else { 9077 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator); 9078 QTN = new (*this, alignof(DependentTemplateName)) 9079 DependentTemplateName(NNS, Operator, Canon); 9080 9081 DependentTemplateName *CheckQTN 9082 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 9083 assert(!CheckQTN && "Dependent template name canonicalization broken"); 9084 (void)CheckQTN; 9085 } 9086 9087 DependentTemplateNames.InsertNode(QTN, InsertPos); 9088 return TemplateName(QTN); 9089 } 9090 9091 TemplateName 9092 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param, 9093 TemplateName replacement) const { 9094 llvm::FoldingSetNodeID ID; 9095 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement); 9096 9097 void *insertPos = nullptr; 9098 SubstTemplateTemplateParmStorage *subst 9099 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos); 9100 9101 if (!subst) { 9102 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement); 9103 SubstTemplateTemplateParms.InsertNode(subst, insertPos); 9104 } 9105 9106 return TemplateName(subst); 9107 } 9108 9109 TemplateName 9110 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param, 9111 const TemplateArgument &ArgPack) const { 9112 auto &Self = const_cast<ASTContext &>(*this); 9113 llvm::FoldingSetNodeID ID; 9114 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack); 9115 9116 void *InsertPos = nullptr; 9117 SubstTemplateTemplateParmPackStorage *Subst 9118 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos); 9119 9120 if (!Subst) { 9121 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param, 9122 ArgPack.pack_size(), 9123 ArgPack.pack_begin()); 9124 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos); 9125 } 9126 9127 return TemplateName(Subst); 9128 } 9129 9130 /// getFromTargetType - Given one of the integer types provided by 9131 /// TargetInfo, produce the corresponding type. The unsigned @p Type 9132 /// is actually a value of type @c TargetInfo::IntType. 9133 CanQualType ASTContext::getFromTargetType(unsigned Type) const { 9134 switch (Type) { 9135 case TargetInfo::NoInt: return {}; 9136 case TargetInfo::SignedChar: return SignedCharTy; 9137 case TargetInfo::UnsignedChar: return UnsignedCharTy; 9138 case TargetInfo::SignedShort: return ShortTy; 9139 case TargetInfo::UnsignedShort: return UnsignedShortTy; 9140 case TargetInfo::SignedInt: return IntTy; 9141 case TargetInfo::UnsignedInt: return UnsignedIntTy; 9142 case TargetInfo::SignedLong: return LongTy; 9143 case TargetInfo::UnsignedLong: return UnsignedLongTy; 9144 case TargetInfo::SignedLongLong: return LongLongTy; 9145 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy; 9146 } 9147 9148 llvm_unreachable("Unhandled TargetInfo::IntType value"); 9149 } 9150 9151 //===----------------------------------------------------------------------===// 9152 // Type Predicates. 9153 //===----------------------------------------------------------------------===// 9154 9155 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's 9156 /// garbage collection attribute. 9157 /// 9158 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const { 9159 if (getLangOpts().getGC() == LangOptions::NonGC) 9160 return Qualifiers::GCNone; 9161 9162 assert(getLangOpts().ObjC); 9163 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr(); 9164 9165 // Default behaviour under objective-C's gc is for ObjC pointers 9166 // (or pointers to them) be treated as though they were declared 9167 // as __strong. 9168 if (GCAttrs == Qualifiers::GCNone) { 9169 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) 9170 return Qualifiers::Strong; 9171 else if (Ty->isPointerType()) 9172 return getObjCGCAttrKind(Ty->castAs<PointerType>()->getPointeeType()); 9173 } else { 9174 // It's not valid to set GC attributes on anything that isn't a 9175 // pointer. 9176 #ifndef NDEBUG 9177 QualType CT = Ty->getCanonicalTypeInternal(); 9178 while (const auto *AT = dyn_cast<ArrayType>(CT)) 9179 CT = AT->getElementType(); 9180 assert(CT->isAnyPointerType() || CT->isBlockPointerType()); 9181 #endif 9182 } 9183 return GCAttrs; 9184 } 9185 9186 //===----------------------------------------------------------------------===// 9187 // Type Compatibility Testing 9188 //===----------------------------------------------------------------------===// 9189 9190 /// areCompatVectorTypes - Return true if the two specified vector types are 9191 /// compatible. 9192 static bool areCompatVectorTypes(const VectorType *LHS, 9193 const VectorType *RHS) { 9194 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 9195 return LHS->getElementType() == RHS->getElementType() && 9196 LHS->getNumElements() == RHS->getNumElements(); 9197 } 9198 9199 /// areCompatMatrixTypes - Return true if the two specified matrix types are 9200 /// compatible. 9201 static bool areCompatMatrixTypes(const ConstantMatrixType *LHS, 9202 const ConstantMatrixType *RHS) { 9203 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 9204 return LHS->getElementType() == RHS->getElementType() && 9205 LHS->getNumRows() == RHS->getNumRows() && 9206 LHS->getNumColumns() == RHS->getNumColumns(); 9207 } 9208 9209 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec, 9210 QualType SecondVec) { 9211 assert(FirstVec->isVectorType() && "FirstVec should be a vector type"); 9212 assert(SecondVec->isVectorType() && "SecondVec should be a vector type"); 9213 9214 if (hasSameUnqualifiedType(FirstVec, SecondVec)) 9215 return true; 9216 9217 // Treat Neon vector types and most AltiVec vector types as if they are the 9218 // equivalent GCC vector types. 9219 const auto *First = FirstVec->castAs<VectorType>(); 9220 const auto *Second = SecondVec->castAs<VectorType>(); 9221 if (First->getNumElements() == Second->getNumElements() && 9222 hasSameType(First->getElementType(), Second->getElementType()) && 9223 First->getVectorKind() != VectorType::AltiVecPixel && 9224 First->getVectorKind() != VectorType::AltiVecBool && 9225 Second->getVectorKind() != VectorType::AltiVecPixel && 9226 Second->getVectorKind() != VectorType::AltiVecBool && 9227 First->getVectorKind() != VectorType::SveFixedLengthDataVector && 9228 First->getVectorKind() != VectorType::SveFixedLengthPredicateVector && 9229 Second->getVectorKind() != VectorType::SveFixedLengthDataVector && 9230 Second->getVectorKind() != VectorType::SveFixedLengthPredicateVector) 9231 return true; 9232 9233 return false; 9234 } 9235 9236 /// getSVETypeSize - Return SVE vector or predicate register size. 9237 static uint64_t getSVETypeSize(ASTContext &Context, const BuiltinType *Ty) { 9238 assert(Ty->isVLSTBuiltinType() && "Invalid SVE Type"); 9239 return Ty->getKind() == BuiltinType::SveBool 9240 ? (Context.getLangOpts().VScaleMin * 128) / Context.getCharWidth() 9241 : Context.getLangOpts().VScaleMin * 128; 9242 } 9243 9244 bool ASTContext::areCompatibleSveTypes(QualType FirstType, 9245 QualType SecondType) { 9246 assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) || 9247 (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) && 9248 "Expected SVE builtin type and vector type!"); 9249 9250 auto IsValidCast = [this](QualType FirstType, QualType SecondType) { 9251 if (const auto *BT = FirstType->getAs<BuiltinType>()) { 9252 if (const auto *VT = SecondType->getAs<VectorType>()) { 9253 // Predicates have the same representation as uint8 so we also have to 9254 // check the kind to make these types incompatible. 9255 if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 9256 return BT->getKind() == BuiltinType::SveBool; 9257 else if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) 9258 return VT->getElementType().getCanonicalType() == 9259 FirstType->getSveEltType(*this); 9260 else if (VT->getVectorKind() == VectorType::GenericVector) 9261 return getTypeSize(SecondType) == getSVETypeSize(*this, BT) && 9262 hasSameType(VT->getElementType(), 9263 getBuiltinVectorTypeInfo(BT).ElementType); 9264 } 9265 } 9266 return false; 9267 }; 9268 9269 return IsValidCast(FirstType, SecondType) || 9270 IsValidCast(SecondType, FirstType); 9271 } 9272 9273 bool ASTContext::areLaxCompatibleSveTypes(QualType FirstType, 9274 QualType SecondType) { 9275 assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) || 9276 (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) && 9277 "Expected SVE builtin type and vector type!"); 9278 9279 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) { 9280 const auto *BT = FirstType->getAs<BuiltinType>(); 9281 if (!BT) 9282 return false; 9283 9284 const auto *VecTy = SecondType->getAs<VectorType>(); 9285 if (VecTy && 9286 (VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector || 9287 VecTy->getVectorKind() == VectorType::GenericVector)) { 9288 const LangOptions::LaxVectorConversionKind LVCKind = 9289 getLangOpts().getLaxVectorConversions(); 9290 9291 // Can not convert between sve predicates and sve vectors because of 9292 // different size. 9293 if (BT->getKind() == BuiltinType::SveBool && 9294 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector) 9295 return false; 9296 9297 // If __ARM_FEATURE_SVE_BITS != N do not allow GNU vector lax conversion. 9298 // "Whenever __ARM_FEATURE_SVE_BITS==N, GNUT implicitly 9299 // converts to VLAT and VLAT implicitly converts to GNUT." 9300 // ACLE Spec Version 00bet6, 3.7.3.2. Behavior common to vectors and 9301 // predicates. 9302 if (VecTy->getVectorKind() == VectorType::GenericVector && 9303 getTypeSize(SecondType) != getSVETypeSize(*this, BT)) 9304 return false; 9305 9306 // If -flax-vector-conversions=all is specified, the types are 9307 // certainly compatible. 9308 if (LVCKind == LangOptions::LaxVectorConversionKind::All) 9309 return true; 9310 9311 // If -flax-vector-conversions=integer is specified, the types are 9312 // compatible if the elements are integer types. 9313 if (LVCKind == LangOptions::LaxVectorConversionKind::Integer) 9314 return VecTy->getElementType().getCanonicalType()->isIntegerType() && 9315 FirstType->getSveEltType(*this)->isIntegerType(); 9316 } 9317 9318 return false; 9319 }; 9320 9321 return IsLaxCompatible(FirstType, SecondType) || 9322 IsLaxCompatible(SecondType, FirstType); 9323 } 9324 9325 bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const { 9326 while (true) { 9327 // __strong id 9328 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) { 9329 if (Attr->getAttrKind() == attr::ObjCOwnership) 9330 return true; 9331 9332 Ty = Attr->getModifiedType(); 9333 9334 // X *__strong (...) 9335 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) { 9336 Ty = Paren->getInnerType(); 9337 9338 // We do not want to look through typedefs, typeof(expr), 9339 // typeof(type), or any other way that the type is somehow 9340 // abstracted. 9341 } else { 9342 return false; 9343 } 9344 } 9345 } 9346 9347 //===----------------------------------------------------------------------===// 9348 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's. 9349 //===----------------------------------------------------------------------===// 9350 9351 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the 9352 /// inheritance hierarchy of 'rProto'. 9353 bool 9354 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, 9355 ObjCProtocolDecl *rProto) const { 9356 if (declaresSameEntity(lProto, rProto)) 9357 return true; 9358 for (auto *PI : rProto->protocols()) 9359 if (ProtocolCompatibleWithProtocol(lProto, PI)) 9360 return true; 9361 return false; 9362 } 9363 9364 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and 9365 /// Class<pr1, ...>. 9366 bool ASTContext::ObjCQualifiedClassTypesAreCompatible( 9367 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) { 9368 for (auto *lhsProto : lhs->quals()) { 9369 bool match = false; 9370 for (auto *rhsProto : rhs->quals()) { 9371 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) { 9372 match = true; 9373 break; 9374 } 9375 } 9376 if (!match) 9377 return false; 9378 } 9379 return true; 9380 } 9381 9382 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an 9383 /// ObjCQualifiedIDType. 9384 bool ASTContext::ObjCQualifiedIdTypesAreCompatible( 9385 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs, 9386 bool compare) { 9387 // Allow id<P..> and an 'id' in all cases. 9388 if (lhs->isObjCIdType() || rhs->isObjCIdType()) 9389 return true; 9390 9391 // Don't allow id<P..> to convert to Class or Class<P..> in either direction. 9392 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() || 9393 rhs->isObjCClassType() || rhs->isObjCQualifiedClassType()) 9394 return false; 9395 9396 if (lhs->isObjCQualifiedIdType()) { 9397 if (rhs->qual_empty()) { 9398 // If the RHS is a unqualified interface pointer "NSString*", 9399 // make sure we check the class hierarchy. 9400 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) { 9401 for (auto *I : lhs->quals()) { 9402 // when comparing an id<P> on lhs with a static type on rhs, 9403 // see if static class implements all of id's protocols, directly or 9404 // through its super class and categories. 9405 if (!rhsID->ClassImplementsProtocol(I, true)) 9406 return false; 9407 } 9408 } 9409 // If there are no qualifiers and no interface, we have an 'id'. 9410 return true; 9411 } 9412 // Both the right and left sides have qualifiers. 9413 for (auto *lhsProto : lhs->quals()) { 9414 bool match = false; 9415 9416 // when comparing an id<P> on lhs with a static type on rhs, 9417 // see if static class implements all of id's protocols, directly or 9418 // through its super class and categories. 9419 for (auto *rhsProto : rhs->quals()) { 9420 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 9421 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 9422 match = true; 9423 break; 9424 } 9425 } 9426 // If the RHS is a qualified interface pointer "NSString<P>*", 9427 // make sure we check the class hierarchy. 9428 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) { 9429 for (auto *I : lhs->quals()) { 9430 // when comparing an id<P> on lhs with a static type on rhs, 9431 // see if static class implements all of id's protocols, directly or 9432 // through its super class and categories. 9433 if (rhsID->ClassImplementsProtocol(I, true)) { 9434 match = true; 9435 break; 9436 } 9437 } 9438 } 9439 if (!match) 9440 return false; 9441 } 9442 9443 return true; 9444 } 9445 9446 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>"); 9447 9448 if (lhs->getInterfaceType()) { 9449 // If both the right and left sides have qualifiers. 9450 for (auto *lhsProto : lhs->quals()) { 9451 bool match = false; 9452 9453 // when comparing an id<P> on rhs with a static type on lhs, 9454 // see if static class implements all of id's protocols, directly or 9455 // through its super class and categories. 9456 // First, lhs protocols in the qualifier list must be found, direct 9457 // or indirect in rhs's qualifier list or it is a mismatch. 9458 for (auto *rhsProto : rhs->quals()) { 9459 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 9460 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 9461 match = true; 9462 break; 9463 } 9464 } 9465 if (!match) 9466 return false; 9467 } 9468 9469 // Static class's protocols, or its super class or category protocols 9470 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch. 9471 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) { 9472 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols; 9473 CollectInheritedProtocols(lhsID, LHSInheritedProtocols); 9474 // This is rather dubious but matches gcc's behavior. If lhs has 9475 // no type qualifier and its class has no static protocol(s) 9476 // assume that it is mismatch. 9477 if (LHSInheritedProtocols.empty() && lhs->qual_empty()) 9478 return false; 9479 for (auto *lhsProto : LHSInheritedProtocols) { 9480 bool match = false; 9481 for (auto *rhsProto : rhs->quals()) { 9482 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 9483 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 9484 match = true; 9485 break; 9486 } 9487 } 9488 if (!match) 9489 return false; 9490 } 9491 } 9492 return true; 9493 } 9494 return false; 9495 } 9496 9497 /// canAssignObjCInterfaces - Return true if the two interface types are 9498 /// compatible for assignment from RHS to LHS. This handles validation of any 9499 /// protocol qualifiers on the LHS or RHS. 9500 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, 9501 const ObjCObjectPointerType *RHSOPT) { 9502 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 9503 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 9504 9505 // If either type represents the built-in 'id' type, return true. 9506 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId()) 9507 return true; 9508 9509 // Function object that propagates a successful result or handles 9510 // __kindof types. 9511 auto finish = [&](bool succeeded) -> bool { 9512 if (succeeded) 9513 return true; 9514 9515 if (!RHS->isKindOfType()) 9516 return false; 9517 9518 // Strip off __kindof and protocol qualifiers, then check whether 9519 // we can assign the other way. 9520 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this), 9521 LHSOPT->stripObjCKindOfTypeAndQuals(*this)); 9522 }; 9523 9524 // Casts from or to id<P> are allowed when the other side has compatible 9525 // protocols. 9526 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) { 9527 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false)); 9528 } 9529 9530 // Verify protocol compatibility for casts from Class<P1> to Class<P2>. 9531 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) { 9532 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT)); 9533 } 9534 9535 // Casts from Class to Class<Foo>, or vice-versa, are allowed. 9536 if (LHS->isObjCClass() && RHS->isObjCClass()) { 9537 return true; 9538 } 9539 9540 // If we have 2 user-defined types, fall into that path. 9541 if (LHS->getInterface() && RHS->getInterface()) { 9542 return finish(canAssignObjCInterfaces(LHS, RHS)); 9543 } 9544 9545 return false; 9546 } 9547 9548 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written 9549 /// for providing type-safety for objective-c pointers used to pass/return 9550 /// arguments in block literals. When passed as arguments, passing 'A*' where 9551 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is 9552 /// not OK. For the return type, the opposite is not OK. 9553 bool ASTContext::canAssignObjCInterfacesInBlockPointer( 9554 const ObjCObjectPointerType *LHSOPT, 9555 const ObjCObjectPointerType *RHSOPT, 9556 bool BlockReturnType) { 9557 9558 // Function object that propagates a successful result or handles 9559 // __kindof types. 9560 auto finish = [&](bool succeeded) -> bool { 9561 if (succeeded) 9562 return true; 9563 9564 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT; 9565 if (!Expected->isKindOfType()) 9566 return false; 9567 9568 // Strip off __kindof and protocol qualifiers, then check whether 9569 // we can assign the other way. 9570 return canAssignObjCInterfacesInBlockPointer( 9571 RHSOPT->stripObjCKindOfTypeAndQuals(*this), 9572 LHSOPT->stripObjCKindOfTypeAndQuals(*this), 9573 BlockReturnType); 9574 }; 9575 9576 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType()) 9577 return true; 9578 9579 if (LHSOPT->isObjCBuiltinType()) { 9580 return finish(RHSOPT->isObjCBuiltinType() || 9581 RHSOPT->isObjCQualifiedIdType()); 9582 } 9583 9584 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) { 9585 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking) 9586 // Use for block parameters previous type checking for compatibility. 9587 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) || 9588 // Or corrected type checking as in non-compat mode. 9589 (!BlockReturnType && 9590 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false))); 9591 else 9592 return finish(ObjCQualifiedIdTypesAreCompatible( 9593 (BlockReturnType ? LHSOPT : RHSOPT), 9594 (BlockReturnType ? RHSOPT : LHSOPT), false)); 9595 } 9596 9597 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType(); 9598 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType(); 9599 if (LHS && RHS) { // We have 2 user-defined types. 9600 if (LHS != RHS) { 9601 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl())) 9602 return finish(BlockReturnType); 9603 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl())) 9604 return finish(!BlockReturnType); 9605 } 9606 else 9607 return true; 9608 } 9609 return false; 9610 } 9611 9612 /// Comparison routine for Objective-C protocols to be used with 9613 /// llvm::array_pod_sort. 9614 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs, 9615 ObjCProtocolDecl * const *rhs) { 9616 return (*lhs)->getName().compare((*rhs)->getName()); 9617 } 9618 9619 /// getIntersectionOfProtocols - This routine finds the intersection of set 9620 /// of protocols inherited from two distinct objective-c pointer objects with 9621 /// the given common base. 9622 /// It is used to build composite qualifier list of the composite type of 9623 /// the conditional expression involving two objective-c pointer objects. 9624 static 9625 void getIntersectionOfProtocols(ASTContext &Context, 9626 const ObjCInterfaceDecl *CommonBase, 9627 const ObjCObjectPointerType *LHSOPT, 9628 const ObjCObjectPointerType *RHSOPT, 9629 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) { 9630 9631 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 9632 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 9633 assert(LHS->getInterface() && "LHS must have an interface base"); 9634 assert(RHS->getInterface() && "RHS must have an interface base"); 9635 9636 // Add all of the protocols for the LHS. 9637 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet; 9638 9639 // Start with the protocol qualifiers. 9640 for (auto proto : LHS->quals()) { 9641 Context.CollectInheritedProtocols(proto, LHSProtocolSet); 9642 } 9643 9644 // Also add the protocols associated with the LHS interface. 9645 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet); 9646 9647 // Add all of the protocols for the RHS. 9648 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet; 9649 9650 // Start with the protocol qualifiers. 9651 for (auto proto : RHS->quals()) { 9652 Context.CollectInheritedProtocols(proto, RHSProtocolSet); 9653 } 9654 9655 // Also add the protocols associated with the RHS interface. 9656 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet); 9657 9658 // Compute the intersection of the collected protocol sets. 9659 for (auto proto : LHSProtocolSet) { 9660 if (RHSProtocolSet.count(proto)) 9661 IntersectionSet.push_back(proto); 9662 } 9663 9664 // Compute the set of protocols that is implied by either the common type or 9665 // the protocols within the intersection. 9666 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols; 9667 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols); 9668 9669 // Remove any implied protocols from the list of inherited protocols. 9670 if (!ImpliedProtocols.empty()) { 9671 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool { 9672 return ImpliedProtocols.contains(proto); 9673 }); 9674 } 9675 9676 // Sort the remaining protocols by name. 9677 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(), 9678 compareObjCProtocolsByName); 9679 } 9680 9681 /// Determine whether the first type is a subtype of the second. 9682 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs, 9683 QualType rhs) { 9684 // Common case: two object pointers. 9685 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>(); 9686 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 9687 if (lhsOPT && rhsOPT) 9688 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT); 9689 9690 // Two block pointers. 9691 const auto *lhsBlock = lhs->getAs<BlockPointerType>(); 9692 const auto *rhsBlock = rhs->getAs<BlockPointerType>(); 9693 if (lhsBlock && rhsBlock) 9694 return ctx.typesAreBlockPointerCompatible(lhs, rhs); 9695 9696 // If either is an unqualified 'id' and the other is a block, it's 9697 // acceptable. 9698 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) || 9699 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock)) 9700 return true; 9701 9702 return false; 9703 } 9704 9705 // Check that the given Objective-C type argument lists are equivalent. 9706 static bool sameObjCTypeArgs(ASTContext &ctx, 9707 const ObjCInterfaceDecl *iface, 9708 ArrayRef<QualType> lhsArgs, 9709 ArrayRef<QualType> rhsArgs, 9710 bool stripKindOf) { 9711 if (lhsArgs.size() != rhsArgs.size()) 9712 return false; 9713 9714 ObjCTypeParamList *typeParams = iface->getTypeParamList(); 9715 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) { 9716 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i])) 9717 continue; 9718 9719 switch (typeParams->begin()[i]->getVariance()) { 9720 case ObjCTypeParamVariance::Invariant: 9721 if (!stripKindOf || 9722 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx), 9723 rhsArgs[i].stripObjCKindOfType(ctx))) { 9724 return false; 9725 } 9726 break; 9727 9728 case ObjCTypeParamVariance::Covariant: 9729 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i])) 9730 return false; 9731 break; 9732 9733 case ObjCTypeParamVariance::Contravariant: 9734 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i])) 9735 return false; 9736 break; 9737 } 9738 } 9739 9740 return true; 9741 } 9742 9743 QualType ASTContext::areCommonBaseCompatible( 9744 const ObjCObjectPointerType *Lptr, 9745 const ObjCObjectPointerType *Rptr) { 9746 const ObjCObjectType *LHS = Lptr->getObjectType(); 9747 const ObjCObjectType *RHS = Rptr->getObjectType(); 9748 const ObjCInterfaceDecl* LDecl = LHS->getInterface(); 9749 const ObjCInterfaceDecl* RDecl = RHS->getInterface(); 9750 9751 if (!LDecl || !RDecl) 9752 return {}; 9753 9754 // When either LHS or RHS is a kindof type, we should return a kindof type. 9755 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return 9756 // kindof(A). 9757 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType(); 9758 9759 // Follow the left-hand side up the class hierarchy until we either hit a 9760 // root or find the RHS. Record the ancestors in case we don't find it. 9761 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4> 9762 LHSAncestors; 9763 while (true) { 9764 // Record this ancestor. We'll need this if the common type isn't in the 9765 // path from the LHS to the root. 9766 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS; 9767 9768 if (declaresSameEntity(LHS->getInterface(), RDecl)) { 9769 // Get the type arguments. 9770 ArrayRef<QualType> LHSTypeArgs = LHS->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 LHSTypeArgs = {}; 9782 anyChanges = true; 9783 } 9784 9785 // Compute the intersection of protocols. 9786 SmallVector<ObjCProtocolDecl *, 8> Protocols; 9787 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr, 9788 Protocols); 9789 if (!Protocols.empty()) 9790 anyChanges = true; 9791 9792 // If anything in the LHS will have changed, build a new result type. 9793 // If we need to return a kindof type but LHS is not a kindof type, we 9794 // build a new result type. 9795 if (anyChanges || LHS->isKindOfType() != anyKindOf) { 9796 QualType Result = getObjCInterfaceType(LHS->getInterface()); 9797 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols, 9798 anyKindOf || LHS->isKindOfType()); 9799 return getObjCObjectPointerType(Result); 9800 } 9801 9802 return getObjCObjectPointerType(QualType(LHS, 0)); 9803 } 9804 9805 // Find the superclass. 9806 QualType LHSSuperType = LHS->getSuperClassType(); 9807 if (LHSSuperType.isNull()) 9808 break; 9809 9810 LHS = LHSSuperType->castAs<ObjCObjectType>(); 9811 } 9812 9813 // We didn't find anything by following the LHS to its root; now check 9814 // the RHS against the cached set of ancestors. 9815 while (true) { 9816 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl()); 9817 if (KnownLHS != LHSAncestors.end()) { 9818 LHS = KnownLHS->second; 9819 9820 // Get the type arguments. 9821 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten(); 9822 bool anyChanges = false; 9823 if (LHS->isSpecialized() && RHS->isSpecialized()) { 9824 // Both have type arguments, compare them. 9825 if (!sameObjCTypeArgs(*this, LHS->getInterface(), 9826 LHS->getTypeArgs(), RHS->getTypeArgs(), 9827 /*stripKindOf=*/true)) 9828 return {}; 9829 } else if (LHS->isSpecialized() != RHS->isSpecialized()) { 9830 // If only one has type arguments, the result will not have type 9831 // arguments. 9832 RHSTypeArgs = {}; 9833 anyChanges = true; 9834 } 9835 9836 // Compute the intersection of protocols. 9837 SmallVector<ObjCProtocolDecl *, 8> Protocols; 9838 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr, 9839 Protocols); 9840 if (!Protocols.empty()) 9841 anyChanges = true; 9842 9843 // If we need to return a kindof type but RHS is not a kindof type, we 9844 // build a new result type. 9845 if (anyChanges || RHS->isKindOfType() != anyKindOf) { 9846 QualType Result = getObjCInterfaceType(RHS->getInterface()); 9847 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols, 9848 anyKindOf || RHS->isKindOfType()); 9849 return getObjCObjectPointerType(Result); 9850 } 9851 9852 return getObjCObjectPointerType(QualType(RHS, 0)); 9853 } 9854 9855 // Find the superclass of the RHS. 9856 QualType RHSSuperType = RHS->getSuperClassType(); 9857 if (RHSSuperType.isNull()) 9858 break; 9859 9860 RHS = RHSSuperType->castAs<ObjCObjectType>(); 9861 } 9862 9863 return {}; 9864 } 9865 9866 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS, 9867 const ObjCObjectType *RHS) { 9868 assert(LHS->getInterface() && "LHS is not an interface type"); 9869 assert(RHS->getInterface() && "RHS is not an interface type"); 9870 9871 // Verify that the base decls are compatible: the RHS must be a subclass of 9872 // the LHS. 9873 ObjCInterfaceDecl *LHSInterface = LHS->getInterface(); 9874 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface()); 9875 if (!IsSuperClass) 9876 return false; 9877 9878 // If the LHS has protocol qualifiers, determine whether all of them are 9879 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the 9880 // LHS). 9881 if (LHS->getNumProtocols() > 0) { 9882 // OK if conversion of LHS to SuperClass results in narrowing of types 9883 // ; i.e., SuperClass may implement at least one of the protocols 9884 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok. 9885 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>. 9886 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols; 9887 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols); 9888 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's 9889 // qualifiers. 9890 for (auto *RHSPI : RHS->quals()) 9891 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols); 9892 // If there is no protocols associated with RHS, it is not a match. 9893 if (SuperClassInheritedProtocols.empty()) 9894 return false; 9895 9896 for (const auto *LHSProto : LHS->quals()) { 9897 bool SuperImplementsProtocol = false; 9898 for (auto *SuperClassProto : SuperClassInheritedProtocols) 9899 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) { 9900 SuperImplementsProtocol = true; 9901 break; 9902 } 9903 if (!SuperImplementsProtocol) 9904 return false; 9905 } 9906 } 9907 9908 // If the LHS is specialized, we may need to check type arguments. 9909 if (LHS->isSpecialized()) { 9910 // Follow the superclass chain until we've matched the LHS class in the 9911 // hierarchy. This substitutes type arguments through. 9912 const ObjCObjectType *RHSSuper = RHS; 9913 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface)) 9914 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>(); 9915 9916 // If the RHS is specializd, compare type arguments. 9917 if (RHSSuper->isSpecialized() && 9918 !sameObjCTypeArgs(*this, LHS->getInterface(), 9919 LHS->getTypeArgs(), RHSSuper->getTypeArgs(), 9920 /*stripKindOf=*/true)) { 9921 return false; 9922 } 9923 } 9924 9925 return true; 9926 } 9927 9928 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) { 9929 // get the "pointed to" types 9930 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>(); 9931 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>(); 9932 9933 if (!LHSOPT || !RHSOPT) 9934 return false; 9935 9936 return canAssignObjCInterfaces(LHSOPT, RHSOPT) || 9937 canAssignObjCInterfaces(RHSOPT, LHSOPT); 9938 } 9939 9940 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) { 9941 return canAssignObjCInterfaces( 9942 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(), 9943 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>()); 9944 } 9945 9946 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible, 9947 /// both shall have the identically qualified version of a compatible type. 9948 /// C99 6.2.7p1: Two types have compatible types if their types are the 9949 /// same. See 6.7.[2,3,5] for additional rules. 9950 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS, 9951 bool CompareUnqualified) { 9952 if (getLangOpts().CPlusPlus) 9953 return hasSameType(LHS, RHS); 9954 9955 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull(); 9956 } 9957 9958 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) { 9959 return typesAreCompatible(LHS, RHS); 9960 } 9961 9962 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) { 9963 return !mergeTypes(LHS, RHS, true).isNull(); 9964 } 9965 9966 /// mergeTransparentUnionType - if T is a transparent union type and a member 9967 /// of T is compatible with SubType, return the merged type, else return 9968 /// QualType() 9969 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType, 9970 bool OfBlockPointer, 9971 bool Unqualified) { 9972 if (const RecordType *UT = T->getAsUnionType()) { 9973 RecordDecl *UD = UT->getDecl(); 9974 if (UD->hasAttr<TransparentUnionAttr>()) { 9975 for (const auto *I : UD->fields()) { 9976 QualType ET = I->getType().getUnqualifiedType(); 9977 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified); 9978 if (!MT.isNull()) 9979 return MT; 9980 } 9981 } 9982 } 9983 9984 return {}; 9985 } 9986 9987 /// mergeFunctionParameterTypes - merge two types which appear as function 9988 /// parameter types 9989 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs, 9990 bool OfBlockPointer, 9991 bool Unqualified) { 9992 // GNU extension: two types are compatible if they appear as a function 9993 // argument, one of the types is a transparent union type and the other 9994 // type is compatible with a union member 9995 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer, 9996 Unqualified); 9997 if (!lmerge.isNull()) 9998 return lmerge; 9999 10000 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer, 10001 Unqualified); 10002 if (!rmerge.isNull()) 10003 return rmerge; 10004 10005 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified); 10006 } 10007 10008 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, 10009 bool OfBlockPointer, bool Unqualified, 10010 bool AllowCXX) { 10011 const auto *lbase = lhs->castAs<FunctionType>(); 10012 const auto *rbase = rhs->castAs<FunctionType>(); 10013 const auto *lproto = dyn_cast<FunctionProtoType>(lbase); 10014 const auto *rproto = dyn_cast<FunctionProtoType>(rbase); 10015 bool allLTypes = true; 10016 bool allRTypes = true; 10017 10018 // Check return type 10019 QualType retType; 10020 if (OfBlockPointer) { 10021 QualType RHS = rbase->getReturnType(); 10022 QualType LHS = lbase->getReturnType(); 10023 bool UnqualifiedResult = Unqualified; 10024 if (!UnqualifiedResult) 10025 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers()); 10026 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true); 10027 } 10028 else 10029 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false, 10030 Unqualified); 10031 if (retType.isNull()) 10032 return {}; 10033 10034 if (Unqualified) 10035 retType = retType.getUnqualifiedType(); 10036 10037 CanQualType LRetType = getCanonicalType(lbase->getReturnType()); 10038 CanQualType RRetType = getCanonicalType(rbase->getReturnType()); 10039 if (Unqualified) { 10040 LRetType = LRetType.getUnqualifiedType(); 10041 RRetType = RRetType.getUnqualifiedType(); 10042 } 10043 10044 if (getCanonicalType(retType) != LRetType) 10045 allLTypes = false; 10046 if (getCanonicalType(retType) != RRetType) 10047 allRTypes = false; 10048 10049 // FIXME: double check this 10050 // FIXME: should we error if lbase->getRegParmAttr() != 0 && 10051 // rbase->getRegParmAttr() != 0 && 10052 // lbase->getRegParmAttr() != rbase->getRegParmAttr()? 10053 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo(); 10054 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo(); 10055 10056 // Compatible functions must have compatible calling conventions 10057 if (lbaseInfo.getCC() != rbaseInfo.getCC()) 10058 return {}; 10059 10060 // Regparm is part of the calling convention. 10061 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm()) 10062 return {}; 10063 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm()) 10064 return {}; 10065 10066 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult()) 10067 return {}; 10068 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs()) 10069 return {}; 10070 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck()) 10071 return {}; 10072 10073 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'. 10074 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn(); 10075 10076 if (lbaseInfo.getNoReturn() != NoReturn) 10077 allLTypes = false; 10078 if (rbaseInfo.getNoReturn() != NoReturn) 10079 allRTypes = false; 10080 10081 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn); 10082 10083 if (lproto && rproto) { // two C99 style function prototypes 10084 assert((AllowCXX || 10085 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) && 10086 "C++ shouldn't be here"); 10087 // Compatible functions must have the same number of parameters 10088 if (lproto->getNumParams() != rproto->getNumParams()) 10089 return {}; 10090 10091 // Variadic and non-variadic functions aren't compatible 10092 if (lproto->isVariadic() != rproto->isVariadic()) 10093 return {}; 10094 10095 if (lproto->getMethodQuals() != rproto->getMethodQuals()) 10096 return {}; 10097 10098 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos; 10099 bool canUseLeft, canUseRight; 10100 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight, 10101 newParamInfos)) 10102 return {}; 10103 10104 if (!canUseLeft) 10105 allLTypes = false; 10106 if (!canUseRight) 10107 allRTypes = false; 10108 10109 // Check parameter type compatibility 10110 SmallVector<QualType, 10> types; 10111 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) { 10112 QualType lParamType = lproto->getParamType(i).getUnqualifiedType(); 10113 QualType rParamType = rproto->getParamType(i).getUnqualifiedType(); 10114 QualType paramType = mergeFunctionParameterTypes( 10115 lParamType, rParamType, OfBlockPointer, Unqualified); 10116 if (paramType.isNull()) 10117 return {}; 10118 10119 if (Unqualified) 10120 paramType = paramType.getUnqualifiedType(); 10121 10122 types.push_back(paramType); 10123 if (Unqualified) { 10124 lParamType = lParamType.getUnqualifiedType(); 10125 rParamType = rParamType.getUnqualifiedType(); 10126 } 10127 10128 if (getCanonicalType(paramType) != getCanonicalType(lParamType)) 10129 allLTypes = false; 10130 if (getCanonicalType(paramType) != getCanonicalType(rParamType)) 10131 allRTypes = false; 10132 } 10133 10134 if (allLTypes) return lhs; 10135 if (allRTypes) return rhs; 10136 10137 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo(); 10138 EPI.ExtInfo = einfo; 10139 EPI.ExtParameterInfos = 10140 newParamInfos.empty() ? nullptr : newParamInfos.data(); 10141 return getFunctionType(retType, types, EPI); 10142 } 10143 10144 if (lproto) allRTypes = false; 10145 if (rproto) allLTypes = false; 10146 10147 const FunctionProtoType *proto = lproto ? lproto : rproto; 10148 if (proto) { 10149 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here"); 10150 if (proto->isVariadic()) 10151 return {}; 10152 // Check that the types are compatible with the types that 10153 // would result from default argument promotions (C99 6.7.5.3p15). 10154 // The only types actually affected are promotable integer 10155 // types and floats, which would be passed as a different 10156 // type depending on whether the prototype is visible. 10157 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) { 10158 QualType paramTy = proto->getParamType(i); 10159 10160 // Look at the converted type of enum types, since that is the type used 10161 // to pass enum values. 10162 if (const auto *Enum = paramTy->getAs<EnumType>()) { 10163 paramTy = Enum->getDecl()->getIntegerType(); 10164 if (paramTy.isNull()) 10165 return {}; 10166 } 10167 10168 if (paramTy->isPromotableIntegerType() || 10169 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy) 10170 return {}; 10171 } 10172 10173 if (allLTypes) return lhs; 10174 if (allRTypes) return rhs; 10175 10176 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo(); 10177 EPI.ExtInfo = einfo; 10178 return getFunctionType(retType, proto->getParamTypes(), EPI); 10179 } 10180 10181 if (allLTypes) return lhs; 10182 if (allRTypes) return rhs; 10183 return getFunctionNoProtoType(retType, einfo); 10184 } 10185 10186 /// Given that we have an enum type and a non-enum type, try to merge them. 10187 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET, 10188 QualType other, bool isBlockReturnType) { 10189 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char, 10190 // a signed integer type, or an unsigned integer type. 10191 // Compatibility is based on the underlying type, not the promotion 10192 // type. 10193 QualType underlyingType = ET->getDecl()->getIntegerType(); 10194 if (underlyingType.isNull()) 10195 return {}; 10196 if (Context.hasSameType(underlyingType, other)) 10197 return other; 10198 10199 // In block return types, we're more permissive and accept any 10200 // integral type of the same size. 10201 if (isBlockReturnType && other->isIntegerType() && 10202 Context.getTypeSize(underlyingType) == Context.getTypeSize(other)) 10203 return other; 10204 10205 return {}; 10206 } 10207 10208 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, 10209 bool OfBlockPointer, 10210 bool Unqualified, bool BlockReturnType) { 10211 // For C++ we will not reach this code with reference types (see below), 10212 // for OpenMP variant call overloading we might. 10213 // 10214 // C++ [expr]: If an expression initially has the type "reference to T", the 10215 // type is adjusted to "T" prior to any further analysis, the expression 10216 // designates the object or function denoted by the reference, and the 10217 // expression is an lvalue unless the reference is an rvalue reference and 10218 // the expression is a function call (possibly inside parentheses). 10219 auto *LHSRefTy = LHS->getAs<ReferenceType>(); 10220 auto *RHSRefTy = RHS->getAs<ReferenceType>(); 10221 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy && 10222 LHS->getTypeClass() == RHS->getTypeClass()) 10223 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(), 10224 OfBlockPointer, Unqualified, BlockReturnType); 10225 if (LHSRefTy || RHSRefTy) 10226 return {}; 10227 10228 if (Unqualified) { 10229 LHS = LHS.getUnqualifiedType(); 10230 RHS = RHS.getUnqualifiedType(); 10231 } 10232 10233 QualType LHSCan = getCanonicalType(LHS), 10234 RHSCan = getCanonicalType(RHS); 10235 10236 // If two types are identical, they are compatible. 10237 if (LHSCan == RHSCan) 10238 return LHS; 10239 10240 // If the qualifiers are different, the types aren't compatible... mostly. 10241 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 10242 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 10243 if (LQuals != RQuals) { 10244 // If any of these qualifiers are different, we have a type 10245 // mismatch. 10246 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 10247 LQuals.getAddressSpace() != RQuals.getAddressSpace() || 10248 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() || 10249 LQuals.hasUnaligned() != RQuals.hasUnaligned()) 10250 return {}; 10251 10252 // Exactly one GC qualifier difference is allowed: __strong is 10253 // okay if the other type has no GC qualifier but is an Objective 10254 // C object pointer (i.e. implicitly strong by default). We fix 10255 // this by pretending that the unqualified type was actually 10256 // qualified __strong. 10257 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 10258 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 10259 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 10260 10261 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 10262 return {}; 10263 10264 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) { 10265 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong)); 10266 } 10267 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) { 10268 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS); 10269 } 10270 return {}; 10271 } 10272 10273 // Okay, qualifiers are equal. 10274 10275 Type::TypeClass LHSClass = LHSCan->getTypeClass(); 10276 Type::TypeClass RHSClass = RHSCan->getTypeClass(); 10277 10278 // We want to consider the two function types to be the same for these 10279 // comparisons, just force one to the other. 10280 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto; 10281 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto; 10282 10283 // Same as above for arrays 10284 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray) 10285 LHSClass = Type::ConstantArray; 10286 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray) 10287 RHSClass = Type::ConstantArray; 10288 10289 // ObjCInterfaces are just specialized ObjCObjects. 10290 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject; 10291 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject; 10292 10293 // Canonicalize ExtVector -> Vector. 10294 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector; 10295 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector; 10296 10297 // If the canonical type classes don't match. 10298 if (LHSClass != RHSClass) { 10299 // Note that we only have special rules for turning block enum 10300 // returns into block int returns, not vice-versa. 10301 if (const auto *ETy = LHS->getAs<EnumType>()) { 10302 return mergeEnumWithInteger(*this, ETy, RHS, false); 10303 } 10304 if (const EnumType* ETy = RHS->getAs<EnumType>()) { 10305 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType); 10306 } 10307 // allow block pointer type to match an 'id' type. 10308 if (OfBlockPointer && !BlockReturnType) { 10309 if (LHS->isObjCIdType() && RHS->isBlockPointerType()) 10310 return LHS; 10311 if (RHS->isObjCIdType() && LHS->isBlockPointerType()) 10312 return RHS; 10313 } 10314 // Allow __auto_type to match anything; it merges to the type with more 10315 // information. 10316 if (const auto *AT = LHS->getAs<AutoType>()) { 10317 if (AT->isGNUAutoType()) 10318 return RHS; 10319 } 10320 if (const auto *AT = RHS->getAs<AutoType>()) { 10321 if (AT->isGNUAutoType()) 10322 return LHS; 10323 } 10324 return {}; 10325 } 10326 10327 // The canonical type classes match. 10328 switch (LHSClass) { 10329 #define TYPE(Class, Base) 10330 #define ABSTRACT_TYPE(Class, Base) 10331 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 10332 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 10333 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 10334 #include "clang/AST/TypeNodes.inc" 10335 llvm_unreachable("Non-canonical and dependent types shouldn't get here"); 10336 10337 case Type::Auto: 10338 case Type::DeducedTemplateSpecialization: 10339 case Type::LValueReference: 10340 case Type::RValueReference: 10341 case Type::MemberPointer: 10342 llvm_unreachable("C++ should never be in mergeTypes"); 10343 10344 case Type::ObjCInterface: 10345 case Type::IncompleteArray: 10346 case Type::VariableArray: 10347 case Type::FunctionProto: 10348 case Type::ExtVector: 10349 llvm_unreachable("Types are eliminated above"); 10350 10351 case Type::Pointer: 10352 { 10353 // Merge two pointer types, while trying to preserve typedef info 10354 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType(); 10355 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType(); 10356 if (Unqualified) { 10357 LHSPointee = LHSPointee.getUnqualifiedType(); 10358 RHSPointee = RHSPointee.getUnqualifiedType(); 10359 } 10360 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false, 10361 Unqualified); 10362 if (ResultType.isNull()) 10363 return {}; 10364 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 10365 return LHS; 10366 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 10367 return RHS; 10368 return getPointerType(ResultType); 10369 } 10370 case Type::BlockPointer: 10371 { 10372 // Merge two block pointer types, while trying to preserve typedef info 10373 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType(); 10374 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType(); 10375 if (Unqualified) { 10376 LHSPointee = LHSPointee.getUnqualifiedType(); 10377 RHSPointee = RHSPointee.getUnqualifiedType(); 10378 } 10379 if (getLangOpts().OpenCL) { 10380 Qualifiers LHSPteeQual = LHSPointee.getQualifiers(); 10381 Qualifiers RHSPteeQual = RHSPointee.getQualifiers(); 10382 // Blocks can't be an expression in a ternary operator (OpenCL v2.0 10383 // 6.12.5) thus the following check is asymmetric. 10384 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual)) 10385 return {}; 10386 LHSPteeQual.removeAddressSpace(); 10387 RHSPteeQual.removeAddressSpace(); 10388 LHSPointee = 10389 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue()); 10390 RHSPointee = 10391 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue()); 10392 } 10393 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer, 10394 Unqualified); 10395 if (ResultType.isNull()) 10396 return {}; 10397 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 10398 return LHS; 10399 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 10400 return RHS; 10401 return getBlockPointerType(ResultType); 10402 } 10403 case Type::Atomic: 10404 { 10405 // Merge two pointer types, while trying to preserve typedef info 10406 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType(); 10407 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType(); 10408 if (Unqualified) { 10409 LHSValue = LHSValue.getUnqualifiedType(); 10410 RHSValue = RHSValue.getUnqualifiedType(); 10411 } 10412 QualType ResultType = mergeTypes(LHSValue, RHSValue, false, 10413 Unqualified); 10414 if (ResultType.isNull()) 10415 return {}; 10416 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType)) 10417 return LHS; 10418 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType)) 10419 return RHS; 10420 return getAtomicType(ResultType); 10421 } 10422 case Type::ConstantArray: 10423 { 10424 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS); 10425 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS); 10426 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize()) 10427 return {}; 10428 10429 QualType LHSElem = getAsArrayType(LHS)->getElementType(); 10430 QualType RHSElem = getAsArrayType(RHS)->getElementType(); 10431 if (Unqualified) { 10432 LHSElem = LHSElem.getUnqualifiedType(); 10433 RHSElem = RHSElem.getUnqualifiedType(); 10434 } 10435 10436 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified); 10437 if (ResultType.isNull()) 10438 return {}; 10439 10440 const VariableArrayType* LVAT = getAsVariableArrayType(LHS); 10441 const VariableArrayType* RVAT = getAsVariableArrayType(RHS); 10442 10443 // If either side is a variable array, and both are complete, check whether 10444 // the current dimension is definite. 10445 if (LVAT || RVAT) { 10446 auto SizeFetch = [this](const VariableArrayType* VAT, 10447 const ConstantArrayType* CAT) 10448 -> std::pair<bool,llvm::APInt> { 10449 if (VAT) { 10450 Optional<llvm::APSInt> TheInt; 10451 Expr *E = VAT->getSizeExpr(); 10452 if (E && (TheInt = E->getIntegerConstantExpr(*this))) 10453 return std::make_pair(true, *TheInt); 10454 return std::make_pair(false, llvm::APSInt()); 10455 } 10456 if (CAT) 10457 return std::make_pair(true, CAT->getSize()); 10458 return std::make_pair(false, llvm::APInt()); 10459 }; 10460 10461 bool HaveLSize, HaveRSize; 10462 llvm::APInt LSize, RSize; 10463 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT); 10464 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT); 10465 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize)) 10466 return {}; // Definite, but unequal, array dimension 10467 } 10468 10469 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 10470 return LHS; 10471 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 10472 return RHS; 10473 if (LCAT) 10474 return getConstantArrayType(ResultType, LCAT->getSize(), 10475 LCAT->getSizeExpr(), 10476 ArrayType::ArraySizeModifier(), 0); 10477 if (RCAT) 10478 return getConstantArrayType(ResultType, RCAT->getSize(), 10479 RCAT->getSizeExpr(), 10480 ArrayType::ArraySizeModifier(), 0); 10481 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 10482 return LHS; 10483 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 10484 return RHS; 10485 if (LVAT) { 10486 // FIXME: This isn't correct! But tricky to implement because 10487 // the array's size has to be the size of LHS, but the type 10488 // has to be different. 10489 return LHS; 10490 } 10491 if (RVAT) { 10492 // FIXME: This isn't correct! But tricky to implement because 10493 // the array's size has to be the size of RHS, but the type 10494 // has to be different. 10495 return RHS; 10496 } 10497 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS; 10498 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS; 10499 return getIncompleteArrayType(ResultType, 10500 ArrayType::ArraySizeModifier(), 0); 10501 } 10502 case Type::FunctionNoProto: 10503 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified); 10504 case Type::Record: 10505 case Type::Enum: 10506 return {}; 10507 case Type::Builtin: 10508 // Only exactly equal builtin types are compatible, which is tested above. 10509 return {}; 10510 case Type::Complex: 10511 // Distinct complex types are incompatible. 10512 return {}; 10513 case Type::Vector: 10514 // FIXME: The merged type should be an ExtVector! 10515 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(), 10516 RHSCan->castAs<VectorType>())) 10517 return LHS; 10518 return {}; 10519 case Type::ConstantMatrix: 10520 if (areCompatMatrixTypes(LHSCan->castAs<ConstantMatrixType>(), 10521 RHSCan->castAs<ConstantMatrixType>())) 10522 return LHS; 10523 return {}; 10524 case Type::ObjCObject: { 10525 // Check if the types are assignment compatible. 10526 // FIXME: This should be type compatibility, e.g. whether 10527 // "LHS x; RHS x;" at global scope is legal. 10528 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectType>(), 10529 RHS->castAs<ObjCObjectType>())) 10530 return LHS; 10531 return {}; 10532 } 10533 case Type::ObjCObjectPointer: 10534 if (OfBlockPointer) { 10535 if (canAssignObjCInterfacesInBlockPointer( 10536 LHS->castAs<ObjCObjectPointerType>(), 10537 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType)) 10538 return LHS; 10539 return {}; 10540 } 10541 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectPointerType>(), 10542 RHS->castAs<ObjCObjectPointerType>())) 10543 return LHS; 10544 return {}; 10545 case Type::Pipe: 10546 assert(LHS != RHS && 10547 "Equivalent pipe types should have already been handled!"); 10548 return {}; 10549 case Type::BitInt: { 10550 // Merge two bit-precise int types, while trying to preserve typedef info. 10551 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned(); 10552 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned(); 10553 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits(); 10554 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits(); 10555 10556 // Like unsigned/int, shouldn't have a type if they don't match. 10557 if (LHSUnsigned != RHSUnsigned) 10558 return {}; 10559 10560 if (LHSBits != RHSBits) 10561 return {}; 10562 return LHS; 10563 } 10564 } 10565 10566 llvm_unreachable("Invalid Type::Class!"); 10567 } 10568 10569 bool ASTContext::mergeExtParameterInfo( 10570 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType, 10571 bool &CanUseFirst, bool &CanUseSecond, 10572 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) { 10573 assert(NewParamInfos.empty() && "param info list not empty"); 10574 CanUseFirst = CanUseSecond = true; 10575 bool FirstHasInfo = FirstFnType->hasExtParameterInfos(); 10576 bool SecondHasInfo = SecondFnType->hasExtParameterInfos(); 10577 10578 // Fast path: if the first type doesn't have ext parameter infos, 10579 // we match if and only if the second type also doesn't have them. 10580 if (!FirstHasInfo && !SecondHasInfo) 10581 return true; 10582 10583 bool NeedParamInfo = false; 10584 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size() 10585 : SecondFnType->getExtParameterInfos().size(); 10586 10587 for (size_t I = 0; I < E; ++I) { 10588 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam; 10589 if (FirstHasInfo) 10590 FirstParam = FirstFnType->getExtParameterInfo(I); 10591 if (SecondHasInfo) 10592 SecondParam = SecondFnType->getExtParameterInfo(I); 10593 10594 // Cannot merge unless everything except the noescape flag matches. 10595 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false)) 10596 return false; 10597 10598 bool FirstNoEscape = FirstParam.isNoEscape(); 10599 bool SecondNoEscape = SecondParam.isNoEscape(); 10600 bool IsNoEscape = FirstNoEscape && SecondNoEscape; 10601 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape)); 10602 if (NewParamInfos.back().getOpaqueValue()) 10603 NeedParamInfo = true; 10604 if (FirstNoEscape != IsNoEscape) 10605 CanUseFirst = false; 10606 if (SecondNoEscape != IsNoEscape) 10607 CanUseSecond = false; 10608 } 10609 10610 if (!NeedParamInfo) 10611 NewParamInfos.clear(); 10612 10613 return true; 10614 } 10615 10616 void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) { 10617 ObjCLayouts[CD] = nullptr; 10618 } 10619 10620 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 10621 /// 'RHS' attributes and returns the merged version; including for function 10622 /// return types. 10623 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) { 10624 QualType LHSCan = getCanonicalType(LHS), 10625 RHSCan = getCanonicalType(RHS); 10626 // If two types are identical, they are compatible. 10627 if (LHSCan == RHSCan) 10628 return LHS; 10629 if (RHSCan->isFunctionType()) { 10630 if (!LHSCan->isFunctionType()) 10631 return {}; 10632 QualType OldReturnType = 10633 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType(); 10634 QualType NewReturnType = 10635 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType(); 10636 QualType ResReturnType = 10637 mergeObjCGCQualifiers(NewReturnType, OldReturnType); 10638 if (ResReturnType.isNull()) 10639 return {}; 10640 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) { 10641 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo(); 10642 // In either case, use OldReturnType to build the new function type. 10643 const auto *F = LHS->castAs<FunctionType>(); 10644 if (const auto *FPT = cast<FunctionProtoType>(F)) { 10645 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10646 EPI.ExtInfo = getFunctionExtInfo(LHS); 10647 QualType ResultType = 10648 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI); 10649 return ResultType; 10650 } 10651 } 10652 return {}; 10653 } 10654 10655 // If the qualifiers are different, the types can still be merged. 10656 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 10657 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 10658 if (LQuals != RQuals) { 10659 // If any of these qualifiers are different, we have a type mismatch. 10660 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 10661 LQuals.getAddressSpace() != RQuals.getAddressSpace()) 10662 return {}; 10663 10664 // Exactly one GC qualifier difference is allowed: __strong is 10665 // okay if the other type has no GC qualifier but is an Objective 10666 // C object pointer (i.e. implicitly strong by default). We fix 10667 // this by pretending that the unqualified type was actually 10668 // qualified __strong. 10669 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 10670 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 10671 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 10672 10673 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 10674 return {}; 10675 10676 if (GC_L == Qualifiers::Strong) 10677 return LHS; 10678 if (GC_R == Qualifiers::Strong) 10679 return RHS; 10680 return {}; 10681 } 10682 10683 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) { 10684 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType(); 10685 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType(); 10686 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT); 10687 if (ResQT == LHSBaseQT) 10688 return LHS; 10689 if (ResQT == RHSBaseQT) 10690 return RHS; 10691 } 10692 return {}; 10693 } 10694 10695 //===----------------------------------------------------------------------===// 10696 // Integer Predicates 10697 //===----------------------------------------------------------------------===// 10698 10699 unsigned ASTContext::getIntWidth(QualType T) const { 10700 if (const auto *ET = T->getAs<EnumType>()) 10701 T = ET->getDecl()->getIntegerType(); 10702 if (T->isBooleanType()) 10703 return 1; 10704 if (const auto *EIT = T->getAs<BitIntType>()) 10705 return EIT->getNumBits(); 10706 // For builtin types, just use the standard type sizing method 10707 return (unsigned)getTypeSize(T); 10708 } 10709 10710 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const { 10711 assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) && 10712 "Unexpected type"); 10713 10714 // Turn <4 x signed int> -> <4 x unsigned int> 10715 if (const auto *VTy = T->getAs<VectorType>()) 10716 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()), 10717 VTy->getNumElements(), VTy->getVectorKind()); 10718 10719 // For _BitInt, return an unsigned _BitInt with same width. 10720 if (const auto *EITy = T->getAs<BitIntType>()) 10721 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits()); 10722 10723 // For enums, get the underlying integer type of the enum, and let the general 10724 // integer type signchanging code handle it. 10725 if (const auto *ETy = T->getAs<EnumType>()) 10726 T = ETy->getDecl()->getIntegerType(); 10727 10728 switch (T->castAs<BuiltinType>()->getKind()) { 10729 case BuiltinType::Char_S: 10730 case BuiltinType::SChar: 10731 return UnsignedCharTy; 10732 case BuiltinType::Short: 10733 return UnsignedShortTy; 10734 case BuiltinType::Int: 10735 return UnsignedIntTy; 10736 case BuiltinType::Long: 10737 return UnsignedLongTy; 10738 case BuiltinType::LongLong: 10739 return UnsignedLongLongTy; 10740 case BuiltinType::Int128: 10741 return UnsignedInt128Ty; 10742 // wchar_t is special. It is either signed or not, but when it's signed, 10743 // there's no matching "unsigned wchar_t". Therefore we return the unsigned 10744 // version of it's underlying type instead. 10745 case BuiltinType::WChar_S: 10746 return getUnsignedWCharType(); 10747 10748 case BuiltinType::ShortAccum: 10749 return UnsignedShortAccumTy; 10750 case BuiltinType::Accum: 10751 return UnsignedAccumTy; 10752 case BuiltinType::LongAccum: 10753 return UnsignedLongAccumTy; 10754 case BuiltinType::SatShortAccum: 10755 return SatUnsignedShortAccumTy; 10756 case BuiltinType::SatAccum: 10757 return SatUnsignedAccumTy; 10758 case BuiltinType::SatLongAccum: 10759 return SatUnsignedLongAccumTy; 10760 case BuiltinType::ShortFract: 10761 return UnsignedShortFractTy; 10762 case BuiltinType::Fract: 10763 return UnsignedFractTy; 10764 case BuiltinType::LongFract: 10765 return UnsignedLongFractTy; 10766 case BuiltinType::SatShortFract: 10767 return SatUnsignedShortFractTy; 10768 case BuiltinType::SatFract: 10769 return SatUnsignedFractTy; 10770 case BuiltinType::SatLongFract: 10771 return SatUnsignedLongFractTy; 10772 default: 10773 llvm_unreachable("Unexpected signed integer or fixed point type"); 10774 } 10775 } 10776 10777 QualType ASTContext::getCorrespondingSignedType(QualType T) const { 10778 assert((T->hasUnsignedIntegerRepresentation() || 10779 T->isUnsignedFixedPointType()) && 10780 "Unexpected type"); 10781 10782 // Turn <4 x unsigned int> -> <4 x signed int> 10783 if (const auto *VTy = T->getAs<VectorType>()) 10784 return getVectorType(getCorrespondingSignedType(VTy->getElementType()), 10785 VTy->getNumElements(), VTy->getVectorKind()); 10786 10787 // For _BitInt, return a signed _BitInt with same width. 10788 if (const auto *EITy = T->getAs<BitIntType>()) 10789 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits()); 10790 10791 // For enums, get the underlying integer type of the enum, and let the general 10792 // integer type signchanging code handle it. 10793 if (const auto *ETy = T->getAs<EnumType>()) 10794 T = ETy->getDecl()->getIntegerType(); 10795 10796 switch (T->castAs<BuiltinType>()->getKind()) { 10797 case BuiltinType::Char_U: 10798 case BuiltinType::UChar: 10799 return SignedCharTy; 10800 case BuiltinType::UShort: 10801 return ShortTy; 10802 case BuiltinType::UInt: 10803 return IntTy; 10804 case BuiltinType::ULong: 10805 return LongTy; 10806 case BuiltinType::ULongLong: 10807 return LongLongTy; 10808 case BuiltinType::UInt128: 10809 return Int128Ty; 10810 // wchar_t is special. It is either unsigned or not, but when it's unsigned, 10811 // there's no matching "signed wchar_t". Therefore we return the signed 10812 // version of it's underlying type instead. 10813 case BuiltinType::WChar_U: 10814 return getSignedWCharType(); 10815 10816 case BuiltinType::UShortAccum: 10817 return ShortAccumTy; 10818 case BuiltinType::UAccum: 10819 return AccumTy; 10820 case BuiltinType::ULongAccum: 10821 return LongAccumTy; 10822 case BuiltinType::SatUShortAccum: 10823 return SatShortAccumTy; 10824 case BuiltinType::SatUAccum: 10825 return SatAccumTy; 10826 case BuiltinType::SatULongAccum: 10827 return SatLongAccumTy; 10828 case BuiltinType::UShortFract: 10829 return ShortFractTy; 10830 case BuiltinType::UFract: 10831 return FractTy; 10832 case BuiltinType::ULongFract: 10833 return LongFractTy; 10834 case BuiltinType::SatUShortFract: 10835 return SatShortFractTy; 10836 case BuiltinType::SatUFract: 10837 return SatFractTy; 10838 case BuiltinType::SatULongFract: 10839 return SatLongFractTy; 10840 default: 10841 llvm_unreachable("Unexpected unsigned integer or fixed point type"); 10842 } 10843 } 10844 10845 ASTMutationListener::~ASTMutationListener() = default; 10846 10847 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD, 10848 QualType ReturnType) {} 10849 10850 //===----------------------------------------------------------------------===// 10851 // Builtin Type Computation 10852 //===----------------------------------------------------------------------===// 10853 10854 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the 10855 /// pointer over the consumed characters. This returns the resultant type. If 10856 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic 10857 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of 10858 /// a vector of "i*". 10859 /// 10860 /// RequiresICE is filled in on return to indicate whether the value is required 10861 /// to be an Integer Constant Expression. 10862 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, 10863 ASTContext::GetBuiltinTypeError &Error, 10864 bool &RequiresICE, 10865 bool AllowTypeModifiers) { 10866 // Modifiers. 10867 int HowLong = 0; 10868 bool Signed = false, Unsigned = false; 10869 RequiresICE = false; 10870 10871 // Read the prefixed modifiers first. 10872 bool Done = false; 10873 #ifndef NDEBUG 10874 bool IsSpecial = false; 10875 #endif 10876 while (!Done) { 10877 switch (*Str++) { 10878 default: Done = true; --Str; break; 10879 case 'I': 10880 RequiresICE = true; 10881 break; 10882 case 'S': 10883 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!"); 10884 assert(!Signed && "Can't use 'S' modifier multiple times!"); 10885 Signed = true; 10886 break; 10887 case 'U': 10888 assert(!Signed && "Can't use both 'S' and 'U' modifiers!"); 10889 assert(!Unsigned && "Can't use 'U' modifier multiple times!"); 10890 Unsigned = true; 10891 break; 10892 case 'L': 10893 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers"); 10894 assert(HowLong <= 2 && "Can't have LLLL modifier"); 10895 ++HowLong; 10896 break; 10897 case 'N': 10898 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise. 10899 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10900 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!"); 10901 #ifndef NDEBUG 10902 IsSpecial = true; 10903 #endif 10904 if (Context.getTargetInfo().getLongWidth() == 32) 10905 ++HowLong; 10906 break; 10907 case 'W': 10908 // This modifier represents int64 type. 10909 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10910 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!"); 10911 #ifndef NDEBUG 10912 IsSpecial = true; 10913 #endif 10914 switch (Context.getTargetInfo().getInt64Type()) { 10915 default: 10916 llvm_unreachable("Unexpected integer type"); 10917 case TargetInfo::SignedLong: 10918 HowLong = 1; 10919 break; 10920 case TargetInfo::SignedLongLong: 10921 HowLong = 2; 10922 break; 10923 } 10924 break; 10925 case 'Z': 10926 // This modifier represents int32 type. 10927 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10928 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!"); 10929 #ifndef NDEBUG 10930 IsSpecial = true; 10931 #endif 10932 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) { 10933 default: 10934 llvm_unreachable("Unexpected integer type"); 10935 case TargetInfo::SignedInt: 10936 HowLong = 0; 10937 break; 10938 case TargetInfo::SignedLong: 10939 HowLong = 1; 10940 break; 10941 case TargetInfo::SignedLongLong: 10942 HowLong = 2; 10943 break; 10944 } 10945 break; 10946 case 'O': 10947 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10948 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!"); 10949 #ifndef NDEBUG 10950 IsSpecial = true; 10951 #endif 10952 if (Context.getLangOpts().OpenCL) 10953 HowLong = 1; 10954 else 10955 HowLong = 2; 10956 break; 10957 } 10958 } 10959 10960 QualType Type; 10961 10962 // Read the base type. 10963 switch (*Str++) { 10964 default: llvm_unreachable("Unknown builtin type letter!"); 10965 case 'x': 10966 assert(HowLong == 0 && !Signed && !Unsigned && 10967 "Bad modifiers used with 'x'!"); 10968 Type = Context.Float16Ty; 10969 break; 10970 case 'y': 10971 assert(HowLong == 0 && !Signed && !Unsigned && 10972 "Bad modifiers used with 'y'!"); 10973 Type = Context.BFloat16Ty; 10974 break; 10975 case 'v': 10976 assert(HowLong == 0 && !Signed && !Unsigned && 10977 "Bad modifiers used with 'v'!"); 10978 Type = Context.VoidTy; 10979 break; 10980 case 'h': 10981 assert(HowLong == 0 && !Signed && !Unsigned && 10982 "Bad modifiers used with 'h'!"); 10983 Type = Context.HalfTy; 10984 break; 10985 case 'f': 10986 assert(HowLong == 0 && !Signed && !Unsigned && 10987 "Bad modifiers used with 'f'!"); 10988 Type = Context.FloatTy; 10989 break; 10990 case 'd': 10991 assert(HowLong < 3 && !Signed && !Unsigned && 10992 "Bad modifiers used with 'd'!"); 10993 if (HowLong == 1) 10994 Type = Context.LongDoubleTy; 10995 else if (HowLong == 2) 10996 Type = Context.Float128Ty; 10997 else 10998 Type = Context.DoubleTy; 10999 break; 11000 case 's': 11001 assert(HowLong == 0 && "Bad modifiers used with 's'!"); 11002 if (Unsigned) 11003 Type = Context.UnsignedShortTy; 11004 else 11005 Type = Context.ShortTy; 11006 break; 11007 case 'i': 11008 if (HowLong == 3) 11009 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty; 11010 else if (HowLong == 2) 11011 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy; 11012 else if (HowLong == 1) 11013 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy; 11014 else 11015 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy; 11016 break; 11017 case 'c': 11018 assert(HowLong == 0 && "Bad modifiers used with 'c'!"); 11019 if (Signed) 11020 Type = Context.SignedCharTy; 11021 else if (Unsigned) 11022 Type = Context.UnsignedCharTy; 11023 else 11024 Type = Context.CharTy; 11025 break; 11026 case 'b': // boolean 11027 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!"); 11028 Type = Context.BoolTy; 11029 break; 11030 case 'z': // size_t. 11031 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!"); 11032 Type = Context.getSizeType(); 11033 break; 11034 case 'w': // wchar_t. 11035 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!"); 11036 Type = Context.getWideCharType(); 11037 break; 11038 case 'F': 11039 Type = Context.getCFConstantStringType(); 11040 break; 11041 case 'G': 11042 Type = Context.getObjCIdType(); 11043 break; 11044 case 'H': 11045 Type = Context.getObjCSelType(); 11046 break; 11047 case 'M': 11048 Type = Context.getObjCSuperType(); 11049 break; 11050 case 'a': 11051 Type = Context.getBuiltinVaListType(); 11052 assert(!Type.isNull() && "builtin va list type not initialized!"); 11053 break; 11054 case 'A': 11055 // This is a "reference" to a va_list; however, what exactly 11056 // this means depends on how va_list is defined. There are two 11057 // different kinds of va_list: ones passed by value, and ones 11058 // passed by reference. An example of a by-value va_list is 11059 // x86, where va_list is a char*. An example of by-ref va_list 11060 // is x86-64, where va_list is a __va_list_tag[1]. For x86, 11061 // we want this argument to be a char*&; for x86-64, we want 11062 // it to be a __va_list_tag*. 11063 Type = Context.getBuiltinVaListType(); 11064 assert(!Type.isNull() && "builtin va list type not initialized!"); 11065 if (Type->isArrayType()) 11066 Type = Context.getArrayDecayedType(Type); 11067 else 11068 Type = Context.getLValueReferenceType(Type); 11069 break; 11070 case 'q': { 11071 char *End; 11072 unsigned NumElements = strtoul(Str, &End, 10); 11073 assert(End != Str && "Missing vector size"); 11074 Str = End; 11075 11076 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 11077 RequiresICE, false); 11078 assert(!RequiresICE && "Can't require vector ICE"); 11079 11080 Type = Context.getScalableVectorType(ElementType, NumElements); 11081 break; 11082 } 11083 case 'V': { 11084 char *End; 11085 unsigned NumElements = strtoul(Str, &End, 10); 11086 assert(End != Str && "Missing vector size"); 11087 Str = End; 11088 11089 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 11090 RequiresICE, false); 11091 assert(!RequiresICE && "Can't require vector ICE"); 11092 11093 // TODO: No way to make AltiVec vectors in builtins yet. 11094 Type = Context.getVectorType(ElementType, NumElements, 11095 VectorType::GenericVector); 11096 break; 11097 } 11098 case 'E': { 11099 char *End; 11100 11101 unsigned NumElements = strtoul(Str, &End, 10); 11102 assert(End != Str && "Missing vector size"); 11103 11104 Str = End; 11105 11106 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 11107 false); 11108 Type = Context.getExtVectorType(ElementType, NumElements); 11109 break; 11110 } 11111 case 'X': { 11112 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 11113 false); 11114 assert(!RequiresICE && "Can't require complex ICE"); 11115 Type = Context.getComplexType(ElementType); 11116 break; 11117 } 11118 case 'Y': 11119 Type = Context.getPointerDiffType(); 11120 break; 11121 case 'P': 11122 Type = Context.getFILEType(); 11123 if (Type.isNull()) { 11124 Error = ASTContext::GE_Missing_stdio; 11125 return {}; 11126 } 11127 break; 11128 case 'J': 11129 if (Signed) 11130 Type = Context.getsigjmp_bufType(); 11131 else 11132 Type = Context.getjmp_bufType(); 11133 11134 if (Type.isNull()) { 11135 Error = ASTContext::GE_Missing_setjmp; 11136 return {}; 11137 } 11138 break; 11139 case 'K': 11140 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!"); 11141 Type = Context.getucontext_tType(); 11142 11143 if (Type.isNull()) { 11144 Error = ASTContext::GE_Missing_ucontext; 11145 return {}; 11146 } 11147 break; 11148 case 'p': 11149 Type = Context.getProcessIDType(); 11150 break; 11151 } 11152 11153 // If there are modifiers and if we're allowed to parse them, go for it. 11154 Done = !AllowTypeModifiers; 11155 while (!Done) { 11156 switch (char c = *Str++) { 11157 default: Done = true; --Str; break; 11158 case '*': 11159 case '&': { 11160 // Both pointers and references can have their pointee types 11161 // qualified with an address space. 11162 char *End; 11163 unsigned AddrSpace = strtoul(Str, &End, 10); 11164 if (End != Str) { 11165 // Note AddrSpace == 0 is not the same as an unspecified address space. 11166 Type = Context.getAddrSpaceQualType( 11167 Type, 11168 Context.getLangASForBuiltinAddressSpace(AddrSpace)); 11169 Str = End; 11170 } 11171 if (c == '*') 11172 Type = Context.getPointerType(Type); 11173 else 11174 Type = Context.getLValueReferenceType(Type); 11175 break; 11176 } 11177 // FIXME: There's no way to have a built-in with an rvalue ref arg. 11178 case 'C': 11179 Type = Type.withConst(); 11180 break; 11181 case 'D': 11182 Type = Context.getVolatileType(Type); 11183 break; 11184 case 'R': 11185 Type = Type.withRestrict(); 11186 break; 11187 } 11188 } 11189 11190 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) && 11191 "Integer constant 'I' type must be an integer"); 11192 11193 return Type; 11194 } 11195 11196 // On some targets such as PowerPC, some of the builtins are defined with custom 11197 // type descriptors for target-dependent types. These descriptors are decoded in 11198 // other functions, but it may be useful to be able to fall back to default 11199 // descriptor decoding to define builtins mixing target-dependent and target- 11200 // independent types. This function allows decoding one type descriptor with 11201 // default decoding. 11202 QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context, 11203 GetBuiltinTypeError &Error, bool &RequireICE, 11204 bool AllowTypeModifiers) const { 11205 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers); 11206 } 11207 11208 /// GetBuiltinType - Return the type for the specified builtin. 11209 QualType ASTContext::GetBuiltinType(unsigned Id, 11210 GetBuiltinTypeError &Error, 11211 unsigned *IntegerConstantArgs) const { 11212 const char *TypeStr = BuiltinInfo.getTypeString(Id); 11213 if (TypeStr[0] == '\0') { 11214 Error = GE_Missing_type; 11215 return {}; 11216 } 11217 11218 SmallVector<QualType, 8> ArgTypes; 11219 11220 bool RequiresICE = false; 11221 Error = GE_None; 11222 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error, 11223 RequiresICE, true); 11224 if (Error != GE_None) 11225 return {}; 11226 11227 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE"); 11228 11229 while (TypeStr[0] && TypeStr[0] != '.') { 11230 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true); 11231 if (Error != GE_None) 11232 return {}; 11233 11234 // If this argument is required to be an IntegerConstantExpression and the 11235 // caller cares, fill in the bitmask we return. 11236 if (RequiresICE && IntegerConstantArgs) 11237 *IntegerConstantArgs |= 1 << ArgTypes.size(); 11238 11239 // Do array -> pointer decay. The builtin should use the decayed type. 11240 if (Ty->isArrayType()) 11241 Ty = getArrayDecayedType(Ty); 11242 11243 ArgTypes.push_back(Ty); 11244 } 11245 11246 if (Id == Builtin::BI__GetExceptionInfo) 11247 return {}; 11248 11249 assert((TypeStr[0] != '.' || TypeStr[1] == 0) && 11250 "'.' should only occur at end of builtin type list!"); 11251 11252 bool Variadic = (TypeStr[0] == '.'); 11253 11254 FunctionType::ExtInfo EI(getDefaultCallingConvention( 11255 Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true)); 11256 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true); 11257 11258 11259 // We really shouldn't be making a no-proto type here. 11260 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes()) 11261 return getFunctionNoProtoType(ResType, EI); 11262 11263 FunctionProtoType::ExtProtoInfo EPI; 11264 EPI.ExtInfo = EI; 11265 EPI.Variadic = Variadic; 11266 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id)) 11267 EPI.ExceptionSpec.Type = 11268 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone; 11269 11270 return getFunctionType(ResType, ArgTypes, EPI); 11271 } 11272 11273 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, 11274 const FunctionDecl *FD) { 11275 if (!FD->isExternallyVisible()) 11276 return GVA_Internal; 11277 11278 // Non-user-provided functions get emitted as weak definitions with every 11279 // use, no matter whether they've been explicitly instantiated etc. 11280 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 11281 if (!MD->isUserProvided()) 11282 return GVA_DiscardableODR; 11283 11284 GVALinkage External; 11285 switch (FD->getTemplateSpecializationKind()) { 11286 case TSK_Undeclared: 11287 case TSK_ExplicitSpecialization: 11288 External = GVA_StrongExternal; 11289 break; 11290 11291 case TSK_ExplicitInstantiationDefinition: 11292 return GVA_StrongODR; 11293 11294 // C++11 [temp.explicit]p10: 11295 // [ Note: The intent is that an inline function that is the subject of 11296 // an explicit instantiation declaration will still be implicitly 11297 // instantiated when used so that the body can be considered for 11298 // inlining, but that no out-of-line copy of the inline function would be 11299 // generated in the translation unit. -- end note ] 11300 case TSK_ExplicitInstantiationDeclaration: 11301 return GVA_AvailableExternally; 11302 11303 case TSK_ImplicitInstantiation: 11304 External = GVA_DiscardableODR; 11305 break; 11306 } 11307 11308 if (!FD->isInlined()) 11309 return External; 11310 11311 if ((!Context.getLangOpts().CPlusPlus && 11312 !Context.getTargetInfo().getCXXABI().isMicrosoft() && 11313 !FD->hasAttr<DLLExportAttr>()) || 11314 FD->hasAttr<GNUInlineAttr>()) { 11315 // FIXME: This doesn't match gcc's behavior for dllexport inline functions. 11316 11317 // GNU or C99 inline semantics. Determine whether this symbol should be 11318 // externally visible. 11319 if (FD->isInlineDefinitionExternallyVisible()) 11320 return External; 11321 11322 // C99 inline semantics, where the symbol is not externally visible. 11323 return GVA_AvailableExternally; 11324 } 11325 11326 // Functions specified with extern and inline in -fms-compatibility mode 11327 // forcibly get emitted. While the body of the function cannot be later 11328 // replaced, the function definition cannot be discarded. 11329 if (FD->isMSExternInline()) 11330 return GVA_StrongODR; 11331 11332 return GVA_DiscardableODR; 11333 } 11334 11335 static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context, 11336 const Decl *D, GVALinkage L) { 11337 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx 11338 // dllexport/dllimport on inline functions. 11339 if (D->hasAttr<DLLImportAttr>()) { 11340 if (L == GVA_DiscardableODR || L == GVA_StrongODR) 11341 return GVA_AvailableExternally; 11342 } else if (D->hasAttr<DLLExportAttr>()) { 11343 if (L == GVA_DiscardableODR) 11344 return GVA_StrongODR; 11345 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) { 11346 // Device-side functions with __global__ attribute must always be 11347 // visible externally so they can be launched from host. 11348 if (D->hasAttr<CUDAGlobalAttr>() && 11349 (L == GVA_DiscardableODR || L == GVA_Internal)) 11350 return GVA_StrongODR; 11351 // Single source offloading languages like CUDA/HIP need to be able to 11352 // access static device variables from host code of the same compilation 11353 // unit. This is done by externalizing the static variable with a shared 11354 // name between the host and device compilation which is the same for the 11355 // same compilation unit whereas different among different compilation 11356 // units. 11357 if (Context.shouldExternalize(D)) 11358 return GVA_StrongExternal; 11359 } 11360 return L; 11361 } 11362 11363 /// Adjust the GVALinkage for a declaration based on what an external AST source 11364 /// knows about whether there can be other definitions of this declaration. 11365 static GVALinkage 11366 adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D, 11367 GVALinkage L) { 11368 ExternalASTSource *Source = Ctx.getExternalSource(); 11369 if (!Source) 11370 return L; 11371 11372 switch (Source->hasExternalDefinitions(D)) { 11373 case ExternalASTSource::EK_Never: 11374 // Other translation units rely on us to provide the definition. 11375 if (L == GVA_DiscardableODR) 11376 return GVA_StrongODR; 11377 break; 11378 11379 case ExternalASTSource::EK_Always: 11380 return GVA_AvailableExternally; 11381 11382 case ExternalASTSource::EK_ReplyHazy: 11383 break; 11384 } 11385 return L; 11386 } 11387 11388 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const { 11389 return adjustGVALinkageForExternalDefinitionKind(*this, FD, 11390 adjustGVALinkageForAttributes(*this, FD, 11391 basicGVALinkageForFunction(*this, FD))); 11392 } 11393 11394 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context, 11395 const VarDecl *VD) { 11396 if (!VD->isExternallyVisible()) 11397 return GVA_Internal; 11398 11399 if (VD->isStaticLocal()) { 11400 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod(); 11401 while (LexicalContext && !isa<FunctionDecl>(LexicalContext)) 11402 LexicalContext = LexicalContext->getLexicalParent(); 11403 11404 // ObjC Blocks can create local variables that don't have a FunctionDecl 11405 // LexicalContext. 11406 if (!LexicalContext) 11407 return GVA_DiscardableODR; 11408 11409 // Otherwise, let the static local variable inherit its linkage from the 11410 // nearest enclosing function. 11411 auto StaticLocalLinkage = 11412 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext)); 11413 11414 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must 11415 // be emitted in any object with references to the symbol for the object it 11416 // contains, whether inline or out-of-line." 11417 // Similar behavior is observed with MSVC. An alternative ABI could use 11418 // StrongODR/AvailableExternally to match the function, but none are 11419 // known/supported currently. 11420 if (StaticLocalLinkage == GVA_StrongODR || 11421 StaticLocalLinkage == GVA_AvailableExternally) 11422 return GVA_DiscardableODR; 11423 return StaticLocalLinkage; 11424 } 11425 11426 // MSVC treats in-class initialized static data members as definitions. 11427 // By giving them non-strong linkage, out-of-line definitions won't 11428 // cause link errors. 11429 if (Context.isMSStaticDataMemberInlineDefinition(VD)) 11430 return GVA_DiscardableODR; 11431 11432 // Most non-template variables have strong linkage; inline variables are 11433 // linkonce_odr or (occasionally, for compatibility) weak_odr. 11434 GVALinkage StrongLinkage; 11435 switch (Context.getInlineVariableDefinitionKind(VD)) { 11436 case ASTContext::InlineVariableDefinitionKind::None: 11437 StrongLinkage = GVA_StrongExternal; 11438 break; 11439 case ASTContext::InlineVariableDefinitionKind::Weak: 11440 case ASTContext::InlineVariableDefinitionKind::WeakUnknown: 11441 StrongLinkage = GVA_DiscardableODR; 11442 break; 11443 case ASTContext::InlineVariableDefinitionKind::Strong: 11444 StrongLinkage = GVA_StrongODR; 11445 break; 11446 } 11447 11448 switch (VD->getTemplateSpecializationKind()) { 11449 case TSK_Undeclared: 11450 return StrongLinkage; 11451 11452 case TSK_ExplicitSpecialization: 11453 return Context.getTargetInfo().getCXXABI().isMicrosoft() && 11454 VD->isStaticDataMember() 11455 ? GVA_StrongODR 11456 : StrongLinkage; 11457 11458 case TSK_ExplicitInstantiationDefinition: 11459 return GVA_StrongODR; 11460 11461 case TSK_ExplicitInstantiationDeclaration: 11462 return GVA_AvailableExternally; 11463 11464 case TSK_ImplicitInstantiation: 11465 return GVA_DiscardableODR; 11466 } 11467 11468 llvm_unreachable("Invalid Linkage!"); 11469 } 11470 11471 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) { 11472 return adjustGVALinkageForExternalDefinitionKind(*this, VD, 11473 adjustGVALinkageForAttributes(*this, VD, 11474 basicGVALinkageForVariable(*this, VD))); 11475 } 11476 11477 bool ASTContext::DeclMustBeEmitted(const Decl *D) { 11478 if (const auto *VD = dyn_cast<VarDecl>(D)) { 11479 if (!VD->isFileVarDecl()) 11480 return false; 11481 // Global named register variables (GNU extension) are never emitted. 11482 if (VD->getStorageClass() == SC_Register) 11483 return false; 11484 if (VD->getDescribedVarTemplate() || 11485 isa<VarTemplatePartialSpecializationDecl>(VD)) 11486 return false; 11487 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 11488 // We never need to emit an uninstantiated function template. 11489 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 11490 return false; 11491 } else if (isa<PragmaCommentDecl>(D)) 11492 return true; 11493 else if (isa<PragmaDetectMismatchDecl>(D)) 11494 return true; 11495 else if (isa<OMPRequiresDecl>(D)) 11496 return true; 11497 else if (isa<OMPThreadPrivateDecl>(D)) 11498 return !D->getDeclContext()->isDependentContext(); 11499 else if (isa<OMPAllocateDecl>(D)) 11500 return !D->getDeclContext()->isDependentContext(); 11501 else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D)) 11502 return !D->getDeclContext()->isDependentContext(); 11503 else if (isa<ImportDecl>(D)) 11504 return true; 11505 else 11506 return false; 11507 11508 // If this is a member of a class template, we do not need to emit it. 11509 if (D->getDeclContext()->isDependentContext()) 11510 return false; 11511 11512 // Weak references don't produce any output by themselves. 11513 if (D->hasAttr<WeakRefAttr>()) 11514 return false; 11515 11516 // Aliases and used decls are required. 11517 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>()) 11518 return true; 11519 11520 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 11521 // Forward declarations aren't required. 11522 if (!FD->doesThisDeclarationHaveABody()) 11523 return FD->doesDeclarationForceExternallyVisibleDefinition(); 11524 11525 // Constructors and destructors are required. 11526 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>()) 11527 return true; 11528 11529 // The key function for a class is required. This rule only comes 11530 // into play when inline functions can be key functions, though. 11531 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 11532 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 11533 const CXXRecordDecl *RD = MD->getParent(); 11534 if (MD->isOutOfLine() && RD->isDynamicClass()) { 11535 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD); 11536 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl()) 11537 return true; 11538 } 11539 } 11540 } 11541 11542 GVALinkage Linkage = GetGVALinkageForFunction(FD); 11543 11544 // static, static inline, always_inline, and extern inline functions can 11545 // always be deferred. Normal inline functions can be deferred in C99/C++. 11546 // Implicit template instantiations can also be deferred in C++. 11547 return !isDiscardableGVALinkage(Linkage); 11548 } 11549 11550 const auto *VD = cast<VarDecl>(D); 11551 assert(VD->isFileVarDecl() && "Expected file scoped var"); 11552 11553 // If the decl is marked as `declare target to`, it should be emitted for the 11554 // host and for the device. 11555 if (LangOpts.OpenMP && 11556 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 11557 return true; 11558 11559 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly && 11560 !isMSStaticDataMemberInlineDefinition(VD)) 11561 return false; 11562 11563 // Variables that can be needed in other TUs are required. 11564 auto Linkage = GetGVALinkageForVariable(VD); 11565 if (!isDiscardableGVALinkage(Linkage)) 11566 return true; 11567 11568 // We never need to emit a variable that is available in another TU. 11569 if (Linkage == GVA_AvailableExternally) 11570 return false; 11571 11572 // Variables that have destruction with side-effects are required. 11573 if (VD->needsDestruction(*this)) 11574 return true; 11575 11576 // Variables that have initialization with side-effects are required. 11577 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) && 11578 // We can get a value-dependent initializer during error recovery. 11579 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 11580 return true; 11581 11582 // Likewise, variables with tuple-like bindings are required if their 11583 // bindings have side-effects. 11584 if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) 11585 for (const auto *BD : DD->bindings()) 11586 if (const auto *BindingVD = BD->getHoldingVar()) 11587 if (DeclMustBeEmitted(BindingVD)) 11588 return true; 11589 11590 return false; 11591 } 11592 11593 void ASTContext::forEachMultiversionedFunctionVersion( 11594 const FunctionDecl *FD, 11595 llvm::function_ref<void(FunctionDecl *)> Pred) const { 11596 assert(FD->isMultiVersion() && "Only valid for multiversioned functions"); 11597 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls; 11598 FD = FD->getMostRecentDecl(); 11599 // FIXME: The order of traversal here matters and depends on the order of 11600 // lookup results, which happens to be (mostly) oldest-to-newest, but we 11601 // shouldn't rely on that. 11602 for (auto *CurDecl : 11603 FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) { 11604 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl(); 11605 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) && 11606 std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) { 11607 SeenDecls.insert(CurFD); 11608 Pred(CurFD); 11609 } 11610 } 11611 } 11612 11613 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic, 11614 bool IsCXXMethod, 11615 bool IsBuiltin) const { 11616 // Pass through to the C++ ABI object 11617 if (IsCXXMethod) 11618 return ABI->getDefaultMethodCallConv(IsVariadic); 11619 11620 // Builtins ignore user-specified default calling convention and remain the 11621 // Target's default calling convention. 11622 if (!IsBuiltin) { 11623 switch (LangOpts.getDefaultCallingConv()) { 11624 case LangOptions::DCC_None: 11625 break; 11626 case LangOptions::DCC_CDecl: 11627 return CC_C; 11628 case LangOptions::DCC_FastCall: 11629 if (getTargetInfo().hasFeature("sse2") && !IsVariadic) 11630 return CC_X86FastCall; 11631 break; 11632 case LangOptions::DCC_StdCall: 11633 if (!IsVariadic) 11634 return CC_X86StdCall; 11635 break; 11636 case LangOptions::DCC_VectorCall: 11637 // __vectorcall cannot be applied to variadic functions. 11638 if (!IsVariadic) 11639 return CC_X86VectorCall; 11640 break; 11641 case LangOptions::DCC_RegCall: 11642 // __regcall cannot be applied to variadic functions. 11643 if (!IsVariadic) 11644 return CC_X86RegCall; 11645 break; 11646 } 11647 } 11648 return Target->getDefaultCallingConv(); 11649 } 11650 11651 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const { 11652 // Pass through to the C++ ABI object 11653 return ABI->isNearlyEmpty(RD); 11654 } 11655 11656 VTableContextBase *ASTContext::getVTableContext() { 11657 if (!VTContext.get()) { 11658 auto ABI = Target->getCXXABI(); 11659 if (ABI.isMicrosoft()) 11660 VTContext.reset(new MicrosoftVTableContext(*this)); 11661 else { 11662 auto ComponentLayout = getLangOpts().RelativeCXXABIVTables 11663 ? ItaniumVTableContext::Relative 11664 : ItaniumVTableContext::Pointer; 11665 VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout)); 11666 } 11667 } 11668 return VTContext.get(); 11669 } 11670 11671 MangleContext *ASTContext::createMangleContext(const TargetInfo *T) { 11672 if (!T) 11673 T = Target; 11674 switch (T->getCXXABI().getKind()) { 11675 case TargetCXXABI::AppleARM64: 11676 case TargetCXXABI::Fuchsia: 11677 case TargetCXXABI::GenericAArch64: 11678 case TargetCXXABI::GenericItanium: 11679 case TargetCXXABI::GenericARM: 11680 case TargetCXXABI::GenericMIPS: 11681 case TargetCXXABI::iOS: 11682 case TargetCXXABI::WebAssembly: 11683 case TargetCXXABI::WatchOS: 11684 case TargetCXXABI::XL: 11685 return ItaniumMangleContext::create(*this, getDiagnostics()); 11686 case TargetCXXABI::Microsoft: 11687 return MicrosoftMangleContext::create(*this, getDiagnostics()); 11688 } 11689 llvm_unreachable("Unsupported ABI"); 11690 } 11691 11692 MangleContext *ASTContext::createDeviceMangleContext(const TargetInfo &T) { 11693 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft && 11694 "Device mangle context does not support Microsoft mangling."); 11695 switch (T.getCXXABI().getKind()) { 11696 case TargetCXXABI::AppleARM64: 11697 case TargetCXXABI::Fuchsia: 11698 case TargetCXXABI::GenericAArch64: 11699 case TargetCXXABI::GenericItanium: 11700 case TargetCXXABI::GenericARM: 11701 case TargetCXXABI::GenericMIPS: 11702 case TargetCXXABI::iOS: 11703 case TargetCXXABI::WebAssembly: 11704 case TargetCXXABI::WatchOS: 11705 case TargetCXXABI::XL: 11706 return ItaniumMangleContext::create( 11707 *this, getDiagnostics(), 11708 [](ASTContext &, const NamedDecl *ND) -> llvm::Optional<unsigned> { 11709 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) 11710 return RD->getDeviceLambdaManglingNumber(); 11711 return llvm::None; 11712 }, 11713 /*IsAux=*/true); 11714 case TargetCXXABI::Microsoft: 11715 return MicrosoftMangleContext::create(*this, getDiagnostics(), 11716 /*IsAux=*/true); 11717 } 11718 llvm_unreachable("Unsupported ABI"); 11719 } 11720 11721 CXXABI::~CXXABI() = default; 11722 11723 size_t ASTContext::getSideTableAllocatedMemory() const { 11724 return ASTRecordLayouts.getMemorySize() + 11725 llvm::capacity_in_bytes(ObjCLayouts) + 11726 llvm::capacity_in_bytes(KeyFunctions) + 11727 llvm::capacity_in_bytes(ObjCImpls) + 11728 llvm::capacity_in_bytes(BlockVarCopyInits) + 11729 llvm::capacity_in_bytes(DeclAttrs) + 11730 llvm::capacity_in_bytes(TemplateOrInstantiation) + 11731 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) + 11732 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) + 11733 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) + 11734 llvm::capacity_in_bytes(OverriddenMethods) + 11735 llvm::capacity_in_bytes(Types) + 11736 llvm::capacity_in_bytes(VariableArrayTypes); 11737 } 11738 11739 /// getIntTypeForBitwidth - 11740 /// sets integer QualTy according to specified details: 11741 /// bitwidth, signed/unsigned. 11742 /// Returns empty type if there is no appropriate target types. 11743 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth, 11744 unsigned Signed) const { 11745 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed); 11746 CanQualType QualTy = getFromTargetType(Ty); 11747 if (!QualTy && DestWidth == 128) 11748 return Signed ? Int128Ty : UnsignedInt128Ty; 11749 return QualTy; 11750 } 11751 11752 /// getRealTypeForBitwidth - 11753 /// sets floating point QualTy according to specified bitwidth. 11754 /// Returns empty type if there is no appropriate target types. 11755 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth, 11756 FloatModeKind ExplicitType) const { 11757 FloatModeKind Ty = 11758 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType); 11759 switch (Ty) { 11760 case FloatModeKind::Half: 11761 return HalfTy; 11762 case FloatModeKind::Float: 11763 return FloatTy; 11764 case FloatModeKind::Double: 11765 return DoubleTy; 11766 case FloatModeKind::LongDouble: 11767 return LongDoubleTy; 11768 case FloatModeKind::Float128: 11769 return Float128Ty; 11770 case FloatModeKind::Ibm128: 11771 return Ibm128Ty; 11772 case FloatModeKind::NoFloat: 11773 return {}; 11774 } 11775 11776 llvm_unreachable("Unhandled TargetInfo::RealType value"); 11777 } 11778 11779 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) { 11780 if (Number > 1) 11781 MangleNumbers[ND] = Number; 11782 } 11783 11784 unsigned ASTContext::getManglingNumber(const NamedDecl *ND, 11785 bool ForAuxTarget) const { 11786 auto I = MangleNumbers.find(ND); 11787 unsigned Res = I != MangleNumbers.end() ? I->second : 1; 11788 // CUDA/HIP host compilation encodes host and device mangling numbers 11789 // as lower and upper half of 32 bit integer. 11790 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) { 11791 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF; 11792 } else { 11793 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling " 11794 "number for aux target"); 11795 } 11796 return Res > 1 ? Res : 1; 11797 } 11798 11799 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) { 11800 if (Number > 1) 11801 StaticLocalNumbers[VD] = Number; 11802 } 11803 11804 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const { 11805 auto I = StaticLocalNumbers.find(VD); 11806 return I != StaticLocalNumbers.end() ? I->second : 1; 11807 } 11808 11809 MangleNumberingContext & 11810 ASTContext::getManglingNumberContext(const DeclContext *DC) { 11811 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C. 11812 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC]; 11813 if (!MCtx) 11814 MCtx = createMangleNumberingContext(); 11815 return *MCtx; 11816 } 11817 11818 MangleNumberingContext & 11819 ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) { 11820 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C. 11821 std::unique_ptr<MangleNumberingContext> &MCtx = 11822 ExtraMangleNumberingContexts[D]; 11823 if (!MCtx) 11824 MCtx = createMangleNumberingContext(); 11825 return *MCtx; 11826 } 11827 11828 std::unique_ptr<MangleNumberingContext> 11829 ASTContext::createMangleNumberingContext() const { 11830 return ABI->createMangleNumberingContext(); 11831 } 11832 11833 const CXXConstructorDecl * 11834 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) { 11835 return ABI->getCopyConstructorForExceptionObject( 11836 cast<CXXRecordDecl>(RD->getFirstDecl())); 11837 } 11838 11839 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD, 11840 CXXConstructorDecl *CD) { 11841 return ABI->addCopyConstructorForExceptionObject( 11842 cast<CXXRecordDecl>(RD->getFirstDecl()), 11843 cast<CXXConstructorDecl>(CD->getFirstDecl())); 11844 } 11845 11846 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD, 11847 TypedefNameDecl *DD) { 11848 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD); 11849 } 11850 11851 TypedefNameDecl * 11852 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) { 11853 return ABI->getTypedefNameForUnnamedTagDecl(TD); 11854 } 11855 11856 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD, 11857 DeclaratorDecl *DD) { 11858 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD); 11859 } 11860 11861 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) { 11862 return ABI->getDeclaratorForUnnamedTagDecl(TD); 11863 } 11864 11865 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) { 11866 ParamIndices[D] = index; 11867 } 11868 11869 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const { 11870 ParameterIndexTable::const_iterator I = ParamIndices.find(D); 11871 assert(I != ParamIndices.end() && 11872 "ParmIndices lacks entry set by ParmVarDecl"); 11873 return I->second; 11874 } 11875 11876 QualType ASTContext::getStringLiteralArrayType(QualType EltTy, 11877 unsigned Length) const { 11878 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 11879 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 11880 EltTy = EltTy.withConst(); 11881 11882 EltTy = adjustStringLiteralBaseType(EltTy); 11883 11884 // Get an array type for the string, according to C99 6.4.5. This includes 11885 // the null terminator character. 11886 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr, 11887 ArrayType::Normal, /*IndexTypeQuals*/ 0); 11888 } 11889 11890 StringLiteral * 11891 ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const { 11892 StringLiteral *&Result = StringLiteralCache[Key]; 11893 if (!Result) 11894 Result = StringLiteral::Create( 11895 *this, Key, StringLiteral::Ascii, 11896 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()), 11897 SourceLocation()); 11898 return Result; 11899 } 11900 11901 MSGuidDecl * 11902 ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const { 11903 assert(MSGuidTagDecl && "building MS GUID without MS extensions?"); 11904 11905 llvm::FoldingSetNodeID ID; 11906 MSGuidDecl::Profile(ID, Parts); 11907 11908 void *InsertPos; 11909 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos)) 11910 return Existing; 11911 11912 QualType GUIDType = getMSGuidType().withConst(); 11913 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts); 11914 MSGuidDecls.InsertNode(New, InsertPos); 11915 return New; 11916 } 11917 11918 UnnamedGlobalConstantDecl * 11919 ASTContext::getUnnamedGlobalConstantDecl(QualType Ty, 11920 const APValue &APVal) const { 11921 llvm::FoldingSetNodeID ID; 11922 UnnamedGlobalConstantDecl::Profile(ID, Ty, APVal); 11923 11924 void *InsertPos; 11925 if (UnnamedGlobalConstantDecl *Existing = 11926 UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos)) 11927 return Existing; 11928 11929 UnnamedGlobalConstantDecl *New = 11930 UnnamedGlobalConstantDecl::Create(*this, Ty, APVal); 11931 UnnamedGlobalConstantDecls.InsertNode(New, InsertPos); 11932 return New; 11933 } 11934 11935 TemplateParamObjectDecl * 11936 ASTContext::getTemplateParamObjectDecl(QualType T, const APValue &V) const { 11937 assert(T->isRecordType() && "template param object of unexpected type"); 11938 11939 // C++ [temp.param]p8: 11940 // [...] a static storage duration object of type 'const T' [...] 11941 T.addConst(); 11942 11943 llvm::FoldingSetNodeID ID; 11944 TemplateParamObjectDecl::Profile(ID, T, V); 11945 11946 void *InsertPos; 11947 if (TemplateParamObjectDecl *Existing = 11948 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos)) 11949 return Existing; 11950 11951 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V); 11952 TemplateParamObjectDecls.InsertNode(New, InsertPos); 11953 return New; 11954 } 11955 11956 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const { 11957 const llvm::Triple &T = getTargetInfo().getTriple(); 11958 if (!T.isOSDarwin()) 11959 return false; 11960 11961 if (!(T.isiOS() && T.isOSVersionLT(7)) && 11962 !(T.isMacOSX() && T.isOSVersionLT(10, 9))) 11963 return false; 11964 11965 QualType AtomicTy = E->getPtr()->getType()->getPointeeType(); 11966 CharUnits sizeChars = getTypeSizeInChars(AtomicTy); 11967 uint64_t Size = sizeChars.getQuantity(); 11968 CharUnits alignChars = getTypeAlignInChars(AtomicTy); 11969 unsigned Align = alignChars.getQuantity(); 11970 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth(); 11971 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits); 11972 } 11973 11974 bool 11975 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, 11976 const ObjCMethodDecl *MethodImpl) { 11977 // No point trying to match an unavailable/deprecated mothod. 11978 if (MethodDecl->hasAttr<UnavailableAttr>() 11979 || MethodDecl->hasAttr<DeprecatedAttr>()) 11980 return false; 11981 if (MethodDecl->getObjCDeclQualifier() != 11982 MethodImpl->getObjCDeclQualifier()) 11983 return false; 11984 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType())) 11985 return false; 11986 11987 if (MethodDecl->param_size() != MethodImpl->param_size()) 11988 return false; 11989 11990 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(), 11991 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(), 11992 EF = MethodDecl->param_end(); 11993 IM != EM && IF != EF; ++IM, ++IF) { 11994 const ParmVarDecl *DeclVar = (*IF); 11995 const ParmVarDecl *ImplVar = (*IM); 11996 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier()) 11997 return false; 11998 if (!hasSameType(DeclVar->getType(), ImplVar->getType())) 11999 return false; 12000 } 12001 12002 return (MethodDecl->isVariadic() == MethodImpl->isVariadic()); 12003 } 12004 12005 uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const { 12006 LangAS AS; 12007 if (QT->getUnqualifiedDesugaredType()->isNullPtrType()) 12008 AS = LangAS::Default; 12009 else 12010 AS = QT->getPointeeType().getAddressSpace(); 12011 12012 return getTargetInfo().getNullPointerValue(AS); 12013 } 12014 12015 unsigned ASTContext::getTargetAddressSpace(QualType T) const { 12016 // Return the address space for the type. If the type is a 12017 // function type without an address space qualifier, the 12018 // program address space is used. Otherwise, the target picks 12019 // the best address space based on the type information 12020 return T->isFunctionType() && !T.hasAddressSpace() 12021 ? getTargetInfo().getProgramAddressSpace() 12022 : getTargetAddressSpace(T.getQualifiers()); 12023 } 12024 12025 unsigned ASTContext::getTargetAddressSpace(Qualifiers Q) const { 12026 return getTargetAddressSpace(Q.getAddressSpace()); 12027 } 12028 12029 unsigned ASTContext::getTargetAddressSpace(LangAS AS) const { 12030 if (isTargetAddressSpace(AS)) 12031 return toTargetAddressSpace(AS); 12032 else 12033 return (*AddrSpaceMap)[(unsigned)AS]; 12034 } 12035 12036 QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const { 12037 assert(Ty->isFixedPointType()); 12038 12039 if (Ty->isSaturatedFixedPointType()) return Ty; 12040 12041 switch (Ty->castAs<BuiltinType>()->getKind()) { 12042 default: 12043 llvm_unreachable("Not a fixed point type!"); 12044 case BuiltinType::ShortAccum: 12045 return SatShortAccumTy; 12046 case BuiltinType::Accum: 12047 return SatAccumTy; 12048 case BuiltinType::LongAccum: 12049 return SatLongAccumTy; 12050 case BuiltinType::UShortAccum: 12051 return SatUnsignedShortAccumTy; 12052 case BuiltinType::UAccum: 12053 return SatUnsignedAccumTy; 12054 case BuiltinType::ULongAccum: 12055 return SatUnsignedLongAccumTy; 12056 case BuiltinType::ShortFract: 12057 return SatShortFractTy; 12058 case BuiltinType::Fract: 12059 return SatFractTy; 12060 case BuiltinType::LongFract: 12061 return SatLongFractTy; 12062 case BuiltinType::UShortFract: 12063 return SatUnsignedShortFractTy; 12064 case BuiltinType::UFract: 12065 return SatUnsignedFractTy; 12066 case BuiltinType::ULongFract: 12067 return SatUnsignedLongFractTy; 12068 } 12069 } 12070 12071 LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const { 12072 if (LangOpts.OpenCL) 12073 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS); 12074 12075 if (LangOpts.CUDA) 12076 return getTargetInfo().getCUDABuiltinAddressSpace(AS); 12077 12078 return getLangASFromTargetAS(AS); 12079 } 12080 12081 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that 12082 // doesn't include ASTContext.h 12083 template 12084 clang::LazyGenerationalUpdatePtr< 12085 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType 12086 clang::LazyGenerationalUpdatePtr< 12087 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue( 12088 const clang::ASTContext &Ctx, Decl *Value); 12089 12090 unsigned char ASTContext::getFixedPointScale(QualType Ty) const { 12091 assert(Ty->isFixedPointType()); 12092 12093 const TargetInfo &Target = getTargetInfo(); 12094 switch (Ty->castAs<BuiltinType>()->getKind()) { 12095 default: 12096 llvm_unreachable("Not a fixed point type!"); 12097 case BuiltinType::ShortAccum: 12098 case BuiltinType::SatShortAccum: 12099 return Target.getShortAccumScale(); 12100 case BuiltinType::Accum: 12101 case BuiltinType::SatAccum: 12102 return Target.getAccumScale(); 12103 case BuiltinType::LongAccum: 12104 case BuiltinType::SatLongAccum: 12105 return Target.getLongAccumScale(); 12106 case BuiltinType::UShortAccum: 12107 case BuiltinType::SatUShortAccum: 12108 return Target.getUnsignedShortAccumScale(); 12109 case BuiltinType::UAccum: 12110 case BuiltinType::SatUAccum: 12111 return Target.getUnsignedAccumScale(); 12112 case BuiltinType::ULongAccum: 12113 case BuiltinType::SatULongAccum: 12114 return Target.getUnsignedLongAccumScale(); 12115 case BuiltinType::ShortFract: 12116 case BuiltinType::SatShortFract: 12117 return Target.getShortFractScale(); 12118 case BuiltinType::Fract: 12119 case BuiltinType::SatFract: 12120 return Target.getFractScale(); 12121 case BuiltinType::LongFract: 12122 case BuiltinType::SatLongFract: 12123 return Target.getLongFractScale(); 12124 case BuiltinType::UShortFract: 12125 case BuiltinType::SatUShortFract: 12126 return Target.getUnsignedShortFractScale(); 12127 case BuiltinType::UFract: 12128 case BuiltinType::SatUFract: 12129 return Target.getUnsignedFractScale(); 12130 case BuiltinType::ULongFract: 12131 case BuiltinType::SatULongFract: 12132 return Target.getUnsignedLongFractScale(); 12133 } 12134 } 12135 12136 unsigned char ASTContext::getFixedPointIBits(QualType Ty) const { 12137 assert(Ty->isFixedPointType()); 12138 12139 const TargetInfo &Target = getTargetInfo(); 12140 switch (Ty->castAs<BuiltinType>()->getKind()) { 12141 default: 12142 llvm_unreachable("Not a fixed point type!"); 12143 case BuiltinType::ShortAccum: 12144 case BuiltinType::SatShortAccum: 12145 return Target.getShortAccumIBits(); 12146 case BuiltinType::Accum: 12147 case BuiltinType::SatAccum: 12148 return Target.getAccumIBits(); 12149 case BuiltinType::LongAccum: 12150 case BuiltinType::SatLongAccum: 12151 return Target.getLongAccumIBits(); 12152 case BuiltinType::UShortAccum: 12153 case BuiltinType::SatUShortAccum: 12154 return Target.getUnsignedShortAccumIBits(); 12155 case BuiltinType::UAccum: 12156 case BuiltinType::SatUAccum: 12157 return Target.getUnsignedAccumIBits(); 12158 case BuiltinType::ULongAccum: 12159 case BuiltinType::SatULongAccum: 12160 return Target.getUnsignedLongAccumIBits(); 12161 case BuiltinType::ShortFract: 12162 case BuiltinType::SatShortFract: 12163 case BuiltinType::Fract: 12164 case BuiltinType::SatFract: 12165 case BuiltinType::LongFract: 12166 case BuiltinType::SatLongFract: 12167 case BuiltinType::UShortFract: 12168 case BuiltinType::SatUShortFract: 12169 case BuiltinType::UFract: 12170 case BuiltinType::SatUFract: 12171 case BuiltinType::ULongFract: 12172 case BuiltinType::SatULongFract: 12173 return 0; 12174 } 12175 } 12176 12177 llvm::FixedPointSemantics 12178 ASTContext::getFixedPointSemantics(QualType Ty) const { 12179 assert((Ty->isFixedPointType() || Ty->isIntegerType()) && 12180 "Can only get the fixed point semantics for a " 12181 "fixed point or integer type."); 12182 if (Ty->isIntegerType()) 12183 return llvm::FixedPointSemantics::GetIntegerSemantics( 12184 getIntWidth(Ty), Ty->isSignedIntegerType()); 12185 12186 bool isSigned = Ty->isSignedFixedPointType(); 12187 return llvm::FixedPointSemantics( 12188 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned, 12189 Ty->isSaturatedFixedPointType(), 12190 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding()); 12191 } 12192 12193 llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const { 12194 assert(Ty->isFixedPointType()); 12195 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty)); 12196 } 12197 12198 llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const { 12199 assert(Ty->isFixedPointType()); 12200 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty)); 12201 } 12202 12203 QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const { 12204 assert(Ty->isUnsignedFixedPointType() && 12205 "Expected unsigned fixed point type"); 12206 12207 switch (Ty->castAs<BuiltinType>()->getKind()) { 12208 case BuiltinType::UShortAccum: 12209 return ShortAccumTy; 12210 case BuiltinType::UAccum: 12211 return AccumTy; 12212 case BuiltinType::ULongAccum: 12213 return LongAccumTy; 12214 case BuiltinType::SatUShortAccum: 12215 return SatShortAccumTy; 12216 case BuiltinType::SatUAccum: 12217 return SatAccumTy; 12218 case BuiltinType::SatULongAccum: 12219 return SatLongAccumTy; 12220 case BuiltinType::UShortFract: 12221 return ShortFractTy; 12222 case BuiltinType::UFract: 12223 return FractTy; 12224 case BuiltinType::ULongFract: 12225 return LongFractTy; 12226 case BuiltinType::SatUShortFract: 12227 return SatShortFractTy; 12228 case BuiltinType::SatUFract: 12229 return SatFractTy; 12230 case BuiltinType::SatULongFract: 12231 return SatLongFractTy; 12232 default: 12233 llvm_unreachable("Unexpected unsigned fixed point type"); 12234 } 12235 } 12236 12237 ParsedTargetAttr 12238 ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const { 12239 assert(TD != nullptr); 12240 ParsedTargetAttr ParsedAttr = TD->parse(); 12241 12242 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) { 12243 return !Target->isValidFeatureName(StringRef{Feat}.substr(1)); 12244 }); 12245 return ParsedAttr; 12246 } 12247 12248 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 12249 const FunctionDecl *FD) const { 12250 if (FD) 12251 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD)); 12252 else 12253 Target->initFeatureMap(FeatureMap, getDiagnostics(), 12254 Target->getTargetOpts().CPU, 12255 Target->getTargetOpts().Features); 12256 } 12257 12258 // Fills in the supplied string map with the set of target features for the 12259 // passed in function. 12260 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 12261 GlobalDecl GD) const { 12262 StringRef TargetCPU = Target->getTargetOpts().CPU; 12263 const FunctionDecl *FD = GD.getDecl()->getAsFunction(); 12264 if (const auto *TD = FD->getAttr<TargetAttr>()) { 12265 ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD); 12266 12267 // Make a copy of the features as passed on the command line into the 12268 // beginning of the additional features from the function to override. 12269 ParsedAttr.Features.insert( 12270 ParsedAttr.Features.begin(), 12271 Target->getTargetOpts().FeaturesAsWritten.begin(), 12272 Target->getTargetOpts().FeaturesAsWritten.end()); 12273 12274 if (ParsedAttr.Architecture != "" && 12275 Target->isValidCPUName(ParsedAttr.Architecture)) 12276 TargetCPU = ParsedAttr.Architecture; 12277 12278 // Now populate the feature map, first with the TargetCPU which is either 12279 // the default or a new one from the target attribute string. Then we'll use 12280 // the passed in features (FeaturesAsWritten) along with the new ones from 12281 // the attribute. 12282 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, 12283 ParsedAttr.Features); 12284 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) { 12285 llvm::SmallVector<StringRef, 32> FeaturesTmp; 12286 Target->getCPUSpecificCPUDispatchFeatures( 12287 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp); 12288 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end()); 12289 Features.insert(Features.begin(), 12290 Target->getTargetOpts().FeaturesAsWritten.begin(), 12291 Target->getTargetOpts().FeaturesAsWritten.end()); 12292 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features); 12293 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) { 12294 std::vector<std::string> Features; 12295 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex()); 12296 if (VersionStr.startswith("arch=")) 12297 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1); 12298 else if (VersionStr != "default") 12299 Features.push_back((StringRef{"+"} + VersionStr).str()); 12300 12301 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features); 12302 } else { 12303 FeatureMap = Target->getTargetOpts().FeatureMap; 12304 } 12305 } 12306 12307 OMPTraitInfo &ASTContext::getNewOMPTraitInfo() { 12308 OMPTraitInfoVector.emplace_back(new OMPTraitInfo()); 12309 return *OMPTraitInfoVector.back(); 12310 } 12311 12312 const StreamingDiagnostic &clang:: 12313 operator<<(const StreamingDiagnostic &DB, 12314 const ASTContext::SectionInfo &Section) { 12315 if (Section.Decl) 12316 return DB << Section.Decl; 12317 return DB << "a prior #pragma section"; 12318 } 12319 12320 bool ASTContext::mayExternalize(const Decl *D) const { 12321 bool IsStaticVar = 12322 isa<VarDecl>(D) && cast<VarDecl>(D)->getStorageClass() == SC_Static; 12323 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() && 12324 !D->getAttr<CUDADeviceAttr>()->isImplicit()) || 12325 (D->hasAttr<CUDAConstantAttr>() && 12326 !D->getAttr<CUDAConstantAttr>()->isImplicit()); 12327 // CUDA/HIP: static managed variables need to be externalized since it is 12328 // a declaration in IR, therefore cannot have internal linkage. Kernels in 12329 // anonymous name space needs to be externalized to avoid duplicate symbols. 12330 return (IsStaticVar && 12331 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) || 12332 (D->hasAttr<CUDAGlobalAttr>() && 12333 basicGVALinkageForFunction(*this, cast<FunctionDecl>(D)) == 12334 GVA_Internal); 12335 } 12336 12337 bool ASTContext::shouldExternalize(const Decl *D) const { 12338 return mayExternalize(D) && 12339 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() || 12340 CUDADeviceVarODRUsedByHost.count(cast<VarDecl>(D))); 12341 } 12342 12343 StringRef ASTContext::getCUIDHash() const { 12344 if (!CUIDHash.empty()) 12345 return CUIDHash; 12346 if (LangOpts.CUID.empty()) 12347 return StringRef(); 12348 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true); 12349 return CUIDHash; 12350 } 12351