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, Float16Rank, HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank 105 }; 106 107 /// \returns location that is relevant when searching for Doc comments related 108 /// to \p D. 109 static SourceLocation getDeclLocForCommentSearch(const Decl *D, 110 SourceManager &SourceMgr) { 111 assert(D); 112 113 // User can not attach documentation to implicit declarations. 114 if (D->isImplicit()) 115 return {}; 116 117 // User can not attach documentation to implicit instantiations. 118 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 119 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 120 return {}; 121 } 122 123 if (const auto *VD = dyn_cast<VarDecl>(D)) { 124 if (VD->isStaticDataMember() && 125 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 126 return {}; 127 } 128 129 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) { 130 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 131 return {}; 132 } 133 134 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) { 135 TemplateSpecializationKind TSK = CTSD->getSpecializationKind(); 136 if (TSK == TSK_ImplicitInstantiation || 137 TSK == TSK_Undeclared) 138 return {}; 139 } 140 141 if (const auto *ED = dyn_cast<EnumDecl>(D)) { 142 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 143 return {}; 144 } 145 if (const auto *TD = dyn_cast<TagDecl>(D)) { 146 // When tag declaration (but not definition!) is part of the 147 // decl-specifier-seq of some other declaration, it doesn't get comment 148 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition()) 149 return {}; 150 } 151 // TODO: handle comments for function parameters properly. 152 if (isa<ParmVarDecl>(D)) 153 return {}; 154 155 // TODO: we could look up template parameter documentation in the template 156 // documentation. 157 if (isa<TemplateTypeParmDecl>(D) || 158 isa<NonTypeTemplateParmDecl>(D) || 159 isa<TemplateTemplateParmDecl>(D)) 160 return {}; 161 162 // Find declaration location. 163 // For Objective-C declarations we generally don't expect to have multiple 164 // declarators, thus use declaration starting location as the "declaration 165 // location". 166 // For all other declarations multiple declarators are used quite frequently, 167 // so we use the location of the identifier as the "declaration location". 168 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) || 169 isa<ObjCPropertyDecl>(D) || 170 isa<RedeclarableTemplateDecl>(D) || 171 isa<ClassTemplateSpecializationDecl>(D) || 172 // Allow association with Y across {} in `typedef struct X {} Y`. 173 isa<TypedefDecl>(D)) 174 return D->getBeginLoc(); 175 else { 176 const SourceLocation DeclLoc = D->getLocation(); 177 if (DeclLoc.isMacroID()) { 178 if (isa<TypedefDecl>(D)) { 179 // If location of the typedef name is in a macro, it is because being 180 // declared via a macro. Try using declaration's starting location as 181 // the "declaration location". 182 return D->getBeginLoc(); 183 } else if (const auto *TD = dyn_cast<TagDecl>(D)) { 184 // If location of the tag decl is inside a macro, but the spelling of 185 // the tag name comes from a macro argument, it looks like a special 186 // macro like NS_ENUM is being used to define the tag decl. In that 187 // case, adjust the source location to the expansion loc so that we can 188 // attach the comment to the tag decl. 189 if (SourceMgr.isMacroArgExpansion(DeclLoc) && 190 TD->isCompleteDefinition()) 191 return SourceMgr.getExpansionLoc(DeclLoc); 192 } 193 } 194 return DeclLoc; 195 } 196 197 return {}; 198 } 199 200 RawComment *ASTContext::getRawCommentForDeclNoCacheImpl( 201 const Decl *D, const SourceLocation RepresentativeLocForDecl, 202 const std::map<unsigned, RawComment *> &CommentsInTheFile) const { 203 // If the declaration doesn't map directly to a location in a file, we 204 // can't find the comment. 205 if (RepresentativeLocForDecl.isInvalid() || 206 !RepresentativeLocForDecl.isFileID()) 207 return nullptr; 208 209 // If there are no comments anywhere, we won't find anything. 210 if (CommentsInTheFile.empty()) 211 return nullptr; 212 213 // Decompose the location for the declaration and find the beginning of the 214 // file buffer. 215 const std::pair<FileID, unsigned> DeclLocDecomp = 216 SourceMgr.getDecomposedLoc(RepresentativeLocForDecl); 217 218 // Slow path. 219 auto OffsetCommentBehindDecl = 220 CommentsInTheFile.lower_bound(DeclLocDecomp.second); 221 222 // First check whether we have a trailing comment. 223 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) { 224 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second; 225 if ((CommentBehindDecl->isDocumentation() || 226 LangOpts.CommentOpts.ParseAllComments) && 227 CommentBehindDecl->isTrailingComment() && 228 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) || 229 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) { 230 231 // Check that Doxygen trailing comment comes after the declaration, starts 232 // on the same line and in the same file as the declaration. 233 if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) == 234 Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first, 235 OffsetCommentBehindDecl->first)) { 236 return CommentBehindDecl; 237 } 238 } 239 } 240 241 // The comment just after the declaration was not a trailing comment. 242 // Let's look at the previous comment. 243 if (OffsetCommentBehindDecl == CommentsInTheFile.begin()) 244 return nullptr; 245 246 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl; 247 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second; 248 249 // Check that we actually have a non-member Doxygen comment. 250 if (!(CommentBeforeDecl->isDocumentation() || 251 LangOpts.CommentOpts.ParseAllComments) || 252 CommentBeforeDecl->isTrailingComment()) 253 return nullptr; 254 255 // Decompose the end of the comment. 256 const unsigned CommentEndOffset = 257 Comments.getCommentEndOffset(CommentBeforeDecl); 258 259 // Get the corresponding buffer. 260 bool Invalid = false; 261 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first, 262 &Invalid).data(); 263 if (Invalid) 264 return nullptr; 265 266 // Extract text between the comment and declaration. 267 StringRef Text(Buffer + CommentEndOffset, 268 DeclLocDecomp.second - CommentEndOffset); 269 270 // There should be no other declarations or preprocessor directives between 271 // comment and declaration. 272 if (Text.find_first_of(";{}#@") != StringRef::npos) 273 return nullptr; 274 275 return CommentBeforeDecl; 276 } 277 278 RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const { 279 const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr); 280 281 // If the declaration doesn't map directly to a location in a file, we 282 // can't find the comment. 283 if (DeclLoc.isInvalid() || !DeclLoc.isFileID()) 284 return nullptr; 285 286 if (ExternalSource && !CommentsLoaded) { 287 ExternalSource->ReadComments(); 288 CommentsLoaded = true; 289 } 290 291 if (Comments.empty()) 292 return nullptr; 293 294 const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first; 295 const auto CommentsInThisFile = Comments.getCommentsInFile(File); 296 if (!CommentsInThisFile || CommentsInThisFile->empty()) 297 return nullptr; 298 299 return getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile); 300 } 301 302 void ASTContext::addComment(const RawComment &RC) { 303 assert(LangOpts.RetainCommentsFromSystemHeaders || 304 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin())); 305 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc); 306 } 307 308 /// If we have a 'templated' declaration for a template, adjust 'D' to 309 /// refer to the actual template. 310 /// If we have an implicit instantiation, adjust 'D' to refer to template. 311 static const Decl &adjustDeclToTemplate(const Decl &D) { 312 if (const auto *FD = dyn_cast<FunctionDecl>(&D)) { 313 // Is this function declaration part of a function template? 314 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 315 return *FTD; 316 317 // Nothing to do if function is not an implicit instantiation. 318 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) 319 return D; 320 321 // Function is an implicit instantiation of a function template? 322 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate()) 323 return *FTD; 324 325 // Function is instantiated from a member definition of a class template? 326 if (const FunctionDecl *MemberDecl = 327 FD->getInstantiatedFromMemberFunction()) 328 return *MemberDecl; 329 330 return D; 331 } 332 if (const auto *VD = dyn_cast<VarDecl>(&D)) { 333 // Static data member is instantiated from a member definition of a class 334 // template? 335 if (VD->isStaticDataMember()) 336 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember()) 337 return *MemberDecl; 338 339 return D; 340 } 341 if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) { 342 // Is this class declaration part of a class template? 343 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate()) 344 return *CTD; 345 346 // Class is an implicit instantiation of a class template or partial 347 // specialization? 348 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) { 349 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation) 350 return D; 351 llvm::PointerUnion<ClassTemplateDecl *, 352 ClassTemplatePartialSpecializationDecl *> 353 PU = CTSD->getSpecializedTemplateOrPartial(); 354 return PU.is<ClassTemplateDecl *>() 355 ? *static_cast<const Decl *>(PU.get<ClassTemplateDecl *>()) 356 : *static_cast<const Decl *>( 357 PU.get<ClassTemplatePartialSpecializationDecl *>()); 358 } 359 360 // Class is instantiated from a member definition of a class template? 361 if (const MemberSpecializationInfo *Info = 362 CRD->getMemberSpecializationInfo()) 363 return *Info->getInstantiatedFrom(); 364 365 return D; 366 } 367 if (const auto *ED = dyn_cast<EnumDecl>(&D)) { 368 // Enum is instantiated from a member definition of a class template? 369 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum()) 370 return *MemberDecl; 371 372 return D; 373 } 374 // FIXME: Adjust alias templates? 375 return D; 376 } 377 378 const RawComment *ASTContext::getRawCommentForAnyRedecl( 379 const Decl *D, 380 const Decl **OriginalDecl) const { 381 if (!D) { 382 if (OriginalDecl) 383 OriginalDecl = nullptr; 384 return nullptr; 385 } 386 387 D = &adjustDeclToTemplate(*D); 388 389 // Any comment directly attached to D? 390 { 391 auto DeclComment = DeclRawComments.find(D); 392 if (DeclComment != DeclRawComments.end()) { 393 if (OriginalDecl) 394 *OriginalDecl = D; 395 return DeclComment->second; 396 } 397 } 398 399 // Any comment attached to any redeclaration of D? 400 const Decl *CanonicalD = D->getCanonicalDecl(); 401 if (!CanonicalD) 402 return nullptr; 403 404 { 405 auto RedeclComment = RedeclChainComments.find(CanonicalD); 406 if (RedeclComment != RedeclChainComments.end()) { 407 if (OriginalDecl) 408 *OriginalDecl = RedeclComment->second; 409 auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second); 410 assert(CommentAtRedecl != DeclRawComments.end() && 411 "This decl is supposed to have comment attached."); 412 return CommentAtRedecl->second; 413 } 414 } 415 416 // Any redeclarations of D that we haven't checked for comments yet? 417 // We can't use DenseMap::iterator directly since it'd get invalid. 418 auto LastCheckedRedecl = [this, CanonicalD]() -> const Decl * { 419 auto LookupRes = CommentlessRedeclChains.find(CanonicalD); 420 if (LookupRes != CommentlessRedeclChains.end()) 421 return LookupRes->second; 422 return nullptr; 423 }(); 424 425 for (const auto Redecl : D->redecls()) { 426 assert(Redecl); 427 // Skip all redeclarations that have been checked previously. 428 if (LastCheckedRedecl) { 429 if (LastCheckedRedecl == Redecl) { 430 LastCheckedRedecl = nullptr; 431 } 432 continue; 433 } 434 const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl); 435 if (RedeclComment) { 436 cacheRawCommentForDecl(*Redecl, *RedeclComment); 437 if (OriginalDecl) 438 *OriginalDecl = Redecl; 439 return RedeclComment; 440 } 441 CommentlessRedeclChains[CanonicalD] = Redecl; 442 } 443 444 if (OriginalDecl) 445 *OriginalDecl = nullptr; 446 return nullptr; 447 } 448 449 void ASTContext::cacheRawCommentForDecl(const Decl &OriginalD, 450 const RawComment &Comment) const { 451 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments); 452 DeclRawComments.try_emplace(&OriginalD, &Comment); 453 const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl(); 454 RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD); 455 CommentlessRedeclChains.erase(CanonicalDecl); 456 } 457 458 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod, 459 SmallVectorImpl<const NamedDecl *> &Redeclared) { 460 const DeclContext *DC = ObjCMethod->getDeclContext(); 461 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) { 462 const ObjCInterfaceDecl *ID = IMD->getClassInterface(); 463 if (!ID) 464 return; 465 // Add redeclared method here. 466 for (const auto *Ext : ID->known_extensions()) { 467 if (ObjCMethodDecl *RedeclaredMethod = 468 Ext->getMethod(ObjCMethod->getSelector(), 469 ObjCMethod->isInstanceMethod())) 470 Redeclared.push_back(RedeclaredMethod); 471 } 472 } 473 } 474 475 void ASTContext::attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls, 476 const Preprocessor *PP) { 477 if (Comments.empty() || Decls.empty()) 478 return; 479 480 FileID File; 481 for (Decl *D : Decls) { 482 SourceLocation Loc = D->getLocation(); 483 if (Loc.isValid()) { 484 // See if there are any new comments that are not attached to a decl. 485 // The location doesn't have to be precise - we care only about the file. 486 File = SourceMgr.getDecomposedLoc(Loc).first; 487 break; 488 } 489 } 490 491 if (File.isInvalid()) 492 return; 493 494 auto CommentsInThisFile = Comments.getCommentsInFile(File); 495 if (!CommentsInThisFile || CommentsInThisFile->empty() || 496 CommentsInThisFile->rbegin()->second->isAttached()) 497 return; 498 499 // There is at least one comment not attached to a decl. 500 // Maybe it should be attached to one of Decls? 501 // 502 // Note that this way we pick up not only comments that precede the 503 // declaration, but also comments that *follow* the declaration -- thanks to 504 // the lookahead in the lexer: we've consumed the semicolon and looked 505 // ahead through comments. 506 507 for (const Decl *D : Decls) { 508 assert(D); 509 if (D->isInvalidDecl()) 510 continue; 511 512 D = &adjustDeclToTemplate(*D); 513 514 const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr); 515 516 if (DeclLoc.isInvalid() || !DeclLoc.isFileID()) 517 continue; 518 519 if (DeclRawComments.count(D) > 0) 520 continue; 521 522 if (RawComment *const DocComment = 523 getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile)) { 524 cacheRawCommentForDecl(*D, *DocComment); 525 comments::FullComment *FC = DocComment->parse(*this, PP, D); 526 ParsedComments[D->getCanonicalDecl()] = FC; 527 } 528 } 529 } 530 531 comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC, 532 const Decl *D) const { 533 auto *ThisDeclInfo = new (*this) comments::DeclInfo; 534 ThisDeclInfo->CommentDecl = D; 535 ThisDeclInfo->IsFilled = false; 536 ThisDeclInfo->fill(); 537 ThisDeclInfo->CommentDecl = FC->getDecl(); 538 if (!ThisDeclInfo->TemplateParameters) 539 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters; 540 comments::FullComment *CFC = 541 new (*this) comments::FullComment(FC->getBlocks(), 542 ThisDeclInfo); 543 return CFC; 544 } 545 546 comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const { 547 const RawComment *RC = getRawCommentForDeclNoCache(D); 548 return RC ? RC->parse(*this, nullptr, D) : nullptr; 549 } 550 551 comments::FullComment *ASTContext::getCommentForDecl( 552 const Decl *D, 553 const Preprocessor *PP) const { 554 if (!D || D->isInvalidDecl()) 555 return nullptr; 556 D = &adjustDeclToTemplate(*D); 557 558 const Decl *Canonical = D->getCanonicalDecl(); 559 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos = 560 ParsedComments.find(Canonical); 561 562 if (Pos != ParsedComments.end()) { 563 if (Canonical != D) { 564 comments::FullComment *FC = Pos->second; 565 comments::FullComment *CFC = cloneFullComment(FC, D); 566 return CFC; 567 } 568 return Pos->second; 569 } 570 571 const Decl *OriginalDecl = nullptr; 572 573 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl); 574 if (!RC) { 575 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) { 576 SmallVector<const NamedDecl*, 8> Overridden; 577 const auto *OMD = dyn_cast<ObjCMethodDecl>(D); 578 if (OMD && OMD->isPropertyAccessor()) 579 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl()) 580 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP)) 581 return cloneFullComment(FC, D); 582 if (OMD) 583 addRedeclaredMethods(OMD, Overridden); 584 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden); 585 for (unsigned i = 0, e = Overridden.size(); i < e; i++) 586 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP)) 587 return cloneFullComment(FC, D); 588 } 589 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) { 590 // Attach any tag type's documentation to its typedef if latter 591 // does not have one of its own. 592 QualType QT = TD->getUnderlyingType(); 593 if (const auto *TT = QT->getAs<TagType>()) 594 if (const Decl *TD = TT->getDecl()) 595 if (comments::FullComment *FC = getCommentForDecl(TD, PP)) 596 return cloneFullComment(FC, D); 597 } 598 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) { 599 while (IC->getSuperClass()) { 600 IC = IC->getSuperClass(); 601 if (comments::FullComment *FC = getCommentForDecl(IC, PP)) 602 return cloneFullComment(FC, D); 603 } 604 } 605 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) { 606 if (const ObjCInterfaceDecl *IC = CD->getClassInterface()) 607 if (comments::FullComment *FC = getCommentForDecl(IC, PP)) 608 return cloneFullComment(FC, D); 609 } 610 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) { 611 if (!(RD = RD->getDefinition())) 612 return nullptr; 613 // Check non-virtual bases. 614 for (const auto &I : RD->bases()) { 615 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public)) 616 continue; 617 QualType Ty = I.getType(); 618 if (Ty.isNull()) 619 continue; 620 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) { 621 if (!(NonVirtualBase= NonVirtualBase->getDefinition())) 622 continue; 623 624 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP)) 625 return cloneFullComment(FC, D); 626 } 627 } 628 // Check virtual bases. 629 for (const auto &I : RD->vbases()) { 630 if (I.getAccessSpecifier() != AS_public) 631 continue; 632 QualType Ty = I.getType(); 633 if (Ty.isNull()) 634 continue; 635 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) { 636 if (!(VirtualBase= VirtualBase->getDefinition())) 637 continue; 638 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP)) 639 return cloneFullComment(FC, D); 640 } 641 } 642 } 643 return nullptr; 644 } 645 646 // If the RawComment was attached to other redeclaration of this Decl, we 647 // should parse the comment in context of that other Decl. This is important 648 // because comments can contain references to parameter names which can be 649 // different across redeclarations. 650 if (D != OriginalDecl && OriginalDecl) 651 return getCommentForDecl(OriginalDecl, PP); 652 653 comments::FullComment *FC = RC->parse(*this, PP, D); 654 ParsedComments[Canonical] = FC; 655 return FC; 656 } 657 658 void 659 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID, 660 const ASTContext &C, 661 TemplateTemplateParmDecl *Parm) { 662 ID.AddInteger(Parm->getDepth()); 663 ID.AddInteger(Parm->getPosition()); 664 ID.AddBoolean(Parm->isParameterPack()); 665 666 TemplateParameterList *Params = Parm->getTemplateParameters(); 667 ID.AddInteger(Params->size()); 668 for (TemplateParameterList::const_iterator P = Params->begin(), 669 PEnd = Params->end(); 670 P != PEnd; ++P) { 671 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { 672 ID.AddInteger(0); 673 ID.AddBoolean(TTP->isParameterPack()); 674 const TypeConstraint *TC = TTP->getTypeConstraint(); 675 ID.AddBoolean(TC != nullptr); 676 if (TC) 677 TC->getImmediatelyDeclaredConstraint()->Profile(ID, C, 678 /*Canonical=*/true); 679 if (TTP->isExpandedParameterPack()) { 680 ID.AddBoolean(true); 681 ID.AddInteger(TTP->getNumExpansionParameters()); 682 } else 683 ID.AddBoolean(false); 684 continue; 685 } 686 687 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 688 ID.AddInteger(1); 689 ID.AddBoolean(NTTP->isParameterPack()); 690 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr()); 691 if (NTTP->isExpandedParameterPack()) { 692 ID.AddBoolean(true); 693 ID.AddInteger(NTTP->getNumExpansionTypes()); 694 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { 695 QualType T = NTTP->getExpansionType(I); 696 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr()); 697 } 698 } else 699 ID.AddBoolean(false); 700 continue; 701 } 702 703 auto *TTP = cast<TemplateTemplateParmDecl>(*P); 704 ID.AddInteger(2); 705 Profile(ID, C, TTP); 706 } 707 Expr *RequiresClause = Parm->getTemplateParameters()->getRequiresClause(); 708 ID.AddBoolean(RequiresClause != nullptr); 709 if (RequiresClause) 710 RequiresClause->Profile(ID, C, /*Canonical=*/true); 711 } 712 713 static Expr * 714 canonicalizeImmediatelyDeclaredConstraint(const ASTContext &C, Expr *IDC, 715 QualType ConstrainedType) { 716 // This is a bit ugly - we need to form a new immediately-declared 717 // constraint that references the new parameter; this would ideally 718 // require semantic analysis (e.g. template<C T> struct S {}; - the 719 // converted arguments of C<T> could be an argument pack if C is 720 // declared as template<typename... T> concept C = ...). 721 // We don't have semantic analysis here so we dig deep into the 722 // ready-made constraint expr and change the thing manually. 723 ConceptSpecializationExpr *CSE; 724 if (const auto *Fold = dyn_cast<CXXFoldExpr>(IDC)) 725 CSE = cast<ConceptSpecializationExpr>(Fold->getLHS()); 726 else 727 CSE = cast<ConceptSpecializationExpr>(IDC); 728 ArrayRef<TemplateArgument> OldConverted = CSE->getTemplateArguments(); 729 SmallVector<TemplateArgument, 3> NewConverted; 730 NewConverted.reserve(OldConverted.size()); 731 if (OldConverted.front().getKind() == TemplateArgument::Pack) { 732 // The case: 733 // template<typename... T> concept C = true; 734 // template<C<int> T> struct S; -> constraint is C<{T, int}> 735 NewConverted.push_back(ConstrainedType); 736 for (auto &Arg : OldConverted.front().pack_elements().drop_front(1)) 737 NewConverted.push_back(Arg); 738 TemplateArgument NewPack(NewConverted); 739 740 NewConverted.clear(); 741 NewConverted.push_back(NewPack); 742 assert(OldConverted.size() == 1 && 743 "Template parameter pack should be the last parameter"); 744 } else { 745 assert(OldConverted.front().getKind() == TemplateArgument::Type && 746 "Unexpected first argument kind for immediately-declared " 747 "constraint"); 748 NewConverted.push_back(ConstrainedType); 749 for (auto &Arg : OldConverted.drop_front(1)) 750 NewConverted.push_back(Arg); 751 } 752 Expr *NewIDC = ConceptSpecializationExpr::Create( 753 C, CSE->getNamedConcept(), NewConverted, nullptr, 754 CSE->isInstantiationDependent(), CSE->containsUnexpandedParameterPack()); 755 756 if (auto *OrigFold = dyn_cast<CXXFoldExpr>(IDC)) 757 NewIDC = new (C) CXXFoldExpr( 758 OrigFold->getType(), /*Callee*/nullptr, SourceLocation(), NewIDC, 759 BinaryOperatorKind::BO_LAnd, SourceLocation(), /*RHS=*/nullptr, 760 SourceLocation(), /*NumExpansions=*/None); 761 return NewIDC; 762 } 763 764 TemplateTemplateParmDecl * 765 ASTContext::getCanonicalTemplateTemplateParmDecl( 766 TemplateTemplateParmDecl *TTP) const { 767 // Check if we already have a canonical template template parameter. 768 llvm::FoldingSetNodeID ID; 769 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP); 770 void *InsertPos = nullptr; 771 CanonicalTemplateTemplateParm *Canonical 772 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 773 if (Canonical) 774 return Canonical->getParam(); 775 776 // Build a canonical template parameter list. 777 TemplateParameterList *Params = TTP->getTemplateParameters(); 778 SmallVector<NamedDecl *, 4> CanonParams; 779 CanonParams.reserve(Params->size()); 780 for (TemplateParameterList::const_iterator P = Params->begin(), 781 PEnd = Params->end(); 782 P != PEnd; ++P) { 783 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { 784 TemplateTypeParmDecl *NewTTP = TemplateTypeParmDecl::Create(*this, 785 getTranslationUnitDecl(), SourceLocation(), SourceLocation(), 786 TTP->getDepth(), TTP->getIndex(), nullptr, false, 787 TTP->isParameterPack(), TTP->hasTypeConstraint(), 788 TTP->isExpandedParameterPack() ? 789 llvm::Optional<unsigned>(TTP->getNumExpansionParameters()) : None); 790 if (const auto *TC = TTP->getTypeConstraint()) { 791 QualType ParamAsArgument(NewTTP->getTypeForDecl(), 0); 792 Expr *NewIDC = canonicalizeImmediatelyDeclaredConstraint( 793 *this, TC->getImmediatelyDeclaredConstraint(), 794 ParamAsArgument); 795 TemplateArgumentListInfo CanonArgsAsWritten; 796 if (auto *Args = TC->getTemplateArgsAsWritten()) 797 for (const auto &ArgLoc : Args->arguments()) 798 CanonArgsAsWritten.addArgument( 799 TemplateArgumentLoc(ArgLoc.getArgument(), 800 TemplateArgumentLocInfo())); 801 NewTTP->setTypeConstraint( 802 NestedNameSpecifierLoc(), 803 DeclarationNameInfo(TC->getNamedConcept()->getDeclName(), 804 SourceLocation()), /*FoundDecl=*/nullptr, 805 // Actually canonicalizing a TemplateArgumentLoc is difficult so we 806 // simply omit the ArgsAsWritten 807 TC->getNamedConcept(), /*ArgsAsWritten=*/nullptr, NewIDC); 808 } 809 CanonParams.push_back(NewTTP); 810 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 811 QualType T = getCanonicalType(NTTP->getType()); 812 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); 813 NonTypeTemplateParmDecl *Param; 814 if (NTTP->isExpandedParameterPack()) { 815 SmallVector<QualType, 2> ExpandedTypes; 816 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos; 817 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { 818 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I))); 819 ExpandedTInfos.push_back( 820 getTrivialTypeSourceInfo(ExpandedTypes.back())); 821 } 822 823 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 824 SourceLocation(), 825 SourceLocation(), 826 NTTP->getDepth(), 827 NTTP->getPosition(), nullptr, 828 T, 829 TInfo, 830 ExpandedTypes, 831 ExpandedTInfos); 832 } else { 833 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 834 SourceLocation(), 835 SourceLocation(), 836 NTTP->getDepth(), 837 NTTP->getPosition(), nullptr, 838 T, 839 NTTP->isParameterPack(), 840 TInfo); 841 } 842 if (AutoType *AT = T->getContainedAutoType()) { 843 if (AT->isConstrained()) { 844 Param->setPlaceholderTypeConstraint( 845 canonicalizeImmediatelyDeclaredConstraint( 846 *this, NTTP->getPlaceholderTypeConstraint(), T)); 847 } 848 } 849 CanonParams.push_back(Param); 850 851 } else 852 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl( 853 cast<TemplateTemplateParmDecl>(*P))); 854 } 855 856 Expr *CanonRequiresClause = nullptr; 857 if (Expr *RequiresClause = TTP->getTemplateParameters()->getRequiresClause()) 858 CanonRequiresClause = RequiresClause; 859 860 TemplateTemplateParmDecl *CanonTTP 861 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 862 SourceLocation(), TTP->getDepth(), 863 TTP->getPosition(), 864 TTP->isParameterPack(), 865 nullptr, 866 TemplateParameterList::Create(*this, SourceLocation(), 867 SourceLocation(), 868 CanonParams, 869 SourceLocation(), 870 CanonRequiresClause)); 871 872 // Get the new insert position for the node we care about. 873 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 874 assert(!Canonical && "Shouldn't be in the map!"); 875 (void)Canonical; 876 877 // Create the canonical template template parameter entry. 878 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP); 879 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos); 880 return CanonTTP; 881 } 882 883 TargetCXXABI::Kind ASTContext::getCXXABIKind() const { 884 auto Kind = getTargetInfo().getCXXABI().getKind(); 885 return getLangOpts().CXXABI.getValueOr(Kind); 886 } 887 888 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) { 889 if (!LangOpts.CPlusPlus) return nullptr; 890 891 switch (getCXXABIKind()) { 892 case TargetCXXABI::AppleARM64: 893 case TargetCXXABI::Fuchsia: 894 case TargetCXXABI::GenericARM: // Same as Itanium at this level 895 case TargetCXXABI::iOS: 896 case TargetCXXABI::WatchOS: 897 case TargetCXXABI::GenericAArch64: 898 case TargetCXXABI::GenericMIPS: 899 case TargetCXXABI::GenericItanium: 900 case TargetCXXABI::WebAssembly: 901 case TargetCXXABI::XL: 902 return CreateItaniumCXXABI(*this); 903 case TargetCXXABI::Microsoft: 904 return CreateMicrosoftCXXABI(*this); 905 } 906 llvm_unreachable("Invalid CXXABI type!"); 907 } 908 909 interp::Context &ASTContext::getInterpContext() { 910 if (!InterpContext) { 911 InterpContext.reset(new interp::Context(*this)); 912 } 913 return *InterpContext.get(); 914 } 915 916 ParentMapContext &ASTContext::getParentMapContext() { 917 if (!ParentMapCtx) 918 ParentMapCtx.reset(new ParentMapContext(*this)); 919 return *ParentMapCtx.get(); 920 } 921 922 static const LangASMap *getAddressSpaceMap(const TargetInfo &T, 923 const LangOptions &LOpts) { 924 if (LOpts.FakeAddressSpaceMap) { 925 // The fake address space map must have a distinct entry for each 926 // language-specific address space. 927 static const unsigned FakeAddrSpaceMap[] = { 928 0, // Default 929 1, // opencl_global 930 3, // opencl_local 931 2, // opencl_constant 932 0, // opencl_private 933 4, // opencl_generic 934 5, // opencl_global_device 935 6, // opencl_global_host 936 7, // cuda_device 937 8, // cuda_constant 938 9, // cuda_shared 939 1, // sycl_global 940 5, // sycl_global_device 941 6, // sycl_global_host 942 3, // sycl_local 943 0, // sycl_private 944 10, // ptr32_sptr 945 11, // ptr32_uptr 946 12 // ptr64 947 }; 948 return &FakeAddrSpaceMap; 949 } else { 950 return &T.getAddressSpaceMap(); 951 } 952 } 953 954 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI, 955 const LangOptions &LangOpts) { 956 switch (LangOpts.getAddressSpaceMapMangling()) { 957 case LangOptions::ASMM_Target: 958 return TI.useAddressSpaceMapMangling(); 959 case LangOptions::ASMM_On: 960 return true; 961 case LangOptions::ASMM_Off: 962 return false; 963 } 964 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything."); 965 } 966 967 ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM, 968 IdentifierTable &idents, SelectorTable &sels, 969 Builtin::Context &builtins, TranslationUnitKind TUKind) 970 : ConstantArrayTypes(this_()), FunctionProtoTypes(this_()), 971 TemplateSpecializationTypes(this_()), 972 DependentTemplateSpecializationTypes(this_()), AutoTypes(this_()), 973 SubstTemplateTemplateParmPacks(this_()), 974 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts), 975 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)), 976 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles, 977 LangOpts.XRayNeverInstrumentFiles, 978 LangOpts.XRayAttrListFiles, SM)), 979 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)), 980 PrintingPolicy(LOpts), Idents(idents), Selectors(sels), 981 BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this), 982 Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), 983 CompCategories(this_()), LastSDM(nullptr, 0) { 984 addTranslationUnitDecl(); 985 } 986 987 ASTContext::~ASTContext() { 988 // Release the DenseMaps associated with DeclContext objects. 989 // FIXME: Is this the ideal solution? 990 ReleaseDeclContextMaps(); 991 992 // Call all of the deallocation functions on all of their targets. 993 for (auto &Pair : Deallocations) 994 (Pair.first)(Pair.second); 995 996 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed 997 // because they can contain DenseMaps. 998 for (llvm::DenseMap<const ObjCContainerDecl*, 999 const ASTRecordLayout*>::iterator 1000 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) 1001 // Increment in loop to prevent using deallocated memory. 1002 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second)) 1003 R->Destroy(*this); 1004 1005 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator 1006 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) { 1007 // Increment in loop to prevent using deallocated memory. 1008 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second)) 1009 R->Destroy(*this); 1010 } 1011 1012 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(), 1013 AEnd = DeclAttrs.end(); 1014 A != AEnd; ++A) 1015 A->second->~AttrVec(); 1016 1017 for (const auto &Value : ModuleInitializers) 1018 Value.second->~PerModuleInitializers(); 1019 } 1020 1021 void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) { 1022 TraversalScope = TopLevelDecls; 1023 getParentMapContext().clear(); 1024 } 1025 1026 void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const { 1027 Deallocations.push_back({Callback, Data}); 1028 } 1029 1030 void 1031 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) { 1032 ExternalSource = std::move(Source); 1033 } 1034 1035 void ASTContext::PrintStats() const { 1036 llvm::errs() << "\n*** AST Context Stats:\n"; 1037 llvm::errs() << " " << Types.size() << " types total.\n"; 1038 1039 unsigned counts[] = { 1040 #define TYPE(Name, Parent) 0, 1041 #define ABSTRACT_TYPE(Name, Parent) 1042 #include "clang/AST/TypeNodes.inc" 1043 0 // Extra 1044 }; 1045 1046 for (unsigned i = 0, e = Types.size(); i != e; ++i) { 1047 Type *T = Types[i]; 1048 counts[(unsigned)T->getTypeClass()]++; 1049 } 1050 1051 unsigned Idx = 0; 1052 unsigned TotalBytes = 0; 1053 #define TYPE(Name, Parent) \ 1054 if (counts[Idx]) \ 1055 llvm::errs() << " " << counts[Idx] << " " << #Name \ 1056 << " types, " << sizeof(Name##Type) << " each " \ 1057 << "(" << counts[Idx] * sizeof(Name##Type) \ 1058 << " bytes)\n"; \ 1059 TotalBytes += counts[Idx] * sizeof(Name##Type); \ 1060 ++Idx; 1061 #define ABSTRACT_TYPE(Name, Parent) 1062 #include "clang/AST/TypeNodes.inc" 1063 1064 llvm::errs() << "Total bytes = " << TotalBytes << "\n"; 1065 1066 // Implicit special member functions. 1067 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/" 1068 << NumImplicitDefaultConstructors 1069 << " implicit default constructors created\n"; 1070 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/" 1071 << NumImplicitCopyConstructors 1072 << " implicit copy constructors created\n"; 1073 if (getLangOpts().CPlusPlus) 1074 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/" 1075 << NumImplicitMoveConstructors 1076 << " implicit move constructors created\n"; 1077 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/" 1078 << NumImplicitCopyAssignmentOperators 1079 << " implicit copy assignment operators created\n"; 1080 if (getLangOpts().CPlusPlus) 1081 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/" 1082 << NumImplicitMoveAssignmentOperators 1083 << " implicit move assignment operators created\n"; 1084 llvm::errs() << NumImplicitDestructorsDeclared << "/" 1085 << NumImplicitDestructors 1086 << " implicit destructors created\n"; 1087 1088 if (ExternalSource) { 1089 llvm::errs() << "\n"; 1090 ExternalSource->PrintStats(); 1091 } 1092 1093 BumpAlloc.PrintStats(); 1094 } 1095 1096 void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M, 1097 bool NotifyListeners) { 1098 if (NotifyListeners) 1099 if (auto *Listener = getASTMutationListener()) 1100 Listener->RedefinedHiddenDefinition(ND, M); 1101 1102 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M); 1103 } 1104 1105 void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) { 1106 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl())); 1107 if (It == MergedDefModules.end()) 1108 return; 1109 1110 auto &Merged = It->second; 1111 llvm::DenseSet<Module*> Found; 1112 for (Module *&M : Merged) 1113 if (!Found.insert(M).second) 1114 M = nullptr; 1115 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end()); 1116 } 1117 1118 ArrayRef<Module *> 1119 ASTContext::getModulesWithMergedDefinition(const NamedDecl *Def) { 1120 auto MergedIt = 1121 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl())); 1122 if (MergedIt == MergedDefModules.end()) 1123 return None; 1124 return MergedIt->second; 1125 } 1126 1127 void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) { 1128 if (LazyInitializers.empty()) 1129 return; 1130 1131 auto *Source = Ctx.getExternalSource(); 1132 assert(Source && "lazy initializers but no external source"); 1133 1134 auto LazyInits = std::move(LazyInitializers); 1135 LazyInitializers.clear(); 1136 1137 for (auto ID : LazyInits) 1138 Initializers.push_back(Source->GetExternalDecl(ID)); 1139 1140 assert(LazyInitializers.empty() && 1141 "GetExternalDecl for lazy module initializer added more inits"); 1142 } 1143 1144 void ASTContext::addModuleInitializer(Module *M, Decl *D) { 1145 // One special case: if we add a module initializer that imports another 1146 // module, and that module's only initializer is an ImportDecl, simplify. 1147 if (const auto *ID = dyn_cast<ImportDecl>(D)) { 1148 auto It = ModuleInitializers.find(ID->getImportedModule()); 1149 1150 // Maybe the ImportDecl does nothing at all. (Common case.) 1151 if (It == ModuleInitializers.end()) 1152 return; 1153 1154 // Maybe the ImportDecl only imports another ImportDecl. 1155 auto &Imported = *It->second; 1156 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) { 1157 Imported.resolve(*this); 1158 auto *OnlyDecl = Imported.Initializers.front(); 1159 if (isa<ImportDecl>(OnlyDecl)) 1160 D = OnlyDecl; 1161 } 1162 } 1163 1164 auto *&Inits = ModuleInitializers[M]; 1165 if (!Inits) 1166 Inits = new (*this) PerModuleInitializers; 1167 Inits->Initializers.push_back(D); 1168 } 1169 1170 void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) { 1171 auto *&Inits = ModuleInitializers[M]; 1172 if (!Inits) 1173 Inits = new (*this) PerModuleInitializers; 1174 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(), 1175 IDs.begin(), IDs.end()); 1176 } 1177 1178 ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) { 1179 auto It = ModuleInitializers.find(M); 1180 if (It == ModuleInitializers.end()) 1181 return None; 1182 1183 auto *Inits = It->second; 1184 Inits->resolve(*this); 1185 return Inits->Initializers; 1186 } 1187 1188 ExternCContextDecl *ASTContext::getExternCContextDecl() const { 1189 if (!ExternCContext) 1190 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl()); 1191 1192 return ExternCContext; 1193 } 1194 1195 BuiltinTemplateDecl * 1196 ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK, 1197 const IdentifierInfo *II) const { 1198 auto *BuiltinTemplate = 1199 BuiltinTemplateDecl::Create(*this, getTranslationUnitDecl(), II, BTK); 1200 BuiltinTemplate->setImplicit(); 1201 getTranslationUnitDecl()->addDecl(BuiltinTemplate); 1202 1203 return BuiltinTemplate; 1204 } 1205 1206 BuiltinTemplateDecl * 1207 ASTContext::getMakeIntegerSeqDecl() const { 1208 if (!MakeIntegerSeqDecl) 1209 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq, 1210 getMakeIntegerSeqName()); 1211 return MakeIntegerSeqDecl; 1212 } 1213 1214 BuiltinTemplateDecl * 1215 ASTContext::getTypePackElementDecl() const { 1216 if (!TypePackElementDecl) 1217 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element, 1218 getTypePackElementName()); 1219 return TypePackElementDecl; 1220 } 1221 1222 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name, 1223 RecordDecl::TagKind TK) const { 1224 SourceLocation Loc; 1225 RecordDecl *NewDecl; 1226 if (getLangOpts().CPlusPlus) 1227 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, 1228 Loc, &Idents.get(Name)); 1229 else 1230 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc, 1231 &Idents.get(Name)); 1232 NewDecl->setImplicit(); 1233 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit( 1234 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default)); 1235 return NewDecl; 1236 } 1237 1238 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T, 1239 StringRef Name) const { 1240 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); 1241 TypedefDecl *NewDecl = TypedefDecl::Create( 1242 const_cast<ASTContext &>(*this), getTranslationUnitDecl(), 1243 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo); 1244 NewDecl->setImplicit(); 1245 return NewDecl; 1246 } 1247 1248 TypedefDecl *ASTContext::getInt128Decl() const { 1249 if (!Int128Decl) 1250 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t"); 1251 return Int128Decl; 1252 } 1253 1254 TypedefDecl *ASTContext::getUInt128Decl() const { 1255 if (!UInt128Decl) 1256 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t"); 1257 return UInt128Decl; 1258 } 1259 1260 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) { 1261 auto *Ty = new (*this, TypeAlignment) BuiltinType(K); 1262 R = CanQualType::CreateUnsafe(QualType(Ty, 0)); 1263 Types.push_back(Ty); 1264 } 1265 1266 void ASTContext::InitBuiltinTypes(const TargetInfo &Target, 1267 const TargetInfo *AuxTarget) { 1268 assert((!this->Target || this->Target == &Target) && 1269 "Incorrect target reinitialization"); 1270 assert(VoidTy.isNull() && "Context reinitialized?"); 1271 1272 this->Target = &Target; 1273 this->AuxTarget = AuxTarget; 1274 1275 ABI.reset(createCXXABI(Target)); 1276 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts); 1277 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts); 1278 1279 // C99 6.2.5p19. 1280 InitBuiltinType(VoidTy, BuiltinType::Void); 1281 1282 // C99 6.2.5p2. 1283 InitBuiltinType(BoolTy, BuiltinType::Bool); 1284 // C99 6.2.5p3. 1285 if (LangOpts.CharIsSigned) 1286 InitBuiltinType(CharTy, BuiltinType::Char_S); 1287 else 1288 InitBuiltinType(CharTy, BuiltinType::Char_U); 1289 // C99 6.2.5p4. 1290 InitBuiltinType(SignedCharTy, BuiltinType::SChar); 1291 InitBuiltinType(ShortTy, BuiltinType::Short); 1292 InitBuiltinType(IntTy, BuiltinType::Int); 1293 InitBuiltinType(LongTy, BuiltinType::Long); 1294 InitBuiltinType(LongLongTy, BuiltinType::LongLong); 1295 1296 // C99 6.2.5p6. 1297 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar); 1298 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort); 1299 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt); 1300 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong); 1301 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong); 1302 1303 // C99 6.2.5p10. 1304 InitBuiltinType(FloatTy, BuiltinType::Float); 1305 InitBuiltinType(DoubleTy, BuiltinType::Double); 1306 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble); 1307 1308 // GNU extension, __float128 for IEEE quadruple precision 1309 InitBuiltinType(Float128Ty, BuiltinType::Float128); 1310 1311 // C11 extension ISO/IEC TS 18661-3 1312 InitBuiltinType(Float16Ty, BuiltinType::Float16); 1313 1314 // ISO/IEC JTC1 SC22 WG14 N1169 Extension 1315 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum); 1316 InitBuiltinType(AccumTy, BuiltinType::Accum); 1317 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum); 1318 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum); 1319 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum); 1320 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum); 1321 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract); 1322 InitBuiltinType(FractTy, BuiltinType::Fract); 1323 InitBuiltinType(LongFractTy, BuiltinType::LongFract); 1324 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract); 1325 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract); 1326 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract); 1327 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum); 1328 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum); 1329 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum); 1330 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum); 1331 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum); 1332 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum); 1333 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract); 1334 InitBuiltinType(SatFractTy, BuiltinType::SatFract); 1335 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract); 1336 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract); 1337 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract); 1338 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract); 1339 1340 // GNU extension, 128-bit integers. 1341 InitBuiltinType(Int128Ty, BuiltinType::Int128); 1342 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128); 1343 1344 // C++ 3.9.1p5 1345 if (TargetInfo::isTypeSigned(Target.getWCharType())) 1346 InitBuiltinType(WCharTy, BuiltinType::WChar_S); 1347 else // -fshort-wchar makes wchar_t be unsigned. 1348 InitBuiltinType(WCharTy, BuiltinType::WChar_U); 1349 if (LangOpts.CPlusPlus && LangOpts.WChar) 1350 WideCharTy = WCharTy; 1351 else { 1352 // C99 (or C++ using -fno-wchar). 1353 WideCharTy = getFromTargetType(Target.getWCharType()); 1354 } 1355 1356 WIntTy = getFromTargetType(Target.getWIntType()); 1357 1358 // C++20 (proposed) 1359 InitBuiltinType(Char8Ty, BuiltinType::Char8); 1360 1361 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 1362 InitBuiltinType(Char16Ty, BuiltinType::Char16); 1363 else // C99 1364 Char16Ty = getFromTargetType(Target.getChar16Type()); 1365 1366 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 1367 InitBuiltinType(Char32Ty, BuiltinType::Char32); 1368 else // C99 1369 Char32Ty = getFromTargetType(Target.getChar32Type()); 1370 1371 // Placeholder type for type-dependent expressions whose type is 1372 // completely unknown. No code should ever check a type against 1373 // DependentTy and users should never see it; however, it is here to 1374 // help diagnose failures to properly check for type-dependent 1375 // expressions. 1376 InitBuiltinType(DependentTy, BuiltinType::Dependent); 1377 1378 // Placeholder type for functions. 1379 InitBuiltinType(OverloadTy, BuiltinType::Overload); 1380 1381 // Placeholder type for bound members. 1382 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember); 1383 1384 // Placeholder type for pseudo-objects. 1385 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject); 1386 1387 // "any" type; useful for debugger-like clients. 1388 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny); 1389 1390 // Placeholder type for unbridged ARC casts. 1391 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast); 1392 1393 // Placeholder type for builtin functions. 1394 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn); 1395 1396 // Placeholder type for OMP array sections. 1397 if (LangOpts.OpenMP) { 1398 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection); 1399 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping); 1400 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator); 1401 } 1402 if (LangOpts.MatrixTypes) 1403 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx); 1404 1405 // C99 6.2.5p11. 1406 FloatComplexTy = getComplexType(FloatTy); 1407 DoubleComplexTy = getComplexType(DoubleTy); 1408 LongDoubleComplexTy = getComplexType(LongDoubleTy); 1409 Float128ComplexTy = getComplexType(Float128Ty); 1410 1411 // Builtin types for 'id', 'Class', and 'SEL'. 1412 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId); 1413 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass); 1414 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel); 1415 1416 if (LangOpts.OpenCL) { 1417 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 1418 InitBuiltinType(SingletonId, BuiltinType::Id); 1419 #include "clang/Basic/OpenCLImageTypes.def" 1420 1421 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler); 1422 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent); 1423 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent); 1424 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue); 1425 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID); 1426 1427 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 1428 InitBuiltinType(Id##Ty, BuiltinType::Id); 1429 #include "clang/Basic/OpenCLExtensionTypes.def" 1430 } 1431 1432 if (Target.hasAArch64SVETypes()) { 1433 #define SVE_TYPE(Name, Id, SingletonId) \ 1434 InitBuiltinType(SingletonId, BuiltinType::Id); 1435 #include "clang/Basic/AArch64SVEACLETypes.def" 1436 } 1437 1438 if (Target.getTriple().isPPC64() && 1439 Target.hasFeature("paired-vector-memops")) { 1440 if (Target.hasFeature("mma")) { 1441 #define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \ 1442 InitBuiltinType(Id##Ty, BuiltinType::Id); 1443 #include "clang/Basic/PPCTypes.def" 1444 } 1445 #define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \ 1446 InitBuiltinType(Id##Ty, BuiltinType::Id); 1447 #include "clang/Basic/PPCTypes.def" 1448 } 1449 1450 if (Target.hasRISCVVTypes()) { 1451 #define RVV_TYPE(Name, Id, SingletonId) \ 1452 InitBuiltinType(SingletonId, BuiltinType::Id); 1453 #include "clang/Basic/RISCVVTypes.def" 1454 } 1455 1456 // Builtin type for __objc_yes and __objc_no 1457 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ? 1458 SignedCharTy : BoolTy); 1459 1460 ObjCConstantStringType = QualType(); 1461 1462 ObjCSuperType = QualType(); 1463 1464 // void * type 1465 if (LangOpts.OpenCLGenericAddressSpace) { 1466 auto Q = VoidTy.getQualifiers(); 1467 Q.setAddressSpace(LangAS::opencl_generic); 1468 VoidPtrTy = getPointerType(getCanonicalType( 1469 getQualifiedType(VoidTy.getUnqualifiedType(), Q))); 1470 } else { 1471 VoidPtrTy = getPointerType(VoidTy); 1472 } 1473 1474 // nullptr type (C++0x 2.14.7) 1475 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr); 1476 1477 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16 1478 InitBuiltinType(HalfTy, BuiltinType::Half); 1479 1480 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16); 1481 1482 // Builtin type used to help define __builtin_va_list. 1483 VaListTagDecl = nullptr; 1484 1485 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls. 1486 if (LangOpts.MicrosoftExt || LangOpts.Borland) { 1487 MSGuidTagDecl = buildImplicitRecord("_GUID"); 1488 getTranslationUnitDecl()->addDecl(MSGuidTagDecl); 1489 } 1490 } 1491 1492 DiagnosticsEngine &ASTContext::getDiagnostics() const { 1493 return SourceMgr.getDiagnostics(); 1494 } 1495 1496 AttrVec& ASTContext::getDeclAttrs(const Decl *D) { 1497 AttrVec *&Result = DeclAttrs[D]; 1498 if (!Result) { 1499 void *Mem = Allocate(sizeof(AttrVec)); 1500 Result = new (Mem) AttrVec; 1501 } 1502 1503 return *Result; 1504 } 1505 1506 /// Erase the attributes corresponding to the given declaration. 1507 void ASTContext::eraseDeclAttrs(const Decl *D) { 1508 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D); 1509 if (Pos != DeclAttrs.end()) { 1510 Pos->second->~AttrVec(); 1511 DeclAttrs.erase(Pos); 1512 } 1513 } 1514 1515 // FIXME: Remove ? 1516 MemberSpecializationInfo * 1517 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) { 1518 assert(Var->isStaticDataMember() && "Not a static data member"); 1519 return getTemplateOrSpecializationInfo(Var) 1520 .dyn_cast<MemberSpecializationInfo *>(); 1521 } 1522 1523 ASTContext::TemplateOrSpecializationInfo 1524 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) { 1525 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos = 1526 TemplateOrInstantiation.find(Var); 1527 if (Pos == TemplateOrInstantiation.end()) 1528 return {}; 1529 1530 return Pos->second; 1531 } 1532 1533 void 1534 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, 1535 TemplateSpecializationKind TSK, 1536 SourceLocation PointOfInstantiation) { 1537 assert(Inst->isStaticDataMember() && "Not a static data member"); 1538 assert(Tmpl->isStaticDataMember() && "Not a static data member"); 1539 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo( 1540 Tmpl, TSK, PointOfInstantiation)); 1541 } 1542 1543 void 1544 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst, 1545 TemplateOrSpecializationInfo TSI) { 1546 assert(!TemplateOrInstantiation[Inst] && 1547 "Already noted what the variable was instantiated from"); 1548 TemplateOrInstantiation[Inst] = TSI; 1549 } 1550 1551 NamedDecl * 1552 ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) { 1553 auto Pos = InstantiatedFromUsingDecl.find(UUD); 1554 if (Pos == InstantiatedFromUsingDecl.end()) 1555 return nullptr; 1556 1557 return Pos->second; 1558 } 1559 1560 void 1561 ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) { 1562 assert((isa<UsingDecl>(Pattern) || 1563 isa<UnresolvedUsingValueDecl>(Pattern) || 1564 isa<UnresolvedUsingTypenameDecl>(Pattern)) && 1565 "pattern decl is not a using decl"); 1566 assert((isa<UsingDecl>(Inst) || 1567 isa<UnresolvedUsingValueDecl>(Inst) || 1568 isa<UnresolvedUsingTypenameDecl>(Inst)) && 1569 "instantiation did not produce a using decl"); 1570 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists"); 1571 InstantiatedFromUsingDecl[Inst] = Pattern; 1572 } 1573 1574 UsingEnumDecl * 1575 ASTContext::getInstantiatedFromUsingEnumDecl(UsingEnumDecl *UUD) { 1576 auto Pos = InstantiatedFromUsingEnumDecl.find(UUD); 1577 if (Pos == InstantiatedFromUsingEnumDecl.end()) 1578 return nullptr; 1579 1580 return Pos->second; 1581 } 1582 1583 void ASTContext::setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst, 1584 UsingEnumDecl *Pattern) { 1585 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists"); 1586 InstantiatedFromUsingEnumDecl[Inst] = Pattern; 1587 } 1588 1589 UsingShadowDecl * 1590 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) { 1591 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos 1592 = InstantiatedFromUsingShadowDecl.find(Inst); 1593 if (Pos == InstantiatedFromUsingShadowDecl.end()) 1594 return nullptr; 1595 1596 return Pos->second; 1597 } 1598 1599 void 1600 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, 1601 UsingShadowDecl *Pattern) { 1602 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists"); 1603 InstantiatedFromUsingShadowDecl[Inst] = Pattern; 1604 } 1605 1606 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) { 1607 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos 1608 = InstantiatedFromUnnamedFieldDecl.find(Field); 1609 if (Pos == InstantiatedFromUnnamedFieldDecl.end()) 1610 return nullptr; 1611 1612 return Pos->second; 1613 } 1614 1615 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, 1616 FieldDecl *Tmpl) { 1617 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed"); 1618 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed"); 1619 assert(!InstantiatedFromUnnamedFieldDecl[Inst] && 1620 "Already noted what unnamed field was instantiated from"); 1621 1622 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl; 1623 } 1624 1625 ASTContext::overridden_cxx_method_iterator 1626 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const { 1627 return overridden_methods(Method).begin(); 1628 } 1629 1630 ASTContext::overridden_cxx_method_iterator 1631 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const { 1632 return overridden_methods(Method).end(); 1633 } 1634 1635 unsigned 1636 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const { 1637 auto Range = overridden_methods(Method); 1638 return Range.end() - Range.begin(); 1639 } 1640 1641 ASTContext::overridden_method_range 1642 ASTContext::overridden_methods(const CXXMethodDecl *Method) const { 1643 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos = 1644 OverriddenMethods.find(Method->getCanonicalDecl()); 1645 if (Pos == OverriddenMethods.end()) 1646 return overridden_method_range(nullptr, nullptr); 1647 return overridden_method_range(Pos->second.begin(), Pos->second.end()); 1648 } 1649 1650 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method, 1651 const CXXMethodDecl *Overridden) { 1652 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl()); 1653 OverriddenMethods[Method].push_back(Overridden); 1654 } 1655 1656 void ASTContext::getOverriddenMethods( 1657 const NamedDecl *D, 1658 SmallVectorImpl<const NamedDecl *> &Overridden) const { 1659 assert(D); 1660 1661 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) { 1662 Overridden.append(overridden_methods_begin(CXXMethod), 1663 overridden_methods_end(CXXMethod)); 1664 return; 1665 } 1666 1667 const auto *Method = dyn_cast<ObjCMethodDecl>(D); 1668 if (!Method) 1669 return; 1670 1671 SmallVector<const ObjCMethodDecl *, 8> OverDecls; 1672 Method->getOverriddenMethods(OverDecls); 1673 Overridden.append(OverDecls.begin(), OverDecls.end()); 1674 } 1675 1676 void ASTContext::addedLocalImportDecl(ImportDecl *Import) { 1677 assert(!Import->getNextLocalImport() && 1678 "Import declaration already in the chain"); 1679 assert(!Import->isFromASTFile() && "Non-local import declaration"); 1680 if (!FirstLocalImport) { 1681 FirstLocalImport = Import; 1682 LastLocalImport = Import; 1683 return; 1684 } 1685 1686 LastLocalImport->setNextLocalImport(Import); 1687 LastLocalImport = Import; 1688 } 1689 1690 //===----------------------------------------------------------------------===// 1691 // Type Sizing and Analysis 1692 //===----------------------------------------------------------------------===// 1693 1694 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified 1695 /// scalar floating point type. 1696 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const { 1697 switch (T->castAs<BuiltinType>()->getKind()) { 1698 default: 1699 llvm_unreachable("Not a floating point type!"); 1700 case BuiltinType::BFloat16: 1701 return Target->getBFloat16Format(); 1702 case BuiltinType::Float16: 1703 case BuiltinType::Half: 1704 return Target->getHalfFormat(); 1705 case BuiltinType::Float: return Target->getFloatFormat(); 1706 case BuiltinType::Double: return Target->getDoubleFormat(); 1707 case BuiltinType::LongDouble: 1708 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) 1709 return AuxTarget->getLongDoubleFormat(); 1710 return Target->getLongDoubleFormat(); 1711 case BuiltinType::Float128: 1712 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) 1713 return AuxTarget->getFloat128Format(); 1714 return Target->getFloat128Format(); 1715 } 1716 } 1717 1718 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const { 1719 unsigned Align = Target->getCharWidth(); 1720 1721 bool UseAlignAttrOnly = false; 1722 if (unsigned AlignFromAttr = D->getMaxAlignment()) { 1723 Align = AlignFromAttr; 1724 1725 // __attribute__((aligned)) can increase or decrease alignment 1726 // *except* on a struct or struct member, where it only increases 1727 // alignment unless 'packed' is also specified. 1728 // 1729 // It is an error for alignas to decrease alignment, so we can 1730 // ignore that possibility; Sema should diagnose it. 1731 if (isa<FieldDecl>(D)) { 1732 UseAlignAttrOnly = D->hasAttr<PackedAttr>() || 1733 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 1734 } else { 1735 UseAlignAttrOnly = true; 1736 } 1737 } 1738 else if (isa<FieldDecl>(D)) 1739 UseAlignAttrOnly = 1740 D->hasAttr<PackedAttr>() || 1741 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 1742 1743 // If we're using the align attribute only, just ignore everything 1744 // else about the declaration and its type. 1745 if (UseAlignAttrOnly) { 1746 // do nothing 1747 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) { 1748 QualType T = VD->getType(); 1749 if (const auto *RT = T->getAs<ReferenceType>()) { 1750 if (ForAlignof) 1751 T = RT->getPointeeType(); 1752 else 1753 T = getPointerType(RT->getPointeeType()); 1754 } 1755 QualType BaseT = getBaseElementType(T); 1756 if (T->isFunctionType()) 1757 Align = getTypeInfoImpl(T.getTypePtr()).Align; 1758 else if (!BaseT->isIncompleteType()) { 1759 // Adjust alignments of declarations with array type by the 1760 // large-array alignment on the target. 1761 if (const ArrayType *arrayType = getAsArrayType(T)) { 1762 unsigned MinWidth = Target->getLargeArrayMinWidth(); 1763 if (!ForAlignof && MinWidth) { 1764 if (isa<VariableArrayType>(arrayType)) 1765 Align = std::max(Align, Target->getLargeArrayAlign()); 1766 else if (isa<ConstantArrayType>(arrayType) && 1767 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType))) 1768 Align = std::max(Align, Target->getLargeArrayAlign()); 1769 } 1770 } 1771 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr())); 1772 if (BaseT.getQualifiers().hasUnaligned()) 1773 Align = Target->getCharWidth(); 1774 if (const auto *VD = dyn_cast<VarDecl>(D)) { 1775 if (VD->hasGlobalStorage() && !ForAlignof) { 1776 uint64_t TypeSize = getTypeSize(T.getTypePtr()); 1777 Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize)); 1778 } 1779 } 1780 } 1781 1782 // Fields can be subject to extra alignment constraints, like if 1783 // the field is packed, the struct is packed, or the struct has a 1784 // a max-field-alignment constraint (#pragma pack). So calculate 1785 // the actual alignment of the field within the struct, and then 1786 // (as we're expected to) constrain that by the alignment of the type. 1787 if (const auto *Field = dyn_cast<FieldDecl>(VD)) { 1788 const RecordDecl *Parent = Field->getParent(); 1789 // We can only produce a sensible answer if the record is valid. 1790 if (!Parent->isInvalidDecl()) { 1791 const ASTRecordLayout &Layout = getASTRecordLayout(Parent); 1792 1793 // Start with the record's overall alignment. 1794 unsigned FieldAlign = toBits(Layout.getAlignment()); 1795 1796 // Use the GCD of that and the offset within the record. 1797 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex()); 1798 if (Offset > 0) { 1799 // Alignment is always a power of 2, so the GCD will be a power of 2, 1800 // which means we get to do this crazy thing instead of Euclid's. 1801 uint64_t LowBitOfOffset = Offset & (~Offset + 1); 1802 if (LowBitOfOffset < FieldAlign) 1803 FieldAlign = static_cast<unsigned>(LowBitOfOffset); 1804 } 1805 1806 Align = std::min(Align, FieldAlign); 1807 } 1808 } 1809 } 1810 1811 // Some targets have hard limitation on the maximum requestable alignment in 1812 // aligned attribute for static variables. 1813 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute(); 1814 const auto *VD = dyn_cast<VarDecl>(D); 1815 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static) 1816 Align = std::min(Align, MaxAlignedAttr); 1817 1818 return toCharUnitsFromBits(Align); 1819 } 1820 1821 CharUnits ASTContext::getExnObjectAlignment() const { 1822 return toCharUnitsFromBits(Target->getExnObjectAlignment()); 1823 } 1824 1825 // getTypeInfoDataSizeInChars - Return the size of a type, in 1826 // chars. If the type is a record, its data size is returned. This is 1827 // the size of the memcpy that's performed when assigning this type 1828 // using a trivial copy/move assignment operator. 1829 TypeInfoChars ASTContext::getTypeInfoDataSizeInChars(QualType T) const { 1830 TypeInfoChars Info = getTypeInfoInChars(T); 1831 1832 // In C++, objects can sometimes be allocated into the tail padding 1833 // of a base-class subobject. We decide whether that's possible 1834 // during class layout, so here we can just trust the layout results. 1835 if (getLangOpts().CPlusPlus) { 1836 if (const auto *RT = T->getAs<RecordType>()) { 1837 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl()); 1838 Info.Width = layout.getDataSize(); 1839 } 1840 } 1841 1842 return Info; 1843 } 1844 1845 /// getConstantArrayInfoInChars - Performing the computation in CharUnits 1846 /// instead of in bits prevents overflowing the uint64_t for some large arrays. 1847 TypeInfoChars 1848 static getConstantArrayInfoInChars(const ASTContext &Context, 1849 const ConstantArrayType *CAT) { 1850 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType()); 1851 uint64_t Size = CAT->getSize().getZExtValue(); 1852 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <= 1853 (uint64_t)(-1)/Size) && 1854 "Overflow in array type char size evaluation"); 1855 uint64_t Width = EltInfo.Width.getQuantity() * Size; 1856 unsigned Align = EltInfo.Align.getQuantity(); 1857 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() || 1858 Context.getTargetInfo().getPointerWidth(0) == 64) 1859 Width = llvm::alignTo(Width, Align); 1860 return TypeInfoChars(CharUnits::fromQuantity(Width), 1861 CharUnits::fromQuantity(Align), 1862 EltInfo.AlignIsRequired); 1863 } 1864 1865 TypeInfoChars ASTContext::getTypeInfoInChars(const Type *T) const { 1866 if (const auto *CAT = dyn_cast<ConstantArrayType>(T)) 1867 return getConstantArrayInfoInChars(*this, CAT); 1868 TypeInfo Info = getTypeInfo(T); 1869 return TypeInfoChars(toCharUnitsFromBits(Info.Width), 1870 toCharUnitsFromBits(Info.Align), 1871 Info.AlignIsRequired); 1872 } 1873 1874 TypeInfoChars ASTContext::getTypeInfoInChars(QualType T) const { 1875 return getTypeInfoInChars(T.getTypePtr()); 1876 } 1877 1878 bool ASTContext::isAlignmentRequired(const Type *T) const { 1879 return getTypeInfo(T).AlignIsRequired; 1880 } 1881 1882 bool ASTContext::isAlignmentRequired(QualType T) const { 1883 return isAlignmentRequired(T.getTypePtr()); 1884 } 1885 1886 unsigned ASTContext::getTypeAlignIfKnown(QualType T, 1887 bool NeedsPreferredAlignment) const { 1888 // An alignment on a typedef overrides anything else. 1889 if (const auto *TT = T->getAs<TypedefType>()) 1890 if (unsigned Align = TT->getDecl()->getMaxAlignment()) 1891 return Align; 1892 1893 // If we have an (array of) complete type, we're done. 1894 T = getBaseElementType(T); 1895 if (!T->isIncompleteType()) 1896 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T); 1897 1898 // If we had an array type, its element type might be a typedef 1899 // type with an alignment attribute. 1900 if (const auto *TT = T->getAs<TypedefType>()) 1901 if (unsigned Align = TT->getDecl()->getMaxAlignment()) 1902 return Align; 1903 1904 // Otherwise, see if the declaration of the type had an attribute. 1905 if (const auto *TT = T->getAs<TagType>()) 1906 return TT->getDecl()->getMaxAlignment(); 1907 1908 return 0; 1909 } 1910 1911 TypeInfo ASTContext::getTypeInfo(const Type *T) const { 1912 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T); 1913 if (I != MemoizedTypeInfo.end()) 1914 return I->second; 1915 1916 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup. 1917 TypeInfo TI = getTypeInfoImpl(T); 1918 MemoizedTypeInfo[T] = TI; 1919 return TI; 1920 } 1921 1922 /// getTypeInfoImpl - Return the size of the specified type, in bits. This 1923 /// method does not work on incomplete types. 1924 /// 1925 /// FIXME: Pointers into different addr spaces could have different sizes and 1926 /// alignment requirements: getPointerInfo should take an AddrSpace, this 1927 /// should take a QualType, &c. 1928 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const { 1929 uint64_t Width = 0; 1930 unsigned Align = 8; 1931 bool AlignIsRequired = false; 1932 unsigned AS = 0; 1933 switch (T->getTypeClass()) { 1934 #define TYPE(Class, Base) 1935 #define ABSTRACT_TYPE(Class, Base) 1936 #define NON_CANONICAL_TYPE(Class, Base) 1937 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 1938 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \ 1939 case Type::Class: \ 1940 assert(!T->isDependentType() && "should not see dependent types here"); \ 1941 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr()); 1942 #include "clang/AST/TypeNodes.inc" 1943 llvm_unreachable("Should not see dependent types"); 1944 1945 case Type::FunctionNoProto: 1946 case Type::FunctionProto: 1947 // GCC extension: alignof(function) = 32 bits 1948 Width = 0; 1949 Align = 32; 1950 break; 1951 1952 case Type::IncompleteArray: 1953 case Type::VariableArray: 1954 case Type::ConstantArray: { 1955 // Model non-constant sized arrays as size zero, but track the alignment. 1956 uint64_t Size = 0; 1957 if (const auto *CAT = dyn_cast<ConstantArrayType>(T)) 1958 Size = CAT->getSize().getZExtValue(); 1959 1960 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType()); 1961 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) && 1962 "Overflow in array type bit size evaluation"); 1963 Width = EltInfo.Width * Size; 1964 Align = EltInfo.Align; 1965 AlignIsRequired = EltInfo.AlignIsRequired; 1966 if (!getTargetInfo().getCXXABI().isMicrosoft() || 1967 getTargetInfo().getPointerWidth(0) == 64) 1968 Width = llvm::alignTo(Width, Align); 1969 break; 1970 } 1971 1972 case Type::ExtVector: 1973 case Type::Vector: { 1974 const auto *VT = cast<VectorType>(T); 1975 TypeInfo EltInfo = getTypeInfo(VT->getElementType()); 1976 Width = EltInfo.Width * VT->getNumElements(); 1977 Align = Width; 1978 // If the alignment is not a power of 2, round up to the next power of 2. 1979 // This happens for non-power-of-2 length vectors. 1980 if (Align & (Align-1)) { 1981 Align = llvm::NextPowerOf2(Align); 1982 Width = llvm::alignTo(Width, Align); 1983 } 1984 // Adjust the alignment based on the target max. 1985 uint64_t TargetVectorAlign = Target->getMaxVectorAlign(); 1986 if (TargetVectorAlign && TargetVectorAlign < Align) 1987 Align = TargetVectorAlign; 1988 if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) 1989 // Adjust the alignment for fixed-length SVE vectors. This is important 1990 // for non-power-of-2 vector lengths. 1991 Align = 128; 1992 else if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 1993 // Adjust the alignment for fixed-length SVE predicates. 1994 Align = 16; 1995 break; 1996 } 1997 1998 case Type::ConstantMatrix: { 1999 const auto *MT = cast<ConstantMatrixType>(T); 2000 TypeInfo ElementInfo = getTypeInfo(MT->getElementType()); 2001 // The internal layout of a matrix value is implementation defined. 2002 // Initially be ABI compatible with arrays with respect to alignment and 2003 // size. 2004 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns(); 2005 Align = ElementInfo.Align; 2006 break; 2007 } 2008 2009 case Type::Builtin: 2010 switch (cast<BuiltinType>(T)->getKind()) { 2011 default: llvm_unreachable("Unknown builtin type!"); 2012 case BuiltinType::Void: 2013 // GCC extension: alignof(void) = 8 bits. 2014 Width = 0; 2015 Align = 8; 2016 break; 2017 case BuiltinType::Bool: 2018 Width = Target->getBoolWidth(); 2019 Align = Target->getBoolAlign(); 2020 break; 2021 case BuiltinType::Char_S: 2022 case BuiltinType::Char_U: 2023 case BuiltinType::UChar: 2024 case BuiltinType::SChar: 2025 case BuiltinType::Char8: 2026 Width = Target->getCharWidth(); 2027 Align = Target->getCharAlign(); 2028 break; 2029 case BuiltinType::WChar_S: 2030 case BuiltinType::WChar_U: 2031 Width = Target->getWCharWidth(); 2032 Align = Target->getWCharAlign(); 2033 break; 2034 case BuiltinType::Char16: 2035 Width = Target->getChar16Width(); 2036 Align = Target->getChar16Align(); 2037 break; 2038 case BuiltinType::Char32: 2039 Width = Target->getChar32Width(); 2040 Align = Target->getChar32Align(); 2041 break; 2042 case BuiltinType::UShort: 2043 case BuiltinType::Short: 2044 Width = Target->getShortWidth(); 2045 Align = Target->getShortAlign(); 2046 break; 2047 case BuiltinType::UInt: 2048 case BuiltinType::Int: 2049 Width = Target->getIntWidth(); 2050 Align = Target->getIntAlign(); 2051 break; 2052 case BuiltinType::ULong: 2053 case BuiltinType::Long: 2054 Width = Target->getLongWidth(); 2055 Align = Target->getLongAlign(); 2056 break; 2057 case BuiltinType::ULongLong: 2058 case BuiltinType::LongLong: 2059 Width = Target->getLongLongWidth(); 2060 Align = Target->getLongLongAlign(); 2061 break; 2062 case BuiltinType::Int128: 2063 case BuiltinType::UInt128: 2064 Width = 128; 2065 Align = 128; // int128_t is 128-bit aligned on all targets. 2066 break; 2067 case BuiltinType::ShortAccum: 2068 case BuiltinType::UShortAccum: 2069 case BuiltinType::SatShortAccum: 2070 case BuiltinType::SatUShortAccum: 2071 Width = Target->getShortAccumWidth(); 2072 Align = Target->getShortAccumAlign(); 2073 break; 2074 case BuiltinType::Accum: 2075 case BuiltinType::UAccum: 2076 case BuiltinType::SatAccum: 2077 case BuiltinType::SatUAccum: 2078 Width = Target->getAccumWidth(); 2079 Align = Target->getAccumAlign(); 2080 break; 2081 case BuiltinType::LongAccum: 2082 case BuiltinType::ULongAccum: 2083 case BuiltinType::SatLongAccum: 2084 case BuiltinType::SatULongAccum: 2085 Width = Target->getLongAccumWidth(); 2086 Align = Target->getLongAccumAlign(); 2087 break; 2088 case BuiltinType::ShortFract: 2089 case BuiltinType::UShortFract: 2090 case BuiltinType::SatShortFract: 2091 case BuiltinType::SatUShortFract: 2092 Width = Target->getShortFractWidth(); 2093 Align = Target->getShortFractAlign(); 2094 break; 2095 case BuiltinType::Fract: 2096 case BuiltinType::UFract: 2097 case BuiltinType::SatFract: 2098 case BuiltinType::SatUFract: 2099 Width = Target->getFractWidth(); 2100 Align = Target->getFractAlign(); 2101 break; 2102 case BuiltinType::LongFract: 2103 case BuiltinType::ULongFract: 2104 case BuiltinType::SatLongFract: 2105 case BuiltinType::SatULongFract: 2106 Width = Target->getLongFractWidth(); 2107 Align = Target->getLongFractAlign(); 2108 break; 2109 case BuiltinType::BFloat16: 2110 Width = Target->getBFloat16Width(); 2111 Align = Target->getBFloat16Align(); 2112 break; 2113 case BuiltinType::Float16: 2114 case BuiltinType::Half: 2115 if (Target->hasFloat16Type() || !getLangOpts().OpenMP || 2116 !getLangOpts().OpenMPIsDevice) { 2117 Width = Target->getHalfWidth(); 2118 Align = Target->getHalfAlign(); 2119 } else { 2120 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 2121 "Expected OpenMP device compilation."); 2122 Width = AuxTarget->getHalfWidth(); 2123 Align = AuxTarget->getHalfAlign(); 2124 } 2125 break; 2126 case BuiltinType::Float: 2127 Width = Target->getFloatWidth(); 2128 Align = Target->getFloatAlign(); 2129 break; 2130 case BuiltinType::Double: 2131 Width = Target->getDoubleWidth(); 2132 Align = Target->getDoubleAlign(); 2133 break; 2134 case BuiltinType::LongDouble: 2135 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 2136 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() || 2137 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) { 2138 Width = AuxTarget->getLongDoubleWidth(); 2139 Align = AuxTarget->getLongDoubleAlign(); 2140 } else { 2141 Width = Target->getLongDoubleWidth(); 2142 Align = Target->getLongDoubleAlign(); 2143 } 2144 break; 2145 case BuiltinType::Float128: 2146 if (Target->hasFloat128Type() || !getLangOpts().OpenMP || 2147 !getLangOpts().OpenMPIsDevice) { 2148 Width = Target->getFloat128Width(); 2149 Align = Target->getFloat128Align(); 2150 } else { 2151 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 2152 "Expected OpenMP device compilation."); 2153 Width = AuxTarget->getFloat128Width(); 2154 Align = AuxTarget->getFloat128Align(); 2155 } 2156 break; 2157 case BuiltinType::NullPtr: 2158 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t) 2159 Align = Target->getPointerAlign(0); // == sizeof(void*) 2160 break; 2161 case BuiltinType::ObjCId: 2162 case BuiltinType::ObjCClass: 2163 case BuiltinType::ObjCSel: 2164 Width = Target->getPointerWidth(0); 2165 Align = Target->getPointerAlign(0); 2166 break; 2167 case BuiltinType::OCLSampler: 2168 case BuiltinType::OCLEvent: 2169 case BuiltinType::OCLClkEvent: 2170 case BuiltinType::OCLQueue: 2171 case BuiltinType::OCLReserveID: 2172 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 2173 case BuiltinType::Id: 2174 #include "clang/Basic/OpenCLImageTypes.def" 2175 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 2176 case BuiltinType::Id: 2177 #include "clang/Basic/OpenCLExtensionTypes.def" 2178 AS = getTargetAddressSpace( 2179 Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T))); 2180 Width = Target->getPointerWidth(AS); 2181 Align = Target->getPointerAlign(AS); 2182 break; 2183 // The SVE types are effectively target-specific. The length of an 2184 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple 2185 // of 128 bits. There is one predicate bit for each vector byte, so the 2186 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits. 2187 // 2188 // Because the length is only known at runtime, we use a dummy value 2189 // of 0 for the static length. The alignment values are those defined 2190 // by the Procedure Call Standard for the Arm Architecture. 2191 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \ 2192 IsSigned, IsFP, IsBF) \ 2193 case BuiltinType::Id: \ 2194 Width = 0; \ 2195 Align = 128; \ 2196 break; 2197 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \ 2198 case BuiltinType::Id: \ 2199 Width = 0; \ 2200 Align = 16; \ 2201 break; 2202 #include "clang/Basic/AArch64SVEACLETypes.def" 2203 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 2204 case BuiltinType::Id: \ 2205 Width = Size; \ 2206 Align = Size; \ 2207 break; 2208 #include "clang/Basic/PPCTypes.def" 2209 #define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \ 2210 IsFP) \ 2211 case BuiltinType::Id: \ 2212 Width = 0; \ 2213 Align = ElBits; \ 2214 break; 2215 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \ 2216 case BuiltinType::Id: \ 2217 Width = 0; \ 2218 Align = 8; \ 2219 break; 2220 #include "clang/Basic/RISCVVTypes.def" 2221 } 2222 break; 2223 case Type::ObjCObjectPointer: 2224 Width = Target->getPointerWidth(0); 2225 Align = Target->getPointerAlign(0); 2226 break; 2227 case Type::BlockPointer: 2228 AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType()); 2229 Width = Target->getPointerWidth(AS); 2230 Align = Target->getPointerAlign(AS); 2231 break; 2232 case Type::LValueReference: 2233 case Type::RValueReference: 2234 // alignof and sizeof should never enter this code path here, so we go 2235 // the pointer route. 2236 AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType()); 2237 Width = Target->getPointerWidth(AS); 2238 Align = Target->getPointerAlign(AS); 2239 break; 2240 case Type::Pointer: 2241 AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType()); 2242 Width = Target->getPointerWidth(AS); 2243 Align = Target->getPointerAlign(AS); 2244 break; 2245 case Type::MemberPointer: { 2246 const auto *MPT = cast<MemberPointerType>(T); 2247 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT); 2248 Width = MPI.Width; 2249 Align = MPI.Align; 2250 break; 2251 } 2252 case Type::Complex: { 2253 // Complex types have the same alignment as their elements, but twice the 2254 // size. 2255 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType()); 2256 Width = EltInfo.Width * 2; 2257 Align = EltInfo.Align; 2258 break; 2259 } 2260 case Type::ObjCObject: 2261 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr()); 2262 case Type::Adjusted: 2263 case Type::Decayed: 2264 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr()); 2265 case Type::ObjCInterface: { 2266 const auto *ObjCI = cast<ObjCInterfaceType>(T); 2267 if (ObjCI->getDecl()->isInvalidDecl()) { 2268 Width = 8; 2269 Align = 8; 2270 break; 2271 } 2272 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 2273 Width = toBits(Layout.getSize()); 2274 Align = toBits(Layout.getAlignment()); 2275 break; 2276 } 2277 case Type::ExtInt: { 2278 const auto *EIT = cast<ExtIntType>(T); 2279 Align = 2280 std::min(static_cast<unsigned>(std::max( 2281 getCharWidth(), llvm::PowerOf2Ceil(EIT->getNumBits()))), 2282 Target->getLongLongAlign()); 2283 Width = llvm::alignTo(EIT->getNumBits(), Align); 2284 break; 2285 } 2286 case Type::Record: 2287 case Type::Enum: { 2288 const auto *TT = cast<TagType>(T); 2289 2290 if (TT->getDecl()->isInvalidDecl()) { 2291 Width = 8; 2292 Align = 8; 2293 break; 2294 } 2295 2296 if (const auto *ET = dyn_cast<EnumType>(TT)) { 2297 const EnumDecl *ED = ET->getDecl(); 2298 TypeInfo Info = 2299 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType()); 2300 if (unsigned AttrAlign = ED->getMaxAlignment()) { 2301 Info.Align = AttrAlign; 2302 Info.AlignIsRequired = true; 2303 } 2304 return Info; 2305 } 2306 2307 const auto *RT = cast<RecordType>(TT); 2308 const RecordDecl *RD = RT->getDecl(); 2309 const ASTRecordLayout &Layout = getASTRecordLayout(RD); 2310 Width = toBits(Layout.getSize()); 2311 Align = toBits(Layout.getAlignment()); 2312 AlignIsRequired = RD->hasAttr<AlignedAttr>(); 2313 break; 2314 } 2315 2316 case Type::SubstTemplateTypeParm: 2317 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)-> 2318 getReplacementType().getTypePtr()); 2319 2320 case Type::Auto: 2321 case Type::DeducedTemplateSpecialization: { 2322 const auto *A = cast<DeducedType>(T); 2323 assert(!A->getDeducedType().isNull() && 2324 "cannot request the size of an undeduced or dependent auto type"); 2325 return getTypeInfo(A->getDeducedType().getTypePtr()); 2326 } 2327 2328 case Type::Paren: 2329 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr()); 2330 2331 case Type::MacroQualified: 2332 return getTypeInfo( 2333 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr()); 2334 2335 case Type::ObjCTypeParam: 2336 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr()); 2337 2338 case Type::Typedef: { 2339 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl(); 2340 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr()); 2341 // If the typedef has an aligned attribute on it, it overrides any computed 2342 // alignment we have. This violates the GCC documentation (which says that 2343 // attribute(aligned) can only round up) but matches its implementation. 2344 if (unsigned AttrAlign = Typedef->getMaxAlignment()) { 2345 Align = AttrAlign; 2346 AlignIsRequired = true; 2347 } else { 2348 Align = Info.Align; 2349 AlignIsRequired = Info.AlignIsRequired; 2350 } 2351 Width = Info.Width; 2352 break; 2353 } 2354 2355 case Type::Elaborated: 2356 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr()); 2357 2358 case Type::Attributed: 2359 return getTypeInfo( 2360 cast<AttributedType>(T)->getEquivalentType().getTypePtr()); 2361 2362 case Type::Atomic: { 2363 // Start with the base type information. 2364 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType()); 2365 Width = Info.Width; 2366 Align = Info.Align; 2367 2368 if (!Width) { 2369 // An otherwise zero-sized type should still generate an 2370 // atomic operation. 2371 Width = Target->getCharWidth(); 2372 assert(Align); 2373 } else if (Width <= Target->getMaxAtomicPromoteWidth()) { 2374 // If the size of the type doesn't exceed the platform's max 2375 // atomic promotion width, make the size and alignment more 2376 // favorable to atomic operations: 2377 2378 // Round the size up to a power of 2. 2379 if (!llvm::isPowerOf2_64(Width)) 2380 Width = llvm::NextPowerOf2(Width); 2381 2382 // Set the alignment equal to the size. 2383 Align = static_cast<unsigned>(Width); 2384 } 2385 } 2386 break; 2387 2388 case Type::Pipe: 2389 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global)); 2390 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global)); 2391 break; 2392 } 2393 2394 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2"); 2395 return TypeInfo(Width, Align, AlignIsRequired); 2396 } 2397 2398 unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const { 2399 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T); 2400 if (I != MemoizedUnadjustedAlign.end()) 2401 return I->second; 2402 2403 unsigned UnadjustedAlign; 2404 if (const auto *RT = T->getAs<RecordType>()) { 2405 const RecordDecl *RD = RT->getDecl(); 2406 const ASTRecordLayout &Layout = getASTRecordLayout(RD); 2407 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment()); 2408 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) { 2409 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 2410 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment()); 2411 } else { 2412 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType()); 2413 } 2414 2415 MemoizedUnadjustedAlign[T] = UnadjustedAlign; 2416 return UnadjustedAlign; 2417 } 2418 2419 unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const { 2420 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign(); 2421 return SimdAlign; 2422 } 2423 2424 /// toCharUnitsFromBits - Convert a size in bits to a size in characters. 2425 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const { 2426 return CharUnits::fromQuantity(BitSize / getCharWidth()); 2427 } 2428 2429 /// toBits - Convert a size in characters to a size in characters. 2430 int64_t ASTContext::toBits(CharUnits CharSize) const { 2431 return CharSize.getQuantity() * getCharWidth(); 2432 } 2433 2434 /// getTypeSizeInChars - Return the size of the specified type, in characters. 2435 /// This method does not work on incomplete types. 2436 CharUnits ASTContext::getTypeSizeInChars(QualType T) const { 2437 return getTypeInfoInChars(T).Width; 2438 } 2439 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const { 2440 return getTypeInfoInChars(T).Width; 2441 } 2442 2443 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in 2444 /// characters. This method does not work on incomplete types. 2445 CharUnits ASTContext::getTypeAlignInChars(QualType T) const { 2446 return toCharUnitsFromBits(getTypeAlign(T)); 2447 } 2448 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const { 2449 return toCharUnitsFromBits(getTypeAlign(T)); 2450 } 2451 2452 /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a 2453 /// type, in characters, before alignment adustments. This method does 2454 /// not work on incomplete types. 2455 CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const { 2456 return toCharUnitsFromBits(getTypeUnadjustedAlign(T)); 2457 } 2458 CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const { 2459 return toCharUnitsFromBits(getTypeUnadjustedAlign(T)); 2460 } 2461 2462 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified 2463 /// type for the current target in bits. This can be different than the ABI 2464 /// alignment in cases where it is beneficial for performance or backwards 2465 /// compatibility preserving to overalign a data type. (Note: despite the name, 2466 /// the preferred alignment is ABI-impacting, and not an optimization.) 2467 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const { 2468 TypeInfo TI = getTypeInfo(T); 2469 unsigned ABIAlign = TI.Align; 2470 2471 T = T->getBaseElementTypeUnsafe(); 2472 2473 // The preferred alignment of member pointers is that of a pointer. 2474 if (T->isMemberPointerType()) 2475 return getPreferredTypeAlign(getPointerDiffType().getTypePtr()); 2476 2477 if (!Target->allowsLargerPreferedTypeAlignment()) 2478 return ABIAlign; 2479 2480 if (const auto *RT = T->getAs<RecordType>()) { 2481 const RecordDecl *RD = RT->getDecl(); 2482 2483 // When used as part of a typedef, or together with a 'packed' attribute, 2484 // the 'aligned' attribute can be used to decrease alignment. 2485 if ((TI.AlignIsRequired && T->getAs<TypedefType>() != nullptr) || 2486 RD->isInvalidDecl()) 2487 return ABIAlign; 2488 2489 unsigned PreferredAlign = static_cast<unsigned>( 2490 toBits(getASTRecordLayout(RD).PreferredAlignment)); 2491 assert(PreferredAlign >= ABIAlign && 2492 "PreferredAlign should be at least as large as ABIAlign."); 2493 return PreferredAlign; 2494 } 2495 2496 // Double (and, for targets supporting AIX `power` alignment, long double) and 2497 // long long should be naturally aligned (despite requiring less alignment) if 2498 // possible. 2499 if (const auto *CT = T->getAs<ComplexType>()) 2500 T = CT->getElementType().getTypePtr(); 2501 if (const auto *ET = T->getAs<EnumType>()) 2502 T = ET->getDecl()->getIntegerType().getTypePtr(); 2503 if (T->isSpecificBuiltinType(BuiltinType::Double) || 2504 T->isSpecificBuiltinType(BuiltinType::LongLong) || 2505 T->isSpecificBuiltinType(BuiltinType::ULongLong) || 2506 (T->isSpecificBuiltinType(BuiltinType::LongDouble) && 2507 Target->defaultsToAIXPowerAlignment())) 2508 // Don't increase the alignment if an alignment attribute was specified on a 2509 // typedef declaration. 2510 if (!TI.AlignIsRequired) 2511 return std::max(ABIAlign, (unsigned)getTypeSize(T)); 2512 2513 return ABIAlign; 2514 } 2515 2516 /// getTargetDefaultAlignForAttributeAligned - Return the default alignment 2517 /// for __attribute__((aligned)) on this target, to be used if no alignment 2518 /// value is specified. 2519 unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const { 2520 return getTargetInfo().getDefaultAlignForAttributeAligned(); 2521 } 2522 2523 /// getAlignOfGlobalVar - Return the alignment in bits that should be given 2524 /// to a global variable of the specified type. 2525 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const { 2526 uint64_t TypeSize = getTypeSize(T.getTypePtr()); 2527 return std::max(getPreferredTypeAlign(T), 2528 getTargetInfo().getMinGlobalAlign(TypeSize)); 2529 } 2530 2531 /// getAlignOfGlobalVarInChars - Return the alignment in characters that 2532 /// should be given to a global variable of the specified type. 2533 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const { 2534 return toCharUnitsFromBits(getAlignOfGlobalVar(T)); 2535 } 2536 2537 CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const { 2538 CharUnits Offset = CharUnits::Zero(); 2539 const ASTRecordLayout *Layout = &getASTRecordLayout(RD); 2540 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) { 2541 Offset += Layout->getBaseClassOffset(Base); 2542 Layout = &getASTRecordLayout(Base); 2543 } 2544 return Offset; 2545 } 2546 2547 CharUnits ASTContext::getMemberPointerPathAdjustment(const APValue &MP) const { 2548 const ValueDecl *MPD = MP.getMemberPointerDecl(); 2549 CharUnits ThisAdjustment = CharUnits::Zero(); 2550 ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath(); 2551 bool DerivedMember = MP.isMemberPointerToDerivedMember(); 2552 const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext()); 2553 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 2554 const CXXRecordDecl *Base = RD; 2555 const CXXRecordDecl *Derived = Path[I]; 2556 if (DerivedMember) 2557 std::swap(Base, Derived); 2558 ThisAdjustment += getASTRecordLayout(Derived).getBaseClassOffset(Base); 2559 RD = Path[I]; 2560 } 2561 if (DerivedMember) 2562 ThisAdjustment = -ThisAdjustment; 2563 return ThisAdjustment; 2564 } 2565 2566 /// DeepCollectObjCIvars - 2567 /// This routine first collects all declared, but not synthesized, ivars in 2568 /// super class and then collects all ivars, including those synthesized for 2569 /// current class. This routine is used for implementation of current class 2570 /// when all ivars, declared and synthesized are known. 2571 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, 2572 bool leafClass, 2573 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const { 2574 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass()) 2575 DeepCollectObjCIvars(SuperClass, false, Ivars); 2576 if (!leafClass) { 2577 for (const auto *I : OI->ivars()) 2578 Ivars.push_back(I); 2579 } else { 2580 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI); 2581 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv; 2582 Iv= Iv->getNextIvar()) 2583 Ivars.push_back(Iv); 2584 } 2585 } 2586 2587 /// CollectInheritedProtocols - Collect all protocols in current class and 2588 /// those inherited by it. 2589 void ASTContext::CollectInheritedProtocols(const Decl *CDecl, 2590 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) { 2591 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) { 2592 // We can use protocol_iterator here instead of 2593 // all_referenced_protocol_iterator since we are walking all categories. 2594 for (auto *Proto : OI->all_referenced_protocols()) { 2595 CollectInheritedProtocols(Proto, Protocols); 2596 } 2597 2598 // Categories of this Interface. 2599 for (const auto *Cat : OI->visible_categories()) 2600 CollectInheritedProtocols(Cat, Protocols); 2601 2602 if (ObjCInterfaceDecl *SD = OI->getSuperClass()) 2603 while (SD) { 2604 CollectInheritedProtocols(SD, Protocols); 2605 SD = SD->getSuperClass(); 2606 } 2607 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) { 2608 for (auto *Proto : OC->protocols()) { 2609 CollectInheritedProtocols(Proto, Protocols); 2610 } 2611 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) { 2612 // Insert the protocol. 2613 if (!Protocols.insert( 2614 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second) 2615 return; 2616 2617 for (auto *Proto : OP->protocols()) 2618 CollectInheritedProtocols(Proto, Protocols); 2619 } 2620 } 2621 2622 static bool unionHasUniqueObjectRepresentations(const ASTContext &Context, 2623 const RecordDecl *RD) { 2624 assert(RD->isUnion() && "Must be union type"); 2625 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl()); 2626 2627 for (const auto *Field : RD->fields()) { 2628 if (!Context.hasUniqueObjectRepresentations(Field->getType())) 2629 return false; 2630 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType()); 2631 if (FieldSize != UnionSize) 2632 return false; 2633 } 2634 return !RD->field_empty(); 2635 } 2636 2637 static bool isStructEmpty(QualType Ty) { 2638 const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl(); 2639 2640 if (!RD->field_empty()) 2641 return false; 2642 2643 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) 2644 return ClassDecl->isEmpty(); 2645 2646 return true; 2647 } 2648 2649 static llvm::Optional<int64_t> 2650 structHasUniqueObjectRepresentations(const ASTContext &Context, 2651 const RecordDecl *RD) { 2652 assert(!RD->isUnion() && "Must be struct/class type"); 2653 const auto &Layout = Context.getASTRecordLayout(RD); 2654 2655 int64_t CurOffsetInBits = 0; 2656 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) { 2657 if (ClassDecl->isDynamicClass()) 2658 return llvm::None; 2659 2660 SmallVector<std::pair<QualType, int64_t>, 4> Bases; 2661 for (const auto &Base : ClassDecl->bases()) { 2662 // Empty types can be inherited from, and non-empty types can potentially 2663 // have tail padding, so just make sure there isn't an error. 2664 if (!isStructEmpty(Base.getType())) { 2665 llvm::Optional<int64_t> Size = structHasUniqueObjectRepresentations( 2666 Context, Base.getType()->castAs<RecordType>()->getDecl()); 2667 if (!Size) 2668 return llvm::None; 2669 Bases.emplace_back(Base.getType(), Size.getValue()); 2670 } 2671 } 2672 2673 llvm::sort(Bases, [&](const std::pair<QualType, int64_t> &L, 2674 const std::pair<QualType, int64_t> &R) { 2675 return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) < 2676 Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl()); 2677 }); 2678 2679 for (const auto &Base : Bases) { 2680 int64_t BaseOffset = Context.toBits( 2681 Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl())); 2682 int64_t BaseSize = Base.second; 2683 if (BaseOffset != CurOffsetInBits) 2684 return llvm::None; 2685 CurOffsetInBits = BaseOffset + BaseSize; 2686 } 2687 } 2688 2689 for (const auto *Field : RD->fields()) { 2690 if (!Field->getType()->isReferenceType() && 2691 !Context.hasUniqueObjectRepresentations(Field->getType())) 2692 return llvm::None; 2693 2694 int64_t FieldSizeInBits = 2695 Context.toBits(Context.getTypeSizeInChars(Field->getType())); 2696 if (Field->isBitField()) { 2697 int64_t BitfieldSize = Field->getBitWidthValue(Context); 2698 2699 if (BitfieldSize > FieldSizeInBits) 2700 return llvm::None; 2701 FieldSizeInBits = BitfieldSize; 2702 } 2703 2704 int64_t FieldOffsetInBits = Context.getFieldOffset(Field); 2705 2706 if (FieldOffsetInBits != CurOffsetInBits) 2707 return llvm::None; 2708 2709 CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits; 2710 } 2711 2712 return CurOffsetInBits; 2713 } 2714 2715 bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const { 2716 // C++17 [meta.unary.prop]: 2717 // The predicate condition for a template specialization 2718 // has_unique_object_representations<T> shall be 2719 // satisfied if and only if: 2720 // (9.1) - T is trivially copyable, and 2721 // (9.2) - any two objects of type T with the same value have the same 2722 // object representation, where two objects 2723 // of array or non-union class type are considered to have the same value 2724 // if their respective sequences of 2725 // direct subobjects have the same values, and two objects of union type 2726 // are considered to have the same 2727 // value if they have the same active member and the corresponding members 2728 // have the same value. 2729 // The set of scalar types for which this condition holds is 2730 // implementation-defined. [ Note: If a type has padding 2731 // bits, the condition does not hold; otherwise, the condition holds true 2732 // for unsigned integral types. -- end note ] 2733 assert(!Ty.isNull() && "Null QualType sent to unique object rep check"); 2734 2735 // Arrays are unique only if their element type is unique. 2736 if (Ty->isArrayType()) 2737 return hasUniqueObjectRepresentations(getBaseElementType(Ty)); 2738 2739 // (9.1) - T is trivially copyable... 2740 if (!Ty.isTriviallyCopyableType(*this)) 2741 return false; 2742 2743 // All integrals and enums are unique. 2744 if (Ty->isIntegralOrEnumerationType()) 2745 return true; 2746 2747 // All other pointers are unique. 2748 if (Ty->isPointerType()) 2749 return true; 2750 2751 if (Ty->isMemberPointerType()) { 2752 const auto *MPT = Ty->getAs<MemberPointerType>(); 2753 return !ABI->getMemberPointerInfo(MPT).HasPadding; 2754 } 2755 2756 if (Ty->isRecordType()) { 2757 const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl(); 2758 2759 if (Record->isInvalidDecl()) 2760 return false; 2761 2762 if (Record->isUnion()) 2763 return unionHasUniqueObjectRepresentations(*this, Record); 2764 2765 Optional<int64_t> StructSize = 2766 structHasUniqueObjectRepresentations(*this, Record); 2767 2768 return StructSize && 2769 StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty)); 2770 } 2771 2772 // FIXME: More cases to handle here (list by rsmith): 2773 // vectors (careful about, eg, vector of 3 foo) 2774 // _Complex int and friends 2775 // _Atomic T 2776 // Obj-C block pointers 2777 // Obj-C object pointers 2778 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t, 2779 // clk_event_t, queue_t, reserve_id_t) 2780 // There're also Obj-C class types and the Obj-C selector type, but I think it 2781 // makes sense for those to return false here. 2782 2783 return false; 2784 } 2785 2786 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const { 2787 unsigned count = 0; 2788 // Count ivars declared in class extension. 2789 for (const auto *Ext : OI->known_extensions()) 2790 count += Ext->ivar_size(); 2791 2792 // Count ivar defined in this class's implementation. This 2793 // includes synthesized ivars. 2794 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) 2795 count += ImplDecl->ivar_size(); 2796 2797 return count; 2798 } 2799 2800 bool ASTContext::isSentinelNullExpr(const Expr *E) { 2801 if (!E) 2802 return false; 2803 2804 // nullptr_t is always treated as null. 2805 if (E->getType()->isNullPtrType()) return true; 2806 2807 if (E->getType()->isAnyPointerType() && 2808 E->IgnoreParenCasts()->isNullPointerConstant(*this, 2809 Expr::NPC_ValueDependentIsNull)) 2810 return true; 2811 2812 // Unfortunately, __null has type 'int'. 2813 if (isa<GNUNullExpr>(E)) return true; 2814 2815 return false; 2816 } 2817 2818 /// Get the implementation of ObjCInterfaceDecl, or nullptr if none 2819 /// exists. 2820 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) { 2821 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 2822 I = ObjCImpls.find(D); 2823 if (I != ObjCImpls.end()) 2824 return cast<ObjCImplementationDecl>(I->second); 2825 return nullptr; 2826 } 2827 2828 /// Get the implementation of ObjCCategoryDecl, or nullptr if none 2829 /// exists. 2830 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) { 2831 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 2832 I = ObjCImpls.find(D); 2833 if (I != ObjCImpls.end()) 2834 return cast<ObjCCategoryImplDecl>(I->second); 2835 return nullptr; 2836 } 2837 2838 /// Set the implementation of ObjCInterfaceDecl. 2839 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD, 2840 ObjCImplementationDecl *ImplD) { 2841 assert(IFaceD && ImplD && "Passed null params"); 2842 ObjCImpls[IFaceD] = ImplD; 2843 } 2844 2845 /// Set the implementation of ObjCCategoryDecl. 2846 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD, 2847 ObjCCategoryImplDecl *ImplD) { 2848 assert(CatD && ImplD && "Passed null params"); 2849 ObjCImpls[CatD] = ImplD; 2850 } 2851 2852 const ObjCMethodDecl * 2853 ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const { 2854 return ObjCMethodRedecls.lookup(MD); 2855 } 2856 2857 void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD, 2858 const ObjCMethodDecl *Redecl) { 2859 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration"); 2860 ObjCMethodRedecls[MD] = Redecl; 2861 } 2862 2863 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface( 2864 const NamedDecl *ND) const { 2865 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext())) 2866 return ID; 2867 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext())) 2868 return CD->getClassInterface(); 2869 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext())) 2870 return IMD->getClassInterface(); 2871 2872 return nullptr; 2873 } 2874 2875 /// Get the copy initialization expression of VarDecl, or nullptr if 2876 /// none exists. 2877 BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const { 2878 assert(VD && "Passed null params"); 2879 assert(VD->hasAttr<BlocksAttr>() && 2880 "getBlockVarCopyInits - not __block var"); 2881 auto I = BlockVarCopyInits.find(VD); 2882 if (I != BlockVarCopyInits.end()) 2883 return I->second; 2884 return {nullptr, false}; 2885 } 2886 2887 /// Set the copy initialization expression of a block var decl. 2888 void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr, 2889 bool CanThrow) { 2890 assert(VD && CopyExpr && "Passed null params"); 2891 assert(VD->hasAttr<BlocksAttr>() && 2892 "setBlockVarCopyInits - not __block var"); 2893 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow); 2894 } 2895 2896 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T, 2897 unsigned DataSize) const { 2898 if (!DataSize) 2899 DataSize = TypeLoc::getFullDataSizeForType(T); 2900 else 2901 assert(DataSize == TypeLoc::getFullDataSizeForType(T) && 2902 "incorrect data size provided to CreateTypeSourceInfo!"); 2903 2904 auto *TInfo = 2905 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8); 2906 new (TInfo) TypeSourceInfo(T); 2907 return TInfo; 2908 } 2909 2910 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T, 2911 SourceLocation L) const { 2912 TypeSourceInfo *DI = CreateTypeSourceInfo(T); 2913 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L); 2914 return DI; 2915 } 2916 2917 const ASTRecordLayout & 2918 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const { 2919 return getObjCLayout(D, nullptr); 2920 } 2921 2922 const ASTRecordLayout & 2923 ASTContext::getASTObjCImplementationLayout( 2924 const ObjCImplementationDecl *D) const { 2925 return getObjCLayout(D->getClassInterface(), D); 2926 } 2927 2928 //===----------------------------------------------------------------------===// 2929 // Type creation/memoization methods 2930 //===----------------------------------------------------------------------===// 2931 2932 QualType 2933 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const { 2934 unsigned fastQuals = quals.getFastQualifiers(); 2935 quals.removeFastQualifiers(); 2936 2937 // Check if we've already instantiated this type. 2938 llvm::FoldingSetNodeID ID; 2939 ExtQuals::Profile(ID, baseType, quals); 2940 void *insertPos = nullptr; 2941 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) { 2942 assert(eq->getQualifiers() == quals); 2943 return QualType(eq, fastQuals); 2944 } 2945 2946 // If the base type is not canonical, make the appropriate canonical type. 2947 QualType canon; 2948 if (!baseType->isCanonicalUnqualified()) { 2949 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split(); 2950 canonSplit.Quals.addConsistentQualifiers(quals); 2951 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals); 2952 2953 // Re-find the insert position. 2954 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos); 2955 } 2956 2957 auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals); 2958 ExtQualNodes.InsertNode(eq, insertPos); 2959 return QualType(eq, fastQuals); 2960 } 2961 2962 QualType ASTContext::getAddrSpaceQualType(QualType T, 2963 LangAS AddressSpace) const { 2964 QualType CanT = getCanonicalType(T); 2965 if (CanT.getAddressSpace() == AddressSpace) 2966 return T; 2967 2968 // If we are composing extended qualifiers together, merge together 2969 // into one ExtQuals node. 2970 QualifierCollector Quals; 2971 const Type *TypeNode = Quals.strip(T); 2972 2973 // If this type already has an address space specified, it cannot get 2974 // another one. 2975 assert(!Quals.hasAddressSpace() && 2976 "Type cannot be in multiple addr spaces!"); 2977 Quals.addAddressSpace(AddressSpace); 2978 2979 return getExtQualType(TypeNode, Quals); 2980 } 2981 2982 QualType ASTContext::removeAddrSpaceQualType(QualType T) const { 2983 // If the type is not qualified with an address space, just return it 2984 // immediately. 2985 if (!T.hasAddressSpace()) 2986 return T; 2987 2988 // If we are composing extended qualifiers together, merge together 2989 // into one ExtQuals node. 2990 QualifierCollector Quals; 2991 const Type *TypeNode; 2992 2993 while (T.hasAddressSpace()) { 2994 TypeNode = Quals.strip(T); 2995 2996 // If the type no longer has an address space after stripping qualifiers, 2997 // jump out. 2998 if (!QualType(TypeNode, 0).hasAddressSpace()) 2999 break; 3000 3001 // There might be sugar in the way. Strip it and try again. 3002 T = T.getSingleStepDesugaredType(*this); 3003 } 3004 3005 Quals.removeAddressSpace(); 3006 3007 // Removal of the address space can mean there are no longer any 3008 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts) 3009 // or required. 3010 if (Quals.hasNonFastQualifiers()) 3011 return getExtQualType(TypeNode, Quals); 3012 else 3013 return QualType(TypeNode, Quals.getFastQualifiers()); 3014 } 3015 3016 QualType ASTContext::getObjCGCQualType(QualType T, 3017 Qualifiers::GC GCAttr) const { 3018 QualType CanT = getCanonicalType(T); 3019 if (CanT.getObjCGCAttr() == GCAttr) 3020 return T; 3021 3022 if (const auto *ptr = T->getAs<PointerType>()) { 3023 QualType Pointee = ptr->getPointeeType(); 3024 if (Pointee->isAnyPointerType()) { 3025 QualType ResultType = getObjCGCQualType(Pointee, GCAttr); 3026 return getPointerType(ResultType); 3027 } 3028 } 3029 3030 // If we are composing extended qualifiers together, merge together 3031 // into one ExtQuals node. 3032 QualifierCollector Quals; 3033 const Type *TypeNode = Quals.strip(T); 3034 3035 // If this type already has an ObjCGC specified, it cannot get 3036 // another one. 3037 assert(!Quals.hasObjCGCAttr() && 3038 "Type cannot have multiple ObjCGCs!"); 3039 Quals.addObjCGCAttr(GCAttr); 3040 3041 return getExtQualType(TypeNode, Quals); 3042 } 3043 3044 QualType ASTContext::removePtrSizeAddrSpace(QualType T) const { 3045 if (const PointerType *Ptr = T->getAs<PointerType>()) { 3046 QualType Pointee = Ptr->getPointeeType(); 3047 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) { 3048 return getPointerType(removeAddrSpaceQualType(Pointee)); 3049 } 3050 } 3051 return T; 3052 } 3053 3054 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T, 3055 FunctionType::ExtInfo Info) { 3056 if (T->getExtInfo() == Info) 3057 return T; 3058 3059 QualType Result; 3060 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) { 3061 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info); 3062 } else { 3063 const auto *FPT = cast<FunctionProtoType>(T); 3064 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 3065 EPI.ExtInfo = Info; 3066 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI); 3067 } 3068 3069 return cast<FunctionType>(Result.getTypePtr()); 3070 } 3071 3072 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD, 3073 QualType ResultType) { 3074 FD = FD->getMostRecentDecl(); 3075 while (true) { 3076 const auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 3077 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 3078 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI)); 3079 if (FunctionDecl *Next = FD->getPreviousDecl()) 3080 FD = Next; 3081 else 3082 break; 3083 } 3084 if (ASTMutationListener *L = getASTMutationListener()) 3085 L->DeducedReturnType(FD, ResultType); 3086 } 3087 3088 /// Get a function type and produce the equivalent function type with the 3089 /// specified exception specification. Type sugar that can be present on a 3090 /// declaration of a function with an exception specification is permitted 3091 /// and preserved. Other type sugar (for instance, typedefs) is not. 3092 QualType ASTContext::getFunctionTypeWithExceptionSpec( 3093 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) { 3094 // Might have some parens. 3095 if (const auto *PT = dyn_cast<ParenType>(Orig)) 3096 return getParenType( 3097 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI)); 3098 3099 // Might be wrapped in a macro qualified type. 3100 if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig)) 3101 return getMacroQualifiedType( 3102 getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI), 3103 MQT->getMacroIdentifier()); 3104 3105 // Might have a calling-convention attribute. 3106 if (const auto *AT = dyn_cast<AttributedType>(Orig)) 3107 return getAttributedType( 3108 AT->getAttrKind(), 3109 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI), 3110 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI)); 3111 3112 // Anything else must be a function type. Rebuild it with the new exception 3113 // specification. 3114 const auto *Proto = Orig->castAs<FunctionProtoType>(); 3115 return getFunctionType( 3116 Proto->getReturnType(), Proto->getParamTypes(), 3117 Proto->getExtProtoInfo().withExceptionSpec(ESI)); 3118 } 3119 3120 bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T, 3121 QualType U) { 3122 return hasSameType(T, U) || 3123 (getLangOpts().CPlusPlus17 && 3124 hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None), 3125 getFunctionTypeWithExceptionSpec(U, EST_None))); 3126 } 3127 3128 QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) { 3129 if (const auto *Proto = T->getAs<FunctionProtoType>()) { 3130 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType()); 3131 SmallVector<QualType, 16> Args(Proto->param_types()); 3132 for (unsigned i = 0, n = Args.size(); i != n; ++i) 3133 Args[i] = removePtrSizeAddrSpace(Args[i]); 3134 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo()); 3135 } 3136 3137 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) { 3138 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType()); 3139 return getFunctionNoProtoType(RetTy, Proto->getExtInfo()); 3140 } 3141 3142 return T; 3143 } 3144 3145 bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) { 3146 return hasSameType(T, U) || 3147 hasSameType(getFunctionTypeWithoutPtrSizes(T), 3148 getFunctionTypeWithoutPtrSizes(U)); 3149 } 3150 3151 void ASTContext::adjustExceptionSpec( 3152 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, 3153 bool AsWritten) { 3154 // Update the type. 3155 QualType Updated = 3156 getFunctionTypeWithExceptionSpec(FD->getType(), ESI); 3157 FD->setType(Updated); 3158 3159 if (!AsWritten) 3160 return; 3161 3162 // Update the type in the type source information too. 3163 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) { 3164 // If the type and the type-as-written differ, we may need to update 3165 // the type-as-written too. 3166 if (TSInfo->getType() != FD->getType()) 3167 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI); 3168 3169 // FIXME: When we get proper type location information for exceptions, 3170 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch 3171 // up the TypeSourceInfo; 3172 assert(TypeLoc::getFullDataSizeForType(Updated) == 3173 TypeLoc::getFullDataSizeForType(TSInfo->getType()) && 3174 "TypeLoc size mismatch from updating exception specification"); 3175 TSInfo->overrideType(Updated); 3176 } 3177 } 3178 3179 /// getComplexType - Return the uniqued reference to the type for a complex 3180 /// number with the specified element type. 3181 QualType ASTContext::getComplexType(QualType T) const { 3182 // Unique pointers, to guarantee there is only one pointer of a particular 3183 // structure. 3184 llvm::FoldingSetNodeID ID; 3185 ComplexType::Profile(ID, T); 3186 3187 void *InsertPos = nullptr; 3188 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos)) 3189 return QualType(CT, 0); 3190 3191 // If the pointee type isn't canonical, this won't be a canonical type either, 3192 // so fill in the canonical type field. 3193 QualType Canonical; 3194 if (!T.isCanonical()) { 3195 Canonical = getComplexType(getCanonicalType(T)); 3196 3197 // Get the new insert position for the node we care about. 3198 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos); 3199 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3200 } 3201 auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical); 3202 Types.push_back(New); 3203 ComplexTypes.InsertNode(New, InsertPos); 3204 return QualType(New, 0); 3205 } 3206 3207 /// getPointerType - Return the uniqued reference to the type for a pointer to 3208 /// the specified type. 3209 QualType ASTContext::getPointerType(QualType T) const { 3210 // Unique pointers, to guarantee there is only one pointer of a particular 3211 // structure. 3212 llvm::FoldingSetNodeID ID; 3213 PointerType::Profile(ID, T); 3214 3215 void *InsertPos = nullptr; 3216 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3217 return QualType(PT, 0); 3218 3219 // If the pointee type isn't canonical, this won't be a canonical type either, 3220 // so fill in the canonical type field. 3221 QualType Canonical; 3222 if (!T.isCanonical()) { 3223 Canonical = getPointerType(getCanonicalType(T)); 3224 3225 // Get the new insert position for the node we care about. 3226 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3227 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3228 } 3229 auto *New = new (*this, TypeAlignment) PointerType(T, Canonical); 3230 Types.push_back(New); 3231 PointerTypes.InsertNode(New, InsertPos); 3232 return QualType(New, 0); 3233 } 3234 3235 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const { 3236 llvm::FoldingSetNodeID ID; 3237 AdjustedType::Profile(ID, Orig, New); 3238 void *InsertPos = nullptr; 3239 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3240 if (AT) 3241 return QualType(AT, 0); 3242 3243 QualType Canonical = getCanonicalType(New); 3244 3245 // Get the new insert position for the node we care about. 3246 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3247 assert(!AT && "Shouldn't be in the map!"); 3248 3249 AT = new (*this, TypeAlignment) 3250 AdjustedType(Type::Adjusted, Orig, New, Canonical); 3251 Types.push_back(AT); 3252 AdjustedTypes.InsertNode(AT, InsertPos); 3253 return QualType(AT, 0); 3254 } 3255 3256 QualType ASTContext::getDecayedType(QualType T) const { 3257 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay"); 3258 3259 QualType Decayed; 3260 3261 // C99 6.7.5.3p7: 3262 // A declaration of a parameter as "array of type" shall be 3263 // adjusted to "qualified pointer to type", where the type 3264 // qualifiers (if any) are those specified within the [ and ] of 3265 // the array type derivation. 3266 if (T->isArrayType()) 3267 Decayed = getArrayDecayedType(T); 3268 3269 // C99 6.7.5.3p8: 3270 // A declaration of a parameter as "function returning type" 3271 // shall be adjusted to "pointer to function returning type", as 3272 // in 6.3.2.1. 3273 if (T->isFunctionType()) 3274 Decayed = getPointerType(T); 3275 3276 llvm::FoldingSetNodeID ID; 3277 AdjustedType::Profile(ID, T, Decayed); 3278 void *InsertPos = nullptr; 3279 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3280 if (AT) 3281 return QualType(AT, 0); 3282 3283 QualType Canonical = getCanonicalType(Decayed); 3284 3285 // Get the new insert position for the node we care about. 3286 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3287 assert(!AT && "Shouldn't be in the map!"); 3288 3289 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical); 3290 Types.push_back(AT); 3291 AdjustedTypes.InsertNode(AT, InsertPos); 3292 return QualType(AT, 0); 3293 } 3294 3295 /// getBlockPointerType - Return the uniqued reference to the type for 3296 /// a pointer to the specified block. 3297 QualType ASTContext::getBlockPointerType(QualType T) const { 3298 assert(T->isFunctionType() && "block of function types only"); 3299 // Unique pointers, to guarantee there is only one block of a particular 3300 // structure. 3301 llvm::FoldingSetNodeID ID; 3302 BlockPointerType::Profile(ID, T); 3303 3304 void *InsertPos = nullptr; 3305 if (BlockPointerType *PT = 3306 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3307 return QualType(PT, 0); 3308 3309 // If the block pointee type isn't canonical, this won't be a canonical 3310 // type either so fill in the canonical type field. 3311 QualType Canonical; 3312 if (!T.isCanonical()) { 3313 Canonical = getBlockPointerType(getCanonicalType(T)); 3314 3315 // Get the new insert position for the node we care about. 3316 BlockPointerType *NewIP = 3317 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3318 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3319 } 3320 auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical); 3321 Types.push_back(New); 3322 BlockPointerTypes.InsertNode(New, InsertPos); 3323 return QualType(New, 0); 3324 } 3325 3326 /// getLValueReferenceType - Return the uniqued reference to the type for an 3327 /// lvalue reference to the specified type. 3328 QualType 3329 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const { 3330 assert(getCanonicalType(T) != OverloadTy && 3331 "Unresolved overloaded function type"); 3332 3333 // Unique pointers, to guarantee there is only one pointer of a particular 3334 // structure. 3335 llvm::FoldingSetNodeID ID; 3336 ReferenceType::Profile(ID, T, SpelledAsLValue); 3337 3338 void *InsertPos = nullptr; 3339 if (LValueReferenceType *RT = 3340 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 3341 return QualType(RT, 0); 3342 3343 const auto *InnerRef = T->getAs<ReferenceType>(); 3344 3345 // If the referencee type isn't canonical, this won't be a canonical type 3346 // either, so fill in the canonical type field. 3347 QualType Canonical; 3348 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) { 3349 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 3350 Canonical = getLValueReferenceType(getCanonicalType(PointeeType)); 3351 3352 // Get the new insert position for the node we care about. 3353 LValueReferenceType *NewIP = 3354 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 3355 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3356 } 3357 3358 auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical, 3359 SpelledAsLValue); 3360 Types.push_back(New); 3361 LValueReferenceTypes.InsertNode(New, InsertPos); 3362 3363 return QualType(New, 0); 3364 } 3365 3366 /// getRValueReferenceType - Return the uniqued reference to the type for an 3367 /// rvalue reference to the specified type. 3368 QualType ASTContext::getRValueReferenceType(QualType T) const { 3369 // Unique pointers, to guarantee there is only one pointer of a particular 3370 // structure. 3371 llvm::FoldingSetNodeID ID; 3372 ReferenceType::Profile(ID, T, false); 3373 3374 void *InsertPos = nullptr; 3375 if (RValueReferenceType *RT = 3376 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 3377 return QualType(RT, 0); 3378 3379 const auto *InnerRef = T->getAs<ReferenceType>(); 3380 3381 // If the referencee type isn't canonical, this won't be a canonical type 3382 // either, so fill in the canonical type field. 3383 QualType Canonical; 3384 if (InnerRef || !T.isCanonical()) { 3385 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 3386 Canonical = getRValueReferenceType(getCanonicalType(PointeeType)); 3387 3388 // Get the new insert position for the node we care about. 3389 RValueReferenceType *NewIP = 3390 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 3391 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3392 } 3393 3394 auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical); 3395 Types.push_back(New); 3396 RValueReferenceTypes.InsertNode(New, InsertPos); 3397 return QualType(New, 0); 3398 } 3399 3400 /// getMemberPointerType - Return the uniqued reference to the type for a 3401 /// member pointer to the specified type, in the specified class. 3402 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const { 3403 // Unique pointers, to guarantee there is only one pointer of a particular 3404 // structure. 3405 llvm::FoldingSetNodeID ID; 3406 MemberPointerType::Profile(ID, T, Cls); 3407 3408 void *InsertPos = nullptr; 3409 if (MemberPointerType *PT = 3410 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3411 return QualType(PT, 0); 3412 3413 // If the pointee or class type isn't canonical, this won't be a canonical 3414 // type either, so fill in the canonical type field. 3415 QualType Canonical; 3416 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) { 3417 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls)); 3418 3419 // Get the new insert position for the node we care about. 3420 MemberPointerType *NewIP = 3421 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3422 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3423 } 3424 auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical); 3425 Types.push_back(New); 3426 MemberPointerTypes.InsertNode(New, InsertPos); 3427 return QualType(New, 0); 3428 } 3429 3430 /// getConstantArrayType - Return the unique reference to the type for an 3431 /// array of the specified element type. 3432 QualType ASTContext::getConstantArrayType(QualType EltTy, 3433 const llvm::APInt &ArySizeIn, 3434 const Expr *SizeExpr, 3435 ArrayType::ArraySizeModifier ASM, 3436 unsigned IndexTypeQuals) const { 3437 assert((EltTy->isDependentType() || 3438 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) && 3439 "Constant array of VLAs is illegal!"); 3440 3441 // We only need the size as part of the type if it's instantiation-dependent. 3442 if (SizeExpr && !SizeExpr->isInstantiationDependent()) 3443 SizeExpr = nullptr; 3444 3445 // Convert the array size into a canonical width matching the pointer size for 3446 // the target. 3447 llvm::APInt ArySize(ArySizeIn); 3448 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth()); 3449 3450 llvm::FoldingSetNodeID ID; 3451 ConstantArrayType::Profile(ID, *this, EltTy, ArySize, SizeExpr, ASM, 3452 IndexTypeQuals); 3453 3454 void *InsertPos = nullptr; 3455 if (ConstantArrayType *ATP = 3456 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 3457 return QualType(ATP, 0); 3458 3459 // If the element type isn't canonical or has qualifiers, or the array bound 3460 // is instantiation-dependent, this won't be a canonical type either, so fill 3461 // in the canonical type field. 3462 QualType Canon; 3463 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) { 3464 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 3465 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr, 3466 ASM, IndexTypeQuals); 3467 Canon = getQualifiedType(Canon, canonSplit.Quals); 3468 3469 // Get the new insert position for the node we care about. 3470 ConstantArrayType *NewIP = 3471 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 3472 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3473 } 3474 3475 void *Mem = Allocate( 3476 ConstantArrayType::totalSizeToAlloc<const Expr *>(SizeExpr ? 1 : 0), 3477 TypeAlignment); 3478 auto *New = new (Mem) 3479 ConstantArrayType(EltTy, Canon, ArySize, SizeExpr, ASM, IndexTypeQuals); 3480 ConstantArrayTypes.InsertNode(New, InsertPos); 3481 Types.push_back(New); 3482 return QualType(New, 0); 3483 } 3484 3485 /// getVariableArrayDecayedType - Turns the given type, which may be 3486 /// variably-modified, into the corresponding type with all the known 3487 /// sizes replaced with [*]. 3488 QualType ASTContext::getVariableArrayDecayedType(QualType type) const { 3489 // Vastly most common case. 3490 if (!type->isVariablyModifiedType()) return type; 3491 3492 QualType result; 3493 3494 SplitQualType split = type.getSplitDesugaredType(); 3495 const Type *ty = split.Ty; 3496 switch (ty->getTypeClass()) { 3497 #define TYPE(Class, Base) 3498 #define ABSTRACT_TYPE(Class, Base) 3499 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 3500 #include "clang/AST/TypeNodes.inc" 3501 llvm_unreachable("didn't desugar past all non-canonical types?"); 3502 3503 // These types should never be variably-modified. 3504 case Type::Builtin: 3505 case Type::Complex: 3506 case Type::Vector: 3507 case Type::DependentVector: 3508 case Type::ExtVector: 3509 case Type::DependentSizedExtVector: 3510 case Type::ConstantMatrix: 3511 case Type::DependentSizedMatrix: 3512 case Type::DependentAddressSpace: 3513 case Type::ObjCObject: 3514 case Type::ObjCInterface: 3515 case Type::ObjCObjectPointer: 3516 case Type::Record: 3517 case Type::Enum: 3518 case Type::UnresolvedUsing: 3519 case Type::TypeOfExpr: 3520 case Type::TypeOf: 3521 case Type::Decltype: 3522 case Type::UnaryTransform: 3523 case Type::DependentName: 3524 case Type::InjectedClassName: 3525 case Type::TemplateSpecialization: 3526 case Type::DependentTemplateSpecialization: 3527 case Type::TemplateTypeParm: 3528 case Type::SubstTemplateTypeParmPack: 3529 case Type::Auto: 3530 case Type::DeducedTemplateSpecialization: 3531 case Type::PackExpansion: 3532 case Type::ExtInt: 3533 case Type::DependentExtInt: 3534 llvm_unreachable("type should never be variably-modified"); 3535 3536 // These types can be variably-modified but should never need to 3537 // further decay. 3538 case Type::FunctionNoProto: 3539 case Type::FunctionProto: 3540 case Type::BlockPointer: 3541 case Type::MemberPointer: 3542 case Type::Pipe: 3543 return type; 3544 3545 // These types can be variably-modified. All these modifications 3546 // preserve structure except as noted by comments. 3547 // TODO: if we ever care about optimizing VLAs, there are no-op 3548 // optimizations available here. 3549 case Type::Pointer: 3550 result = getPointerType(getVariableArrayDecayedType( 3551 cast<PointerType>(ty)->getPointeeType())); 3552 break; 3553 3554 case Type::LValueReference: { 3555 const auto *lv = cast<LValueReferenceType>(ty); 3556 result = getLValueReferenceType( 3557 getVariableArrayDecayedType(lv->getPointeeType()), 3558 lv->isSpelledAsLValue()); 3559 break; 3560 } 3561 3562 case Type::RValueReference: { 3563 const auto *lv = cast<RValueReferenceType>(ty); 3564 result = getRValueReferenceType( 3565 getVariableArrayDecayedType(lv->getPointeeType())); 3566 break; 3567 } 3568 3569 case Type::Atomic: { 3570 const auto *at = cast<AtomicType>(ty); 3571 result = getAtomicType(getVariableArrayDecayedType(at->getValueType())); 3572 break; 3573 } 3574 3575 case Type::ConstantArray: { 3576 const auto *cat = cast<ConstantArrayType>(ty); 3577 result = getConstantArrayType( 3578 getVariableArrayDecayedType(cat->getElementType()), 3579 cat->getSize(), 3580 cat->getSizeExpr(), 3581 cat->getSizeModifier(), 3582 cat->getIndexTypeCVRQualifiers()); 3583 break; 3584 } 3585 3586 case Type::DependentSizedArray: { 3587 const auto *dat = cast<DependentSizedArrayType>(ty); 3588 result = getDependentSizedArrayType( 3589 getVariableArrayDecayedType(dat->getElementType()), 3590 dat->getSizeExpr(), 3591 dat->getSizeModifier(), 3592 dat->getIndexTypeCVRQualifiers(), 3593 dat->getBracketsRange()); 3594 break; 3595 } 3596 3597 // Turn incomplete types into [*] types. 3598 case Type::IncompleteArray: { 3599 const auto *iat = cast<IncompleteArrayType>(ty); 3600 result = getVariableArrayType( 3601 getVariableArrayDecayedType(iat->getElementType()), 3602 /*size*/ nullptr, 3603 ArrayType::Normal, 3604 iat->getIndexTypeCVRQualifiers(), 3605 SourceRange()); 3606 break; 3607 } 3608 3609 // Turn VLA types into [*] types. 3610 case Type::VariableArray: { 3611 const auto *vat = cast<VariableArrayType>(ty); 3612 result = getVariableArrayType( 3613 getVariableArrayDecayedType(vat->getElementType()), 3614 /*size*/ nullptr, 3615 ArrayType::Star, 3616 vat->getIndexTypeCVRQualifiers(), 3617 vat->getBracketsRange()); 3618 break; 3619 } 3620 } 3621 3622 // Apply the top-level qualifiers from the original. 3623 return getQualifiedType(result, split.Quals); 3624 } 3625 3626 /// getVariableArrayType - Returns a non-unique reference to the type for a 3627 /// variable array of the specified element type. 3628 QualType ASTContext::getVariableArrayType(QualType EltTy, 3629 Expr *NumElts, 3630 ArrayType::ArraySizeModifier ASM, 3631 unsigned IndexTypeQuals, 3632 SourceRange Brackets) const { 3633 // Since we don't unique expressions, it isn't possible to unique VLA's 3634 // that have an expression provided for their size. 3635 QualType Canon; 3636 3637 // Be sure to pull qualifiers off the element type. 3638 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) { 3639 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 3640 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM, 3641 IndexTypeQuals, Brackets); 3642 Canon = getQualifiedType(Canon, canonSplit.Quals); 3643 } 3644 3645 auto *New = new (*this, TypeAlignment) 3646 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets); 3647 3648 VariableArrayTypes.push_back(New); 3649 Types.push_back(New); 3650 return QualType(New, 0); 3651 } 3652 3653 /// getDependentSizedArrayType - Returns a non-unique reference to 3654 /// the type for a dependently-sized array of the specified element 3655 /// type. 3656 QualType ASTContext::getDependentSizedArrayType(QualType elementType, 3657 Expr *numElements, 3658 ArrayType::ArraySizeModifier ASM, 3659 unsigned elementTypeQuals, 3660 SourceRange brackets) const { 3661 assert((!numElements || numElements->isTypeDependent() || 3662 numElements->isValueDependent()) && 3663 "Size must be type- or value-dependent!"); 3664 3665 // Dependently-sized array types that do not have a specified number 3666 // of elements will have their sizes deduced from a dependent 3667 // initializer. We do no canonicalization here at all, which is okay 3668 // because they can't be used in most locations. 3669 if (!numElements) { 3670 auto *newType 3671 = new (*this, TypeAlignment) 3672 DependentSizedArrayType(*this, elementType, QualType(), 3673 numElements, ASM, elementTypeQuals, 3674 brackets); 3675 Types.push_back(newType); 3676 return QualType(newType, 0); 3677 } 3678 3679 // Otherwise, we actually build a new type every time, but we 3680 // also build a canonical type. 3681 3682 SplitQualType canonElementType = getCanonicalType(elementType).split(); 3683 3684 void *insertPos = nullptr; 3685 llvm::FoldingSetNodeID ID; 3686 DependentSizedArrayType::Profile(ID, *this, 3687 QualType(canonElementType.Ty, 0), 3688 ASM, elementTypeQuals, numElements); 3689 3690 // Look for an existing type with these properties. 3691 DependentSizedArrayType *canonTy = 3692 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos); 3693 3694 // If we don't have one, build one. 3695 if (!canonTy) { 3696 canonTy = new (*this, TypeAlignment) 3697 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0), 3698 QualType(), numElements, ASM, elementTypeQuals, 3699 brackets); 3700 DependentSizedArrayTypes.InsertNode(canonTy, insertPos); 3701 Types.push_back(canonTy); 3702 } 3703 3704 // Apply qualifiers from the element type to the array. 3705 QualType canon = getQualifiedType(QualType(canonTy,0), 3706 canonElementType.Quals); 3707 3708 // If we didn't need extra canonicalization for the element type or the size 3709 // expression, then just use that as our result. 3710 if (QualType(canonElementType.Ty, 0) == elementType && 3711 canonTy->getSizeExpr() == numElements) 3712 return canon; 3713 3714 // Otherwise, we need to build a type which follows the spelling 3715 // of the element type. 3716 auto *sugaredType 3717 = new (*this, TypeAlignment) 3718 DependentSizedArrayType(*this, elementType, canon, numElements, 3719 ASM, elementTypeQuals, brackets); 3720 Types.push_back(sugaredType); 3721 return QualType(sugaredType, 0); 3722 } 3723 3724 QualType ASTContext::getIncompleteArrayType(QualType elementType, 3725 ArrayType::ArraySizeModifier ASM, 3726 unsigned elementTypeQuals) const { 3727 llvm::FoldingSetNodeID ID; 3728 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals); 3729 3730 void *insertPos = nullptr; 3731 if (IncompleteArrayType *iat = 3732 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos)) 3733 return QualType(iat, 0); 3734 3735 // If the element type isn't canonical, this won't be a canonical type 3736 // either, so fill in the canonical type field. We also have to pull 3737 // qualifiers off the element type. 3738 QualType canon; 3739 3740 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) { 3741 SplitQualType canonSplit = getCanonicalType(elementType).split(); 3742 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0), 3743 ASM, elementTypeQuals); 3744 canon = getQualifiedType(canon, canonSplit.Quals); 3745 3746 // Get the new insert position for the node we care about. 3747 IncompleteArrayType *existing = 3748 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos); 3749 assert(!existing && "Shouldn't be in the map!"); (void) existing; 3750 } 3751 3752 auto *newType = new (*this, TypeAlignment) 3753 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals); 3754 3755 IncompleteArrayTypes.InsertNode(newType, insertPos); 3756 Types.push_back(newType); 3757 return QualType(newType, 0); 3758 } 3759 3760 ASTContext::BuiltinVectorTypeInfo 3761 ASTContext::getBuiltinVectorTypeInfo(const BuiltinType *Ty) const { 3762 #define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \ 3763 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \ 3764 NUMVECTORS}; 3765 3766 #define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \ 3767 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS}; 3768 3769 switch (Ty->getKind()) { 3770 default: 3771 llvm_unreachable("Unsupported builtin vector type"); 3772 case BuiltinType::SveInt8: 3773 return SVE_INT_ELTTY(8, 16, true, 1); 3774 case BuiltinType::SveUint8: 3775 return SVE_INT_ELTTY(8, 16, false, 1); 3776 case BuiltinType::SveInt8x2: 3777 return SVE_INT_ELTTY(8, 16, true, 2); 3778 case BuiltinType::SveUint8x2: 3779 return SVE_INT_ELTTY(8, 16, false, 2); 3780 case BuiltinType::SveInt8x3: 3781 return SVE_INT_ELTTY(8, 16, true, 3); 3782 case BuiltinType::SveUint8x3: 3783 return SVE_INT_ELTTY(8, 16, false, 3); 3784 case BuiltinType::SveInt8x4: 3785 return SVE_INT_ELTTY(8, 16, true, 4); 3786 case BuiltinType::SveUint8x4: 3787 return SVE_INT_ELTTY(8, 16, false, 4); 3788 case BuiltinType::SveInt16: 3789 return SVE_INT_ELTTY(16, 8, true, 1); 3790 case BuiltinType::SveUint16: 3791 return SVE_INT_ELTTY(16, 8, false, 1); 3792 case BuiltinType::SveInt16x2: 3793 return SVE_INT_ELTTY(16, 8, true, 2); 3794 case BuiltinType::SveUint16x2: 3795 return SVE_INT_ELTTY(16, 8, false, 2); 3796 case BuiltinType::SveInt16x3: 3797 return SVE_INT_ELTTY(16, 8, true, 3); 3798 case BuiltinType::SveUint16x3: 3799 return SVE_INT_ELTTY(16, 8, false, 3); 3800 case BuiltinType::SveInt16x4: 3801 return SVE_INT_ELTTY(16, 8, true, 4); 3802 case BuiltinType::SveUint16x4: 3803 return SVE_INT_ELTTY(16, 8, false, 4); 3804 case BuiltinType::SveInt32: 3805 return SVE_INT_ELTTY(32, 4, true, 1); 3806 case BuiltinType::SveUint32: 3807 return SVE_INT_ELTTY(32, 4, false, 1); 3808 case BuiltinType::SveInt32x2: 3809 return SVE_INT_ELTTY(32, 4, true, 2); 3810 case BuiltinType::SveUint32x2: 3811 return SVE_INT_ELTTY(32, 4, false, 2); 3812 case BuiltinType::SveInt32x3: 3813 return SVE_INT_ELTTY(32, 4, true, 3); 3814 case BuiltinType::SveUint32x3: 3815 return SVE_INT_ELTTY(32, 4, false, 3); 3816 case BuiltinType::SveInt32x4: 3817 return SVE_INT_ELTTY(32, 4, true, 4); 3818 case BuiltinType::SveUint32x4: 3819 return SVE_INT_ELTTY(32, 4, false, 4); 3820 case BuiltinType::SveInt64: 3821 return SVE_INT_ELTTY(64, 2, true, 1); 3822 case BuiltinType::SveUint64: 3823 return SVE_INT_ELTTY(64, 2, false, 1); 3824 case BuiltinType::SveInt64x2: 3825 return SVE_INT_ELTTY(64, 2, true, 2); 3826 case BuiltinType::SveUint64x2: 3827 return SVE_INT_ELTTY(64, 2, false, 2); 3828 case BuiltinType::SveInt64x3: 3829 return SVE_INT_ELTTY(64, 2, true, 3); 3830 case BuiltinType::SveUint64x3: 3831 return SVE_INT_ELTTY(64, 2, false, 3); 3832 case BuiltinType::SveInt64x4: 3833 return SVE_INT_ELTTY(64, 2, true, 4); 3834 case BuiltinType::SveUint64x4: 3835 return SVE_INT_ELTTY(64, 2, false, 4); 3836 case BuiltinType::SveBool: 3837 return SVE_ELTTY(BoolTy, 16, 1); 3838 case BuiltinType::SveFloat16: 3839 return SVE_ELTTY(HalfTy, 8, 1); 3840 case BuiltinType::SveFloat16x2: 3841 return SVE_ELTTY(HalfTy, 8, 2); 3842 case BuiltinType::SveFloat16x3: 3843 return SVE_ELTTY(HalfTy, 8, 3); 3844 case BuiltinType::SveFloat16x4: 3845 return SVE_ELTTY(HalfTy, 8, 4); 3846 case BuiltinType::SveFloat32: 3847 return SVE_ELTTY(FloatTy, 4, 1); 3848 case BuiltinType::SveFloat32x2: 3849 return SVE_ELTTY(FloatTy, 4, 2); 3850 case BuiltinType::SveFloat32x3: 3851 return SVE_ELTTY(FloatTy, 4, 3); 3852 case BuiltinType::SveFloat32x4: 3853 return SVE_ELTTY(FloatTy, 4, 4); 3854 case BuiltinType::SveFloat64: 3855 return SVE_ELTTY(DoubleTy, 2, 1); 3856 case BuiltinType::SveFloat64x2: 3857 return SVE_ELTTY(DoubleTy, 2, 2); 3858 case BuiltinType::SveFloat64x3: 3859 return SVE_ELTTY(DoubleTy, 2, 3); 3860 case BuiltinType::SveFloat64x4: 3861 return SVE_ELTTY(DoubleTy, 2, 4); 3862 case BuiltinType::SveBFloat16: 3863 return SVE_ELTTY(BFloat16Ty, 8, 1); 3864 case BuiltinType::SveBFloat16x2: 3865 return SVE_ELTTY(BFloat16Ty, 8, 2); 3866 case BuiltinType::SveBFloat16x3: 3867 return SVE_ELTTY(BFloat16Ty, 8, 3); 3868 case BuiltinType::SveBFloat16x4: 3869 return SVE_ELTTY(BFloat16Ty, 8, 4); 3870 #define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \ 3871 IsSigned) \ 3872 case BuiltinType::Id: \ 3873 return {getIntTypeForBitwidth(ElBits, IsSigned), \ 3874 llvm::ElementCount::getScalable(NumEls), NF}; 3875 #define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \ 3876 case BuiltinType::Id: \ 3877 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \ 3878 llvm::ElementCount::getScalable(NumEls), NF}; 3879 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \ 3880 case BuiltinType::Id: \ 3881 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1}; 3882 #include "clang/Basic/RISCVVTypes.def" 3883 } 3884 } 3885 3886 /// getScalableVectorType - Return the unique reference to a scalable vector 3887 /// type of the specified element type and size. VectorType must be a built-in 3888 /// type. 3889 QualType ASTContext::getScalableVectorType(QualType EltTy, 3890 unsigned NumElts) const { 3891 if (Target->hasAArch64SVETypes()) { 3892 uint64_t EltTySize = getTypeSize(EltTy); 3893 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \ 3894 IsSigned, IsFP, IsBF) \ 3895 if (!EltTy->isBooleanType() && \ 3896 ((EltTy->hasIntegerRepresentation() && \ 3897 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \ 3898 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \ 3899 IsFP && !IsBF) || \ 3900 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \ 3901 IsBF && !IsFP)) && \ 3902 EltTySize == ElBits && NumElts == NumEls) { \ 3903 return SingletonId; \ 3904 } 3905 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \ 3906 if (EltTy->isBooleanType() && NumElts == NumEls) \ 3907 return SingletonId; 3908 #include "clang/Basic/AArch64SVEACLETypes.def" 3909 } else if (Target->hasRISCVVTypes()) { 3910 uint64_t EltTySize = getTypeSize(EltTy); 3911 #define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \ 3912 IsFP) \ 3913 if (!EltTy->isBooleanType() && \ 3914 ((EltTy->hasIntegerRepresentation() && \ 3915 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \ 3916 (EltTy->hasFloatingRepresentation() && IsFP)) && \ 3917 EltTySize == ElBits && NumElts == NumEls) \ 3918 return SingletonId; 3919 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \ 3920 if (EltTy->isBooleanType() && NumElts == NumEls) \ 3921 return SingletonId; 3922 #include "clang/Basic/RISCVVTypes.def" 3923 } 3924 return QualType(); 3925 } 3926 3927 /// getVectorType - Return the unique reference to a vector type of 3928 /// the specified element type and size. VectorType must be a built-in type. 3929 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts, 3930 VectorType::VectorKind VecKind) const { 3931 assert(vecType->isBuiltinType()); 3932 3933 // Check if we've already instantiated a vector of this type. 3934 llvm::FoldingSetNodeID ID; 3935 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind); 3936 3937 void *InsertPos = nullptr; 3938 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 3939 return QualType(VTP, 0); 3940 3941 // If the element type isn't canonical, this won't be a canonical type either, 3942 // so fill in the canonical type field. 3943 QualType Canonical; 3944 if (!vecType.isCanonical()) { 3945 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind); 3946 3947 // Get the new insert position for the node we care about. 3948 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3949 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3950 } 3951 auto *New = new (*this, TypeAlignment) 3952 VectorType(vecType, NumElts, Canonical, VecKind); 3953 VectorTypes.InsertNode(New, InsertPos); 3954 Types.push_back(New); 3955 return QualType(New, 0); 3956 } 3957 3958 QualType 3959 ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr, 3960 SourceLocation AttrLoc, 3961 VectorType::VectorKind VecKind) const { 3962 llvm::FoldingSetNodeID ID; 3963 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr, 3964 VecKind); 3965 void *InsertPos = nullptr; 3966 DependentVectorType *Canon = 3967 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3968 DependentVectorType *New; 3969 3970 if (Canon) { 3971 New = new (*this, TypeAlignment) DependentVectorType( 3972 *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind); 3973 } else { 3974 QualType CanonVecTy = getCanonicalType(VecType); 3975 if (CanonVecTy == VecType) { 3976 New = new (*this, TypeAlignment) DependentVectorType( 3977 *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind); 3978 3979 DependentVectorType *CanonCheck = 3980 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3981 assert(!CanonCheck && 3982 "Dependent-sized vector_size canonical type broken"); 3983 (void)CanonCheck; 3984 DependentVectorTypes.InsertNode(New, InsertPos); 3985 } else { 3986 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr, 3987 SourceLocation(), VecKind); 3988 New = new (*this, TypeAlignment) DependentVectorType( 3989 *this, VecType, CanonTy, SizeExpr, AttrLoc, VecKind); 3990 } 3991 } 3992 3993 Types.push_back(New); 3994 return QualType(New, 0); 3995 } 3996 3997 /// getExtVectorType - Return the unique reference to an extended vector type of 3998 /// the specified element type and size. VectorType must be a built-in type. 3999 QualType 4000 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const { 4001 assert(vecType->isBuiltinType() || vecType->isDependentType()); 4002 4003 // Check if we've already instantiated a vector of this type. 4004 llvm::FoldingSetNodeID ID; 4005 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, 4006 VectorType::GenericVector); 4007 void *InsertPos = nullptr; 4008 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 4009 return QualType(VTP, 0); 4010 4011 // If the element type isn't canonical, this won't be a canonical type either, 4012 // so fill in the canonical type field. 4013 QualType Canonical; 4014 if (!vecType.isCanonical()) { 4015 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts); 4016 4017 // Get the new insert position for the node we care about. 4018 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4019 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4020 } 4021 auto *New = new (*this, TypeAlignment) 4022 ExtVectorType(vecType, NumElts, Canonical); 4023 VectorTypes.InsertNode(New, InsertPos); 4024 Types.push_back(New); 4025 return QualType(New, 0); 4026 } 4027 4028 QualType 4029 ASTContext::getDependentSizedExtVectorType(QualType vecType, 4030 Expr *SizeExpr, 4031 SourceLocation AttrLoc) const { 4032 llvm::FoldingSetNodeID ID; 4033 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType), 4034 SizeExpr); 4035 4036 void *InsertPos = nullptr; 4037 DependentSizedExtVectorType *Canon 4038 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4039 DependentSizedExtVectorType *New; 4040 if (Canon) { 4041 // We already have a canonical version of this array type; use it as 4042 // the canonical type for a newly-built type. 4043 New = new (*this, TypeAlignment) 4044 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0), 4045 SizeExpr, AttrLoc); 4046 } else { 4047 QualType CanonVecTy = getCanonicalType(vecType); 4048 if (CanonVecTy == vecType) { 4049 New = new (*this, TypeAlignment) 4050 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr, 4051 AttrLoc); 4052 4053 DependentSizedExtVectorType *CanonCheck 4054 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4055 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken"); 4056 (void)CanonCheck; 4057 DependentSizedExtVectorTypes.InsertNode(New, InsertPos); 4058 } else { 4059 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr, 4060 SourceLocation()); 4061 New = new (*this, TypeAlignment) DependentSizedExtVectorType( 4062 *this, vecType, CanonExtTy, SizeExpr, AttrLoc); 4063 } 4064 } 4065 4066 Types.push_back(New); 4067 return QualType(New, 0); 4068 } 4069 4070 QualType ASTContext::getConstantMatrixType(QualType ElementTy, unsigned NumRows, 4071 unsigned NumColumns) const { 4072 llvm::FoldingSetNodeID ID; 4073 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns, 4074 Type::ConstantMatrix); 4075 4076 assert(MatrixType::isValidElementType(ElementTy) && 4077 "need a valid element type"); 4078 assert(ConstantMatrixType::isDimensionValid(NumRows) && 4079 ConstantMatrixType::isDimensionValid(NumColumns) && 4080 "need valid matrix dimensions"); 4081 void *InsertPos = nullptr; 4082 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos)) 4083 return QualType(MTP, 0); 4084 4085 QualType Canonical; 4086 if (!ElementTy.isCanonical()) { 4087 Canonical = 4088 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns); 4089 4090 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos); 4091 assert(!NewIP && "Matrix type shouldn't already exist in the map"); 4092 (void)NewIP; 4093 } 4094 4095 auto *New = new (*this, TypeAlignment) 4096 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical); 4097 MatrixTypes.InsertNode(New, InsertPos); 4098 Types.push_back(New); 4099 return QualType(New, 0); 4100 } 4101 4102 QualType ASTContext::getDependentSizedMatrixType(QualType ElementTy, 4103 Expr *RowExpr, 4104 Expr *ColumnExpr, 4105 SourceLocation AttrLoc) const { 4106 QualType CanonElementTy = getCanonicalType(ElementTy); 4107 llvm::FoldingSetNodeID ID; 4108 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr, 4109 ColumnExpr); 4110 4111 void *InsertPos = nullptr; 4112 DependentSizedMatrixType *Canon = 4113 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos); 4114 4115 if (!Canon) { 4116 Canon = new (*this, TypeAlignment) DependentSizedMatrixType( 4117 *this, CanonElementTy, QualType(), RowExpr, ColumnExpr, AttrLoc); 4118 #ifndef NDEBUG 4119 DependentSizedMatrixType *CanonCheck = 4120 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos); 4121 assert(!CanonCheck && "Dependent-sized matrix canonical type broken"); 4122 #endif 4123 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos); 4124 Types.push_back(Canon); 4125 } 4126 4127 // Already have a canonical version of the matrix type 4128 // 4129 // If it exactly matches the requested type, use it directly. 4130 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr && 4131 Canon->getRowExpr() == ColumnExpr) 4132 return QualType(Canon, 0); 4133 4134 // Use Canon as the canonical type for newly-built type. 4135 DependentSizedMatrixType *New = new (*this, TypeAlignment) 4136 DependentSizedMatrixType(*this, ElementTy, QualType(Canon, 0), RowExpr, 4137 ColumnExpr, AttrLoc); 4138 Types.push_back(New); 4139 return QualType(New, 0); 4140 } 4141 4142 QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType, 4143 Expr *AddrSpaceExpr, 4144 SourceLocation AttrLoc) const { 4145 assert(AddrSpaceExpr->isInstantiationDependent()); 4146 4147 QualType canonPointeeType = getCanonicalType(PointeeType); 4148 4149 void *insertPos = nullptr; 4150 llvm::FoldingSetNodeID ID; 4151 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType, 4152 AddrSpaceExpr); 4153 4154 DependentAddressSpaceType *canonTy = 4155 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos); 4156 4157 if (!canonTy) { 4158 canonTy = new (*this, TypeAlignment) 4159 DependentAddressSpaceType(*this, canonPointeeType, 4160 QualType(), AddrSpaceExpr, AttrLoc); 4161 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos); 4162 Types.push_back(canonTy); 4163 } 4164 4165 if (canonPointeeType == PointeeType && 4166 canonTy->getAddrSpaceExpr() == AddrSpaceExpr) 4167 return QualType(canonTy, 0); 4168 4169 auto *sugaredType 4170 = new (*this, TypeAlignment) 4171 DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0), 4172 AddrSpaceExpr, AttrLoc); 4173 Types.push_back(sugaredType); 4174 return QualType(sugaredType, 0); 4175 } 4176 4177 /// Determine whether \p T is canonical as the result type of a function. 4178 static bool isCanonicalResultType(QualType T) { 4179 return T.isCanonical() && 4180 (T.getObjCLifetime() == Qualifiers::OCL_None || 4181 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone); 4182 } 4183 4184 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'. 4185 QualType 4186 ASTContext::getFunctionNoProtoType(QualType ResultTy, 4187 const FunctionType::ExtInfo &Info) const { 4188 // Unique functions, to guarantee there is only one function of a particular 4189 // structure. 4190 llvm::FoldingSetNodeID ID; 4191 FunctionNoProtoType::Profile(ID, ResultTy, Info); 4192 4193 void *InsertPos = nullptr; 4194 if (FunctionNoProtoType *FT = 4195 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 4196 return QualType(FT, 0); 4197 4198 QualType Canonical; 4199 if (!isCanonicalResultType(ResultTy)) { 4200 Canonical = 4201 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info); 4202 4203 // Get the new insert position for the node we care about. 4204 FunctionNoProtoType *NewIP = 4205 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 4206 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4207 } 4208 4209 auto *New = new (*this, TypeAlignment) 4210 FunctionNoProtoType(ResultTy, Canonical, Info); 4211 Types.push_back(New); 4212 FunctionNoProtoTypes.InsertNode(New, InsertPos); 4213 return QualType(New, 0); 4214 } 4215 4216 CanQualType 4217 ASTContext::getCanonicalFunctionResultType(QualType ResultType) const { 4218 CanQualType CanResultType = getCanonicalType(ResultType); 4219 4220 // Canonical result types do not have ARC lifetime qualifiers. 4221 if (CanResultType.getQualifiers().hasObjCLifetime()) { 4222 Qualifiers Qs = CanResultType.getQualifiers(); 4223 Qs.removeObjCLifetime(); 4224 return CanQualType::CreateUnsafe( 4225 getQualifiedType(CanResultType.getUnqualifiedType(), Qs)); 4226 } 4227 4228 return CanResultType; 4229 } 4230 4231 static bool isCanonicalExceptionSpecification( 4232 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) { 4233 if (ESI.Type == EST_None) 4234 return true; 4235 if (!NoexceptInType) 4236 return false; 4237 4238 // C++17 onwards: exception specification is part of the type, as a simple 4239 // boolean "can this function type throw". 4240 if (ESI.Type == EST_BasicNoexcept) 4241 return true; 4242 4243 // A noexcept(expr) specification is (possibly) canonical if expr is 4244 // value-dependent. 4245 if (ESI.Type == EST_DependentNoexcept) 4246 return true; 4247 4248 // A dynamic exception specification is canonical if it only contains pack 4249 // expansions (so we can't tell whether it's non-throwing) and all its 4250 // contained types are canonical. 4251 if (ESI.Type == EST_Dynamic) { 4252 bool AnyPackExpansions = false; 4253 for (QualType ET : ESI.Exceptions) { 4254 if (!ET.isCanonical()) 4255 return false; 4256 if (ET->getAs<PackExpansionType>()) 4257 AnyPackExpansions = true; 4258 } 4259 return AnyPackExpansions; 4260 } 4261 4262 return false; 4263 } 4264 4265 QualType ASTContext::getFunctionTypeInternal( 4266 QualType ResultTy, ArrayRef<QualType> ArgArray, 4267 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const { 4268 size_t NumArgs = ArgArray.size(); 4269 4270 // Unique functions, to guarantee there is only one function of a particular 4271 // structure. 4272 llvm::FoldingSetNodeID ID; 4273 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI, 4274 *this, true); 4275 4276 QualType Canonical; 4277 bool Unique = false; 4278 4279 void *InsertPos = nullptr; 4280 if (FunctionProtoType *FPT = 4281 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) { 4282 QualType Existing = QualType(FPT, 0); 4283 4284 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse 4285 // it so long as our exception specification doesn't contain a dependent 4286 // noexcept expression, or we're just looking for a canonical type. 4287 // Otherwise, we're going to need to create a type 4288 // sugar node to hold the concrete expression. 4289 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) || 4290 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr()) 4291 return Existing; 4292 4293 // We need a new type sugar node for this one, to hold the new noexcept 4294 // expression. We do no canonicalization here, but that's OK since we don't 4295 // expect to see the same noexcept expression much more than once. 4296 Canonical = getCanonicalType(Existing); 4297 Unique = true; 4298 } 4299 4300 bool NoexceptInType = getLangOpts().CPlusPlus17; 4301 bool IsCanonicalExceptionSpec = 4302 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType); 4303 4304 // Determine whether the type being created is already canonical or not. 4305 bool isCanonical = !Unique && IsCanonicalExceptionSpec && 4306 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn; 4307 for (unsigned i = 0; i != NumArgs && isCanonical; ++i) 4308 if (!ArgArray[i].isCanonicalAsParam()) 4309 isCanonical = false; 4310 4311 if (OnlyWantCanonical) 4312 assert(isCanonical && 4313 "given non-canonical parameters constructing canonical type"); 4314 4315 // If this type isn't canonical, get the canonical version of it if we don't 4316 // already have it. The exception spec is only partially part of the 4317 // canonical type, and only in C++17 onwards. 4318 if (!isCanonical && Canonical.isNull()) { 4319 SmallVector<QualType, 16> CanonicalArgs; 4320 CanonicalArgs.reserve(NumArgs); 4321 for (unsigned i = 0; i != NumArgs; ++i) 4322 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i])); 4323 4324 llvm::SmallVector<QualType, 8> ExceptionTypeStorage; 4325 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI; 4326 CanonicalEPI.HasTrailingReturn = false; 4327 4328 if (IsCanonicalExceptionSpec) { 4329 // Exception spec is already OK. 4330 } else if (NoexceptInType) { 4331 switch (EPI.ExceptionSpec.Type) { 4332 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated: 4333 // We don't know yet. It shouldn't matter what we pick here; no-one 4334 // should ever look at this. 4335 LLVM_FALLTHROUGH; 4336 case EST_None: case EST_MSAny: case EST_NoexceptFalse: 4337 CanonicalEPI.ExceptionSpec.Type = EST_None; 4338 break; 4339 4340 // A dynamic exception specification is almost always "not noexcept", 4341 // with the exception that a pack expansion might expand to no types. 4342 case EST_Dynamic: { 4343 bool AnyPacks = false; 4344 for (QualType ET : EPI.ExceptionSpec.Exceptions) { 4345 if (ET->getAs<PackExpansionType>()) 4346 AnyPacks = true; 4347 ExceptionTypeStorage.push_back(getCanonicalType(ET)); 4348 } 4349 if (!AnyPacks) 4350 CanonicalEPI.ExceptionSpec.Type = EST_None; 4351 else { 4352 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic; 4353 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage; 4354 } 4355 break; 4356 } 4357 4358 case EST_DynamicNone: 4359 case EST_BasicNoexcept: 4360 case EST_NoexceptTrue: 4361 case EST_NoThrow: 4362 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept; 4363 break; 4364 4365 case EST_DependentNoexcept: 4366 llvm_unreachable("dependent noexcept is already canonical"); 4367 } 4368 } else { 4369 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo(); 4370 } 4371 4372 // Adjust the canonical function result type. 4373 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy); 4374 Canonical = 4375 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true); 4376 4377 // Get the new insert position for the node we care about. 4378 FunctionProtoType *NewIP = 4379 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 4380 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4381 } 4382 4383 // Compute the needed size to hold this FunctionProtoType and the 4384 // various trailing objects. 4385 auto ESH = FunctionProtoType::getExceptionSpecSize( 4386 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size()); 4387 size_t Size = FunctionProtoType::totalSizeToAlloc< 4388 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields, 4389 FunctionType::ExceptionType, Expr *, FunctionDecl *, 4390 FunctionProtoType::ExtParameterInfo, Qualifiers>( 4391 NumArgs, EPI.Variadic, 4392 FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type), 4393 ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr, 4394 EPI.ExtParameterInfos ? NumArgs : 0, 4395 EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0); 4396 4397 auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment); 4398 FunctionProtoType::ExtProtoInfo newEPI = EPI; 4399 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI); 4400 Types.push_back(FTP); 4401 if (!Unique) 4402 FunctionProtoTypes.InsertNode(FTP, InsertPos); 4403 return QualType(FTP, 0); 4404 } 4405 4406 QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const { 4407 llvm::FoldingSetNodeID ID; 4408 PipeType::Profile(ID, T, ReadOnly); 4409 4410 void *InsertPos = nullptr; 4411 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos)) 4412 return QualType(PT, 0); 4413 4414 // If the pipe element type isn't canonical, this won't be a canonical type 4415 // either, so fill in the canonical type field. 4416 QualType Canonical; 4417 if (!T.isCanonical()) { 4418 Canonical = getPipeType(getCanonicalType(T), ReadOnly); 4419 4420 // Get the new insert position for the node we care about. 4421 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos); 4422 assert(!NewIP && "Shouldn't be in the map!"); 4423 (void)NewIP; 4424 } 4425 auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly); 4426 Types.push_back(New); 4427 PipeTypes.InsertNode(New, InsertPos); 4428 return QualType(New, 0); 4429 } 4430 4431 QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const { 4432 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 4433 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant) 4434 : Ty; 4435 } 4436 4437 QualType ASTContext::getReadPipeType(QualType T) const { 4438 return getPipeType(T, true); 4439 } 4440 4441 QualType ASTContext::getWritePipeType(QualType T) const { 4442 return getPipeType(T, false); 4443 } 4444 4445 QualType ASTContext::getExtIntType(bool IsUnsigned, unsigned NumBits) const { 4446 llvm::FoldingSetNodeID ID; 4447 ExtIntType::Profile(ID, IsUnsigned, NumBits); 4448 4449 void *InsertPos = nullptr; 4450 if (ExtIntType *EIT = ExtIntTypes.FindNodeOrInsertPos(ID, InsertPos)) 4451 return QualType(EIT, 0); 4452 4453 auto *New = new (*this, TypeAlignment) ExtIntType(IsUnsigned, NumBits); 4454 ExtIntTypes.InsertNode(New, InsertPos); 4455 Types.push_back(New); 4456 return QualType(New, 0); 4457 } 4458 4459 QualType ASTContext::getDependentExtIntType(bool IsUnsigned, 4460 Expr *NumBitsExpr) const { 4461 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent"); 4462 llvm::FoldingSetNodeID ID; 4463 DependentExtIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr); 4464 4465 void *InsertPos = nullptr; 4466 if (DependentExtIntType *Existing = 4467 DependentExtIntTypes.FindNodeOrInsertPos(ID, InsertPos)) 4468 return QualType(Existing, 0); 4469 4470 auto *New = new (*this, TypeAlignment) 4471 DependentExtIntType(*this, IsUnsigned, NumBitsExpr); 4472 DependentExtIntTypes.InsertNode(New, InsertPos); 4473 4474 Types.push_back(New); 4475 return QualType(New, 0); 4476 } 4477 4478 #ifndef NDEBUG 4479 static bool NeedsInjectedClassNameType(const RecordDecl *D) { 4480 if (!isa<CXXRecordDecl>(D)) return false; 4481 const auto *RD = cast<CXXRecordDecl>(D); 4482 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) 4483 return true; 4484 if (RD->getDescribedClassTemplate() && 4485 !isa<ClassTemplateSpecializationDecl>(RD)) 4486 return true; 4487 return false; 4488 } 4489 #endif 4490 4491 /// getInjectedClassNameType - Return the unique reference to the 4492 /// injected class name type for the specified templated declaration. 4493 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl, 4494 QualType TST) const { 4495 assert(NeedsInjectedClassNameType(Decl)); 4496 if (Decl->TypeForDecl) { 4497 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 4498 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) { 4499 assert(PrevDecl->TypeForDecl && "previous declaration has no type"); 4500 Decl->TypeForDecl = PrevDecl->TypeForDecl; 4501 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 4502 } else { 4503 Type *newType = 4504 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST); 4505 Decl->TypeForDecl = newType; 4506 Types.push_back(newType); 4507 } 4508 return QualType(Decl->TypeForDecl, 0); 4509 } 4510 4511 /// getTypeDeclType - Return the unique reference to the type for the 4512 /// specified type declaration. 4513 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const { 4514 assert(Decl && "Passed null for Decl param"); 4515 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case"); 4516 4517 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl)) 4518 return getTypedefType(Typedef); 4519 4520 assert(!isa<TemplateTypeParmDecl>(Decl) && 4521 "Template type parameter types are always available."); 4522 4523 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) { 4524 assert(Record->isFirstDecl() && "struct/union has previous declaration"); 4525 assert(!NeedsInjectedClassNameType(Record)); 4526 return getRecordType(Record); 4527 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) { 4528 assert(Enum->isFirstDecl() && "enum has previous declaration"); 4529 return getEnumType(Enum); 4530 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) { 4531 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using); 4532 Decl->TypeForDecl = newType; 4533 Types.push_back(newType); 4534 } else 4535 llvm_unreachable("TypeDecl without a type?"); 4536 4537 return QualType(Decl->TypeForDecl, 0); 4538 } 4539 4540 /// getTypedefType - Return the unique reference to the type for the 4541 /// specified typedef name decl. 4542 QualType ASTContext::getTypedefType(const TypedefNameDecl *Decl, 4543 QualType Underlying) const { 4544 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 4545 4546 if (Underlying.isNull()) 4547 Underlying = Decl->getUnderlyingType(); 4548 QualType Canonical = getCanonicalType(Underlying); 4549 auto *newType = new (*this, TypeAlignment) 4550 TypedefType(Type::Typedef, Decl, Underlying, Canonical); 4551 Decl->TypeForDecl = newType; 4552 Types.push_back(newType); 4553 return QualType(newType, 0); 4554 } 4555 4556 QualType ASTContext::getRecordType(const RecordDecl *Decl) const { 4557 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 4558 4559 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl()) 4560 if (PrevDecl->TypeForDecl) 4561 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 4562 4563 auto *newType = new (*this, TypeAlignment) RecordType(Decl); 4564 Decl->TypeForDecl = newType; 4565 Types.push_back(newType); 4566 return QualType(newType, 0); 4567 } 4568 4569 QualType ASTContext::getEnumType(const EnumDecl *Decl) const { 4570 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 4571 4572 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl()) 4573 if (PrevDecl->TypeForDecl) 4574 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 4575 4576 auto *newType = new (*this, TypeAlignment) EnumType(Decl); 4577 Decl->TypeForDecl = newType; 4578 Types.push_back(newType); 4579 return QualType(newType, 0); 4580 } 4581 4582 QualType ASTContext::getAttributedType(attr::Kind attrKind, 4583 QualType modifiedType, 4584 QualType equivalentType) { 4585 llvm::FoldingSetNodeID id; 4586 AttributedType::Profile(id, attrKind, modifiedType, equivalentType); 4587 4588 void *insertPos = nullptr; 4589 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos); 4590 if (type) return QualType(type, 0); 4591 4592 QualType canon = getCanonicalType(equivalentType); 4593 type = new (*this, TypeAlignment) 4594 AttributedType(canon, attrKind, modifiedType, equivalentType); 4595 4596 Types.push_back(type); 4597 AttributedTypes.InsertNode(type, insertPos); 4598 4599 return QualType(type, 0); 4600 } 4601 4602 /// Retrieve a substitution-result type. 4603 QualType 4604 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm, 4605 QualType Replacement) const { 4606 assert(Replacement.isCanonical() 4607 && "replacement types must always be canonical"); 4608 4609 llvm::FoldingSetNodeID ID; 4610 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement); 4611 void *InsertPos = nullptr; 4612 SubstTemplateTypeParmType *SubstParm 4613 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 4614 4615 if (!SubstParm) { 4616 SubstParm = new (*this, TypeAlignment) 4617 SubstTemplateTypeParmType(Parm, Replacement); 4618 Types.push_back(SubstParm); 4619 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos); 4620 } 4621 4622 return QualType(SubstParm, 0); 4623 } 4624 4625 /// Retrieve a 4626 QualType ASTContext::getSubstTemplateTypeParmPackType( 4627 const TemplateTypeParmType *Parm, 4628 const TemplateArgument &ArgPack) { 4629 #ifndef NDEBUG 4630 for (const auto &P : ArgPack.pack_elements()) { 4631 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type"); 4632 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type"); 4633 } 4634 #endif 4635 4636 llvm::FoldingSetNodeID ID; 4637 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack); 4638 void *InsertPos = nullptr; 4639 if (SubstTemplateTypeParmPackType *SubstParm 4640 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos)) 4641 return QualType(SubstParm, 0); 4642 4643 QualType Canon; 4644 if (!Parm->isCanonicalUnqualified()) { 4645 Canon = getCanonicalType(QualType(Parm, 0)); 4646 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon), 4647 ArgPack); 4648 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos); 4649 } 4650 4651 auto *SubstParm 4652 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon, 4653 ArgPack); 4654 Types.push_back(SubstParm); 4655 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos); 4656 return QualType(SubstParm, 0); 4657 } 4658 4659 /// Retrieve the template type parameter type for a template 4660 /// parameter or parameter pack with the given depth, index, and (optionally) 4661 /// name. 4662 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index, 4663 bool ParameterPack, 4664 TemplateTypeParmDecl *TTPDecl) const { 4665 llvm::FoldingSetNodeID ID; 4666 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl); 4667 void *InsertPos = nullptr; 4668 TemplateTypeParmType *TypeParm 4669 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 4670 4671 if (TypeParm) 4672 return QualType(TypeParm, 0); 4673 4674 if (TTPDecl) { 4675 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack); 4676 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon); 4677 4678 TemplateTypeParmType *TypeCheck 4679 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 4680 assert(!TypeCheck && "Template type parameter canonical type broken"); 4681 (void)TypeCheck; 4682 } else 4683 TypeParm = new (*this, TypeAlignment) 4684 TemplateTypeParmType(Depth, Index, ParameterPack); 4685 4686 Types.push_back(TypeParm); 4687 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos); 4688 4689 return QualType(TypeParm, 0); 4690 } 4691 4692 TypeSourceInfo * 4693 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name, 4694 SourceLocation NameLoc, 4695 const TemplateArgumentListInfo &Args, 4696 QualType Underlying) const { 4697 assert(!Name.getAsDependentTemplateName() && 4698 "No dependent template names here!"); 4699 QualType TST = getTemplateSpecializationType(Name, Args, Underlying); 4700 4701 TypeSourceInfo *DI = CreateTypeSourceInfo(TST); 4702 TemplateSpecializationTypeLoc TL = 4703 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>(); 4704 TL.setTemplateKeywordLoc(SourceLocation()); 4705 TL.setTemplateNameLoc(NameLoc); 4706 TL.setLAngleLoc(Args.getLAngleLoc()); 4707 TL.setRAngleLoc(Args.getRAngleLoc()); 4708 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 4709 TL.setArgLocInfo(i, Args[i].getLocInfo()); 4710 return DI; 4711 } 4712 4713 QualType 4714 ASTContext::getTemplateSpecializationType(TemplateName Template, 4715 const TemplateArgumentListInfo &Args, 4716 QualType Underlying) const { 4717 assert(!Template.getAsDependentTemplateName() && 4718 "No dependent template names here!"); 4719 4720 SmallVector<TemplateArgument, 4> ArgVec; 4721 ArgVec.reserve(Args.size()); 4722 for (const TemplateArgumentLoc &Arg : Args.arguments()) 4723 ArgVec.push_back(Arg.getArgument()); 4724 4725 return getTemplateSpecializationType(Template, ArgVec, Underlying); 4726 } 4727 4728 #ifndef NDEBUG 4729 static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) { 4730 for (const TemplateArgument &Arg : Args) 4731 if (Arg.isPackExpansion()) 4732 return true; 4733 4734 return true; 4735 } 4736 #endif 4737 4738 QualType 4739 ASTContext::getTemplateSpecializationType(TemplateName Template, 4740 ArrayRef<TemplateArgument> Args, 4741 QualType Underlying) const { 4742 assert(!Template.getAsDependentTemplateName() && 4743 "No dependent template names here!"); 4744 // Look through qualified template names. 4745 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 4746 Template = TemplateName(QTN->getTemplateDecl()); 4747 4748 bool IsTypeAlias = 4749 Template.getAsTemplateDecl() && 4750 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl()); 4751 QualType CanonType; 4752 if (!Underlying.isNull()) 4753 CanonType = getCanonicalType(Underlying); 4754 else { 4755 // We can get here with an alias template when the specialization contains 4756 // a pack expansion that does not match up with a parameter pack. 4757 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) && 4758 "Caller must compute aliased type"); 4759 IsTypeAlias = false; 4760 CanonType = getCanonicalTemplateSpecializationType(Template, Args); 4761 } 4762 4763 // Allocate the (non-canonical) template specialization type, but don't 4764 // try to unique it: these types typically have location information that 4765 // we don't unique and don't want to lose. 4766 void *Mem = Allocate(sizeof(TemplateSpecializationType) + 4767 sizeof(TemplateArgument) * Args.size() + 4768 (IsTypeAlias? sizeof(QualType) : 0), 4769 TypeAlignment); 4770 auto *Spec 4771 = new (Mem) TemplateSpecializationType(Template, Args, CanonType, 4772 IsTypeAlias ? Underlying : QualType()); 4773 4774 Types.push_back(Spec); 4775 return QualType(Spec, 0); 4776 } 4777 4778 QualType ASTContext::getCanonicalTemplateSpecializationType( 4779 TemplateName Template, ArrayRef<TemplateArgument> Args) const { 4780 assert(!Template.getAsDependentTemplateName() && 4781 "No dependent template names here!"); 4782 4783 // Look through qualified template names. 4784 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 4785 Template = TemplateName(QTN->getTemplateDecl()); 4786 4787 // Build the canonical template specialization type. 4788 TemplateName CanonTemplate = getCanonicalTemplateName(Template); 4789 SmallVector<TemplateArgument, 4> CanonArgs; 4790 unsigned NumArgs = Args.size(); 4791 CanonArgs.reserve(NumArgs); 4792 for (const TemplateArgument &Arg : Args) 4793 CanonArgs.push_back(getCanonicalTemplateArgument(Arg)); 4794 4795 // Determine whether this canonical template specialization type already 4796 // exists. 4797 llvm::FoldingSetNodeID ID; 4798 TemplateSpecializationType::Profile(ID, CanonTemplate, 4799 CanonArgs, *this); 4800 4801 void *InsertPos = nullptr; 4802 TemplateSpecializationType *Spec 4803 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 4804 4805 if (!Spec) { 4806 // Allocate a new canonical template specialization type. 4807 void *Mem = Allocate((sizeof(TemplateSpecializationType) + 4808 sizeof(TemplateArgument) * NumArgs), 4809 TypeAlignment); 4810 Spec = new (Mem) TemplateSpecializationType(CanonTemplate, 4811 CanonArgs, 4812 QualType(), QualType()); 4813 Types.push_back(Spec); 4814 TemplateSpecializationTypes.InsertNode(Spec, InsertPos); 4815 } 4816 4817 assert(Spec->isDependentType() && 4818 "Non-dependent template-id type must have a canonical type"); 4819 return QualType(Spec, 0); 4820 } 4821 4822 QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword, 4823 NestedNameSpecifier *NNS, 4824 QualType NamedType, 4825 TagDecl *OwnedTagDecl) const { 4826 llvm::FoldingSetNodeID ID; 4827 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl); 4828 4829 void *InsertPos = nullptr; 4830 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 4831 if (T) 4832 return QualType(T, 0); 4833 4834 QualType Canon = NamedType; 4835 if (!Canon.isCanonical()) { 4836 Canon = getCanonicalType(NamedType); 4837 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 4838 assert(!CheckT && "Elaborated canonical type broken"); 4839 (void)CheckT; 4840 } 4841 4842 void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl), 4843 TypeAlignment); 4844 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl); 4845 4846 Types.push_back(T); 4847 ElaboratedTypes.InsertNode(T, InsertPos); 4848 return QualType(T, 0); 4849 } 4850 4851 QualType 4852 ASTContext::getParenType(QualType InnerType) const { 4853 llvm::FoldingSetNodeID ID; 4854 ParenType::Profile(ID, InnerType); 4855 4856 void *InsertPos = nullptr; 4857 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 4858 if (T) 4859 return QualType(T, 0); 4860 4861 QualType Canon = InnerType; 4862 if (!Canon.isCanonical()) { 4863 Canon = getCanonicalType(InnerType); 4864 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 4865 assert(!CheckT && "Paren canonical type broken"); 4866 (void)CheckT; 4867 } 4868 4869 T = new (*this, TypeAlignment) ParenType(InnerType, Canon); 4870 Types.push_back(T); 4871 ParenTypes.InsertNode(T, InsertPos); 4872 return QualType(T, 0); 4873 } 4874 4875 QualType 4876 ASTContext::getMacroQualifiedType(QualType UnderlyingTy, 4877 const IdentifierInfo *MacroII) const { 4878 QualType Canon = UnderlyingTy; 4879 if (!Canon.isCanonical()) 4880 Canon = getCanonicalType(UnderlyingTy); 4881 4882 auto *newType = new (*this, TypeAlignment) 4883 MacroQualifiedType(UnderlyingTy, Canon, MacroII); 4884 Types.push_back(newType); 4885 return QualType(newType, 0); 4886 } 4887 4888 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword, 4889 NestedNameSpecifier *NNS, 4890 const IdentifierInfo *Name, 4891 QualType Canon) const { 4892 if (Canon.isNull()) { 4893 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 4894 if (CanonNNS != NNS) 4895 Canon = getDependentNameType(Keyword, CanonNNS, Name); 4896 } 4897 4898 llvm::FoldingSetNodeID ID; 4899 DependentNameType::Profile(ID, Keyword, NNS, Name); 4900 4901 void *InsertPos = nullptr; 4902 DependentNameType *T 4903 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos); 4904 if (T) 4905 return QualType(T, 0); 4906 4907 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon); 4908 Types.push_back(T); 4909 DependentNameTypes.InsertNode(T, InsertPos); 4910 return QualType(T, 0); 4911 } 4912 4913 QualType 4914 ASTContext::getDependentTemplateSpecializationType( 4915 ElaboratedTypeKeyword Keyword, 4916 NestedNameSpecifier *NNS, 4917 const IdentifierInfo *Name, 4918 const TemplateArgumentListInfo &Args) const { 4919 // TODO: avoid this copy 4920 SmallVector<TemplateArgument, 16> ArgCopy; 4921 for (unsigned I = 0, E = Args.size(); I != E; ++I) 4922 ArgCopy.push_back(Args[I].getArgument()); 4923 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy); 4924 } 4925 4926 QualType 4927 ASTContext::getDependentTemplateSpecializationType( 4928 ElaboratedTypeKeyword Keyword, 4929 NestedNameSpecifier *NNS, 4930 const IdentifierInfo *Name, 4931 ArrayRef<TemplateArgument> Args) const { 4932 assert((!NNS || NNS->isDependent()) && 4933 "nested-name-specifier must be dependent"); 4934 4935 llvm::FoldingSetNodeID ID; 4936 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS, 4937 Name, Args); 4938 4939 void *InsertPos = nullptr; 4940 DependentTemplateSpecializationType *T 4941 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 4942 if (T) 4943 return QualType(T, 0); 4944 4945 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 4946 4947 ElaboratedTypeKeyword CanonKeyword = Keyword; 4948 if (Keyword == ETK_None) CanonKeyword = ETK_Typename; 4949 4950 bool AnyNonCanonArgs = false; 4951 unsigned NumArgs = Args.size(); 4952 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs); 4953 for (unsigned I = 0; I != NumArgs; ++I) { 4954 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]); 4955 if (!CanonArgs[I].structurallyEquals(Args[I])) 4956 AnyNonCanonArgs = true; 4957 } 4958 4959 QualType Canon; 4960 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) { 4961 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS, 4962 Name, 4963 CanonArgs); 4964 4965 // Find the insert position again. 4966 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 4967 } 4968 4969 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) + 4970 sizeof(TemplateArgument) * NumArgs), 4971 TypeAlignment); 4972 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS, 4973 Name, Args, Canon); 4974 Types.push_back(T); 4975 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos); 4976 return QualType(T, 0); 4977 } 4978 4979 TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) { 4980 TemplateArgument Arg; 4981 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) { 4982 QualType ArgType = getTypeDeclType(TTP); 4983 if (TTP->isParameterPack()) 4984 ArgType = getPackExpansionType(ArgType, None); 4985 4986 Arg = TemplateArgument(ArgType); 4987 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 4988 QualType T = 4989 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this); 4990 // For class NTTPs, ensure we include the 'const' so the type matches that 4991 // of a real template argument. 4992 // FIXME: It would be more faithful to model this as something like an 4993 // lvalue-to-rvalue conversion applied to a const-qualified lvalue. 4994 if (T->isRecordType()) 4995 T.addConst(); 4996 Expr *E = new (*this) DeclRefExpr( 4997 *this, NTTP, /*enclosing*/ false, T, 4998 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation()); 4999 5000 if (NTTP->isParameterPack()) 5001 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(), 5002 None); 5003 Arg = TemplateArgument(E); 5004 } else { 5005 auto *TTP = cast<TemplateTemplateParmDecl>(Param); 5006 if (TTP->isParameterPack()) 5007 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>()); 5008 else 5009 Arg = TemplateArgument(TemplateName(TTP)); 5010 } 5011 5012 if (Param->isTemplateParameterPack()) 5013 Arg = TemplateArgument::CreatePackCopy(*this, Arg); 5014 5015 return Arg; 5016 } 5017 5018 void 5019 ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params, 5020 SmallVectorImpl<TemplateArgument> &Args) { 5021 Args.reserve(Args.size() + Params->size()); 5022 5023 for (NamedDecl *Param : *Params) 5024 Args.push_back(getInjectedTemplateArg(Param)); 5025 } 5026 5027 QualType ASTContext::getPackExpansionType(QualType Pattern, 5028 Optional<unsigned> NumExpansions, 5029 bool ExpectPackInType) { 5030 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) && 5031 "Pack expansions must expand one or more parameter packs"); 5032 5033 llvm::FoldingSetNodeID ID; 5034 PackExpansionType::Profile(ID, Pattern, NumExpansions); 5035 5036 void *InsertPos = nullptr; 5037 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 5038 if (T) 5039 return QualType(T, 0); 5040 5041 QualType Canon; 5042 if (!Pattern.isCanonical()) { 5043 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions, 5044 /*ExpectPackInType=*/false); 5045 5046 // Find the insert position again, in case we inserted an element into 5047 // PackExpansionTypes and invalidated our insert position. 5048 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 5049 } 5050 5051 T = new (*this, TypeAlignment) 5052 PackExpansionType(Pattern, Canon, NumExpansions); 5053 Types.push_back(T); 5054 PackExpansionTypes.InsertNode(T, InsertPos); 5055 return QualType(T, 0); 5056 } 5057 5058 /// CmpProtocolNames - Comparison predicate for sorting protocols 5059 /// alphabetically. 5060 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS, 5061 ObjCProtocolDecl *const *RHS) { 5062 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName()); 5063 } 5064 5065 static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) { 5066 if (Protocols.empty()) return true; 5067 5068 if (Protocols[0]->getCanonicalDecl() != Protocols[0]) 5069 return false; 5070 5071 for (unsigned i = 1; i != Protocols.size(); ++i) 5072 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 || 5073 Protocols[i]->getCanonicalDecl() != Protocols[i]) 5074 return false; 5075 return true; 5076 } 5077 5078 static void 5079 SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) { 5080 // Sort protocols, keyed by name. 5081 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames); 5082 5083 // Canonicalize. 5084 for (ObjCProtocolDecl *&P : Protocols) 5085 P = P->getCanonicalDecl(); 5086 5087 // Remove duplicates. 5088 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end()); 5089 Protocols.erase(ProtocolsEnd, Protocols.end()); 5090 } 5091 5092 QualType ASTContext::getObjCObjectType(QualType BaseType, 5093 ObjCProtocolDecl * const *Protocols, 5094 unsigned NumProtocols) const { 5095 return getObjCObjectType(BaseType, {}, 5096 llvm::makeArrayRef(Protocols, NumProtocols), 5097 /*isKindOf=*/false); 5098 } 5099 5100 QualType ASTContext::getObjCObjectType( 5101 QualType baseType, 5102 ArrayRef<QualType> typeArgs, 5103 ArrayRef<ObjCProtocolDecl *> protocols, 5104 bool isKindOf) const { 5105 // If the base type is an interface and there aren't any protocols or 5106 // type arguments to add, then the interface type will do just fine. 5107 if (typeArgs.empty() && protocols.empty() && !isKindOf && 5108 isa<ObjCInterfaceType>(baseType)) 5109 return baseType; 5110 5111 // Look in the folding set for an existing type. 5112 llvm::FoldingSetNodeID ID; 5113 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf); 5114 void *InsertPos = nullptr; 5115 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos)) 5116 return QualType(QT, 0); 5117 5118 // Determine the type arguments to be used for canonicalization, 5119 // which may be explicitly specified here or written on the base 5120 // type. 5121 ArrayRef<QualType> effectiveTypeArgs = typeArgs; 5122 if (effectiveTypeArgs.empty()) { 5123 if (const auto *baseObject = baseType->getAs<ObjCObjectType>()) 5124 effectiveTypeArgs = baseObject->getTypeArgs(); 5125 } 5126 5127 // Build the canonical type, which has the canonical base type and a 5128 // sorted-and-uniqued list of protocols and the type arguments 5129 // canonicalized. 5130 QualType canonical; 5131 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(), 5132 effectiveTypeArgs.end(), 5133 [&](QualType type) { 5134 return type.isCanonical(); 5135 }); 5136 bool protocolsSorted = areSortedAndUniqued(protocols); 5137 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) { 5138 // Determine the canonical type arguments. 5139 ArrayRef<QualType> canonTypeArgs; 5140 SmallVector<QualType, 4> canonTypeArgsVec; 5141 if (!typeArgsAreCanonical) { 5142 canonTypeArgsVec.reserve(effectiveTypeArgs.size()); 5143 for (auto typeArg : effectiveTypeArgs) 5144 canonTypeArgsVec.push_back(getCanonicalType(typeArg)); 5145 canonTypeArgs = canonTypeArgsVec; 5146 } else { 5147 canonTypeArgs = effectiveTypeArgs; 5148 } 5149 5150 ArrayRef<ObjCProtocolDecl *> canonProtocols; 5151 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec; 5152 if (!protocolsSorted) { 5153 canonProtocolsVec.append(protocols.begin(), protocols.end()); 5154 SortAndUniqueProtocols(canonProtocolsVec); 5155 canonProtocols = canonProtocolsVec; 5156 } else { 5157 canonProtocols = protocols; 5158 } 5159 5160 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs, 5161 canonProtocols, isKindOf); 5162 5163 // Regenerate InsertPos. 5164 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos); 5165 } 5166 5167 unsigned size = sizeof(ObjCObjectTypeImpl); 5168 size += typeArgs.size() * sizeof(QualType); 5169 size += protocols.size() * sizeof(ObjCProtocolDecl *); 5170 void *mem = Allocate(size, TypeAlignment); 5171 auto *T = 5172 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols, 5173 isKindOf); 5174 5175 Types.push_back(T); 5176 ObjCObjectTypes.InsertNode(T, InsertPos); 5177 return QualType(T, 0); 5178 } 5179 5180 /// Apply Objective-C protocol qualifiers to the given type. 5181 /// If this is for the canonical type of a type parameter, we can apply 5182 /// protocol qualifiers on the ObjCObjectPointerType. 5183 QualType 5184 ASTContext::applyObjCProtocolQualifiers(QualType type, 5185 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError, 5186 bool allowOnPointerType) const { 5187 hasError = false; 5188 5189 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) { 5190 return getObjCTypeParamType(objT->getDecl(), protocols); 5191 } 5192 5193 // Apply protocol qualifiers to ObjCObjectPointerType. 5194 if (allowOnPointerType) { 5195 if (const auto *objPtr = 5196 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) { 5197 const ObjCObjectType *objT = objPtr->getObjectType(); 5198 // Merge protocol lists and construct ObjCObjectType. 5199 SmallVector<ObjCProtocolDecl*, 8> protocolsVec; 5200 protocolsVec.append(objT->qual_begin(), 5201 objT->qual_end()); 5202 protocolsVec.append(protocols.begin(), protocols.end()); 5203 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec; 5204 type = getObjCObjectType( 5205 objT->getBaseType(), 5206 objT->getTypeArgsAsWritten(), 5207 protocols, 5208 objT->isKindOfTypeAsWritten()); 5209 return getObjCObjectPointerType(type); 5210 } 5211 } 5212 5213 // Apply protocol qualifiers to ObjCObjectType. 5214 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){ 5215 // FIXME: Check for protocols to which the class type is already 5216 // known to conform. 5217 5218 return getObjCObjectType(objT->getBaseType(), 5219 objT->getTypeArgsAsWritten(), 5220 protocols, 5221 objT->isKindOfTypeAsWritten()); 5222 } 5223 5224 // If the canonical type is ObjCObjectType, ... 5225 if (type->isObjCObjectType()) { 5226 // Silently overwrite any existing protocol qualifiers. 5227 // TODO: determine whether that's the right thing to do. 5228 5229 // FIXME: Check for protocols to which the class type is already 5230 // known to conform. 5231 return getObjCObjectType(type, {}, protocols, false); 5232 } 5233 5234 // id<protocol-list> 5235 if (type->isObjCIdType()) { 5236 const auto *objPtr = type->castAs<ObjCObjectPointerType>(); 5237 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols, 5238 objPtr->isKindOfType()); 5239 return getObjCObjectPointerType(type); 5240 } 5241 5242 // Class<protocol-list> 5243 if (type->isObjCClassType()) { 5244 const auto *objPtr = type->castAs<ObjCObjectPointerType>(); 5245 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols, 5246 objPtr->isKindOfType()); 5247 return getObjCObjectPointerType(type); 5248 } 5249 5250 hasError = true; 5251 return type; 5252 } 5253 5254 QualType 5255 ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl, 5256 ArrayRef<ObjCProtocolDecl *> protocols) const { 5257 // Look in the folding set for an existing type. 5258 llvm::FoldingSetNodeID ID; 5259 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols); 5260 void *InsertPos = nullptr; 5261 if (ObjCTypeParamType *TypeParam = 5262 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos)) 5263 return QualType(TypeParam, 0); 5264 5265 // We canonicalize to the underlying type. 5266 QualType Canonical = getCanonicalType(Decl->getUnderlyingType()); 5267 if (!protocols.empty()) { 5268 // Apply the protocol qualifers. 5269 bool hasError; 5270 Canonical = getCanonicalType(applyObjCProtocolQualifiers( 5271 Canonical, protocols, hasError, true /*allowOnPointerType*/)); 5272 assert(!hasError && "Error when apply protocol qualifier to bound type"); 5273 } 5274 5275 unsigned size = sizeof(ObjCTypeParamType); 5276 size += protocols.size() * sizeof(ObjCProtocolDecl *); 5277 void *mem = Allocate(size, TypeAlignment); 5278 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols); 5279 5280 Types.push_back(newType); 5281 ObjCTypeParamTypes.InsertNode(newType, InsertPos); 5282 return QualType(newType, 0); 5283 } 5284 5285 void ASTContext::adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig, 5286 ObjCTypeParamDecl *New) const { 5287 New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType())); 5288 // Update TypeForDecl after updating TypeSourceInfo. 5289 auto NewTypeParamTy = cast<ObjCTypeParamType>(New->getTypeForDecl()); 5290 SmallVector<ObjCProtocolDecl *, 8> protocols; 5291 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end()); 5292 QualType UpdatedTy = getObjCTypeParamType(New, protocols); 5293 New->setTypeForDecl(UpdatedTy.getTypePtr()); 5294 } 5295 5296 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's 5297 /// protocol list adopt all protocols in QT's qualified-id protocol 5298 /// list. 5299 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT, 5300 ObjCInterfaceDecl *IC) { 5301 if (!QT->isObjCQualifiedIdType()) 5302 return false; 5303 5304 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) { 5305 // If both the right and left sides have qualifiers. 5306 for (auto *Proto : OPT->quals()) { 5307 if (!IC->ClassImplementsProtocol(Proto, false)) 5308 return false; 5309 } 5310 return true; 5311 } 5312 return false; 5313 } 5314 5315 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in 5316 /// QT's qualified-id protocol list adopt all protocols in IDecl's list 5317 /// of protocols. 5318 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT, 5319 ObjCInterfaceDecl *IDecl) { 5320 if (!QT->isObjCQualifiedIdType()) 5321 return false; 5322 const auto *OPT = QT->getAs<ObjCObjectPointerType>(); 5323 if (!OPT) 5324 return false; 5325 if (!IDecl->hasDefinition()) 5326 return false; 5327 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols; 5328 CollectInheritedProtocols(IDecl, InheritedProtocols); 5329 if (InheritedProtocols.empty()) 5330 return false; 5331 // Check that if every protocol in list of id<plist> conforms to a protocol 5332 // of IDecl's, then bridge casting is ok. 5333 bool Conforms = false; 5334 for (auto *Proto : OPT->quals()) { 5335 Conforms = false; 5336 for (auto *PI : InheritedProtocols) { 5337 if (ProtocolCompatibleWithProtocol(Proto, PI)) { 5338 Conforms = true; 5339 break; 5340 } 5341 } 5342 if (!Conforms) 5343 break; 5344 } 5345 if (Conforms) 5346 return true; 5347 5348 for (auto *PI : InheritedProtocols) { 5349 // If both the right and left sides have qualifiers. 5350 bool Adopts = false; 5351 for (auto *Proto : OPT->quals()) { 5352 // return 'true' if 'PI' is in the inheritance hierarchy of Proto 5353 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto))) 5354 break; 5355 } 5356 if (!Adopts) 5357 return false; 5358 } 5359 return true; 5360 } 5361 5362 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for 5363 /// the given object type. 5364 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const { 5365 llvm::FoldingSetNodeID ID; 5366 ObjCObjectPointerType::Profile(ID, ObjectT); 5367 5368 void *InsertPos = nullptr; 5369 if (ObjCObjectPointerType *QT = 5370 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 5371 return QualType(QT, 0); 5372 5373 // Find the canonical object type. 5374 QualType Canonical; 5375 if (!ObjectT.isCanonical()) { 5376 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT)); 5377 5378 // Regenerate InsertPos. 5379 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 5380 } 5381 5382 // No match. 5383 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment); 5384 auto *QType = 5385 new (Mem) ObjCObjectPointerType(Canonical, ObjectT); 5386 5387 Types.push_back(QType); 5388 ObjCObjectPointerTypes.InsertNode(QType, InsertPos); 5389 return QualType(QType, 0); 5390 } 5391 5392 /// getObjCInterfaceType - Return the unique reference to the type for the 5393 /// specified ObjC interface decl. The list of protocols is optional. 5394 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl, 5395 ObjCInterfaceDecl *PrevDecl) const { 5396 if (Decl->TypeForDecl) 5397 return QualType(Decl->TypeForDecl, 0); 5398 5399 if (PrevDecl) { 5400 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl"); 5401 Decl->TypeForDecl = PrevDecl->TypeForDecl; 5402 return QualType(PrevDecl->TypeForDecl, 0); 5403 } 5404 5405 // Prefer the definition, if there is one. 5406 if (const ObjCInterfaceDecl *Def = Decl->getDefinition()) 5407 Decl = Def; 5408 5409 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment); 5410 auto *T = new (Mem) ObjCInterfaceType(Decl); 5411 Decl->TypeForDecl = T; 5412 Types.push_back(T); 5413 return QualType(T, 0); 5414 } 5415 5416 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique 5417 /// TypeOfExprType AST's (since expression's are never shared). For example, 5418 /// multiple declarations that refer to "typeof(x)" all contain different 5419 /// DeclRefExpr's. This doesn't effect the type checker, since it operates 5420 /// on canonical type's (which are always unique). 5421 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const { 5422 TypeOfExprType *toe; 5423 if (tofExpr->isTypeDependent()) { 5424 llvm::FoldingSetNodeID ID; 5425 DependentTypeOfExprType::Profile(ID, *this, tofExpr); 5426 5427 void *InsertPos = nullptr; 5428 DependentTypeOfExprType *Canon 5429 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos); 5430 if (Canon) { 5431 // We already have a "canonical" version of an identical, dependent 5432 // typeof(expr) type. Use that as our canonical type. 5433 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, 5434 QualType((TypeOfExprType*)Canon, 0)); 5435 } else { 5436 // Build a new, canonical typeof(expr) type. 5437 Canon 5438 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr); 5439 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos); 5440 toe = Canon; 5441 } 5442 } else { 5443 QualType Canonical = getCanonicalType(tofExpr->getType()); 5444 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical); 5445 } 5446 Types.push_back(toe); 5447 return QualType(toe, 0); 5448 } 5449 5450 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique 5451 /// TypeOfType nodes. The only motivation to unique these nodes would be 5452 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be 5453 /// an issue. This doesn't affect the type checker, since it operates 5454 /// on canonical types (which are always unique). 5455 QualType ASTContext::getTypeOfType(QualType tofType) const { 5456 QualType Canonical = getCanonicalType(tofType); 5457 auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical); 5458 Types.push_back(tot); 5459 return QualType(tot, 0); 5460 } 5461 5462 /// getReferenceQualifiedType - Given an expr, will return the type for 5463 /// that expression, as in [dcl.type.simple]p4 but without taking id-expressions 5464 /// and class member access into account. 5465 QualType ASTContext::getReferenceQualifiedType(const Expr *E) const { 5466 // C++11 [dcl.type.simple]p4: 5467 // [...] 5468 QualType T = E->getType(); 5469 switch (E->getValueKind()) { 5470 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the 5471 // type of e; 5472 case VK_XValue: 5473 return getRValueReferenceType(T); 5474 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the 5475 // type of e; 5476 case VK_LValue: 5477 return getLValueReferenceType(T); 5478 // - otherwise, decltype(e) is the type of e. 5479 case VK_PRValue: 5480 return T; 5481 } 5482 llvm_unreachable("Unknown value kind"); 5483 } 5484 5485 /// Unlike many "get<Type>" functions, we don't unique DecltypeType 5486 /// nodes. This would never be helpful, since each such type has its own 5487 /// expression, and would not give a significant memory saving, since there 5488 /// is an Expr tree under each such type. 5489 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const { 5490 DecltypeType *dt; 5491 5492 // C++11 [temp.type]p2: 5493 // If an expression e involves a template parameter, decltype(e) denotes a 5494 // unique dependent type. Two such decltype-specifiers refer to the same 5495 // type only if their expressions are equivalent (14.5.6.1). 5496 if (e->isInstantiationDependent()) { 5497 llvm::FoldingSetNodeID ID; 5498 DependentDecltypeType::Profile(ID, *this, e); 5499 5500 void *InsertPos = nullptr; 5501 DependentDecltypeType *Canon 5502 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos); 5503 if (!Canon) { 5504 // Build a new, canonical decltype(expr) type. 5505 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e); 5506 DependentDecltypeTypes.InsertNode(Canon, InsertPos); 5507 } 5508 dt = new (*this, TypeAlignment) 5509 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0)); 5510 } else { 5511 dt = new (*this, TypeAlignment) 5512 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType)); 5513 } 5514 Types.push_back(dt); 5515 return QualType(dt, 0); 5516 } 5517 5518 /// getUnaryTransformationType - We don't unique these, since the memory 5519 /// savings are minimal and these are rare. 5520 QualType ASTContext::getUnaryTransformType(QualType BaseType, 5521 QualType UnderlyingType, 5522 UnaryTransformType::UTTKind Kind) 5523 const { 5524 UnaryTransformType *ut = nullptr; 5525 5526 if (BaseType->isDependentType()) { 5527 // Look in the folding set for an existing type. 5528 llvm::FoldingSetNodeID ID; 5529 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind); 5530 5531 void *InsertPos = nullptr; 5532 DependentUnaryTransformType *Canon 5533 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos); 5534 5535 if (!Canon) { 5536 // Build a new, canonical __underlying_type(type) type. 5537 Canon = new (*this, TypeAlignment) 5538 DependentUnaryTransformType(*this, getCanonicalType(BaseType), 5539 Kind); 5540 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos); 5541 } 5542 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType, 5543 QualType(), Kind, 5544 QualType(Canon, 0)); 5545 } else { 5546 QualType CanonType = getCanonicalType(UnderlyingType); 5547 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType, 5548 UnderlyingType, Kind, 5549 CanonType); 5550 } 5551 Types.push_back(ut); 5552 return QualType(ut, 0); 5553 } 5554 5555 /// getAutoType - Return the uniqued reference to the 'auto' type which has been 5556 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the 5557 /// canonical deduced-but-dependent 'auto' type. 5558 QualType 5559 ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, 5560 bool IsDependent, bool IsPack, 5561 ConceptDecl *TypeConstraintConcept, 5562 ArrayRef<TemplateArgument> TypeConstraintArgs) const { 5563 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack"); 5564 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && 5565 !TypeConstraintConcept && !IsDependent) 5566 return getAutoDeductType(); 5567 5568 // Look in the folding set for an existing type. 5569 void *InsertPos = nullptr; 5570 llvm::FoldingSetNodeID ID; 5571 AutoType::Profile(ID, *this, DeducedType, Keyword, IsDependent, 5572 TypeConstraintConcept, TypeConstraintArgs); 5573 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos)) 5574 return QualType(AT, 0); 5575 5576 void *Mem = Allocate(sizeof(AutoType) + 5577 sizeof(TemplateArgument) * TypeConstraintArgs.size(), 5578 TypeAlignment); 5579 auto *AT = new (Mem) AutoType( 5580 DeducedType, Keyword, 5581 (IsDependent ? TypeDependence::DependentInstantiation 5582 : TypeDependence::None) | 5583 (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None), 5584 TypeConstraintConcept, TypeConstraintArgs); 5585 Types.push_back(AT); 5586 if (InsertPos) 5587 AutoTypes.InsertNode(AT, InsertPos); 5588 return QualType(AT, 0); 5589 } 5590 5591 /// Return the uniqued reference to the deduced template specialization type 5592 /// which has been deduced to the given type, or to the canonical undeduced 5593 /// such type, or the canonical deduced-but-dependent such type. 5594 QualType ASTContext::getDeducedTemplateSpecializationType( 5595 TemplateName Template, QualType DeducedType, bool IsDependent) const { 5596 // Look in the folding set for an existing type. 5597 void *InsertPos = nullptr; 5598 llvm::FoldingSetNodeID ID; 5599 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType, 5600 IsDependent); 5601 if (DeducedTemplateSpecializationType *DTST = 5602 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos)) 5603 return QualType(DTST, 0); 5604 5605 auto *DTST = new (*this, TypeAlignment) 5606 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent); 5607 Types.push_back(DTST); 5608 if (InsertPos) 5609 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos); 5610 return QualType(DTST, 0); 5611 } 5612 5613 /// getAtomicType - Return the uniqued reference to the atomic type for 5614 /// the given value type. 5615 QualType ASTContext::getAtomicType(QualType T) const { 5616 // Unique pointers, to guarantee there is only one pointer of a particular 5617 // structure. 5618 llvm::FoldingSetNodeID ID; 5619 AtomicType::Profile(ID, T); 5620 5621 void *InsertPos = nullptr; 5622 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos)) 5623 return QualType(AT, 0); 5624 5625 // If the atomic value type isn't canonical, this won't be a canonical type 5626 // either, so fill in the canonical type field. 5627 QualType Canonical; 5628 if (!T.isCanonical()) { 5629 Canonical = getAtomicType(getCanonicalType(T)); 5630 5631 // Get the new insert position for the node we care about. 5632 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos); 5633 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 5634 } 5635 auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical); 5636 Types.push_back(New); 5637 AtomicTypes.InsertNode(New, InsertPos); 5638 return QualType(New, 0); 5639 } 5640 5641 /// getAutoDeductType - Get type pattern for deducing against 'auto'. 5642 QualType ASTContext::getAutoDeductType() const { 5643 if (AutoDeductTy.isNull()) 5644 AutoDeductTy = QualType(new (*this, TypeAlignment) 5645 AutoType(QualType(), AutoTypeKeyword::Auto, 5646 TypeDependence::None, 5647 /*concept*/ nullptr, /*args*/ {}), 5648 0); 5649 return AutoDeductTy; 5650 } 5651 5652 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'. 5653 QualType ASTContext::getAutoRRefDeductType() const { 5654 if (AutoRRefDeductTy.isNull()) 5655 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType()); 5656 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern"); 5657 return AutoRRefDeductTy; 5658 } 5659 5660 /// getTagDeclType - Return the unique reference to the type for the 5661 /// specified TagDecl (struct/union/class/enum) decl. 5662 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const { 5663 assert(Decl); 5664 // FIXME: What is the design on getTagDeclType when it requires casting 5665 // away const? mutable? 5666 return getTypeDeclType(const_cast<TagDecl*>(Decl)); 5667 } 5668 5669 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result 5670 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and 5671 /// needs to agree with the definition in <stddef.h>. 5672 CanQualType ASTContext::getSizeType() const { 5673 return getFromTargetType(Target->getSizeType()); 5674 } 5675 5676 /// Return the unique signed counterpart of the integer type 5677 /// corresponding to size_t. 5678 CanQualType ASTContext::getSignedSizeType() const { 5679 return getFromTargetType(Target->getSignedSizeType()); 5680 } 5681 5682 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5). 5683 CanQualType ASTContext::getIntMaxType() const { 5684 return getFromTargetType(Target->getIntMaxType()); 5685 } 5686 5687 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5). 5688 CanQualType ASTContext::getUIntMaxType() const { 5689 return getFromTargetType(Target->getUIntMaxType()); 5690 } 5691 5692 /// getSignedWCharType - Return the type of "signed wchar_t". 5693 /// Used when in C++, as a GCC extension. 5694 QualType ASTContext::getSignedWCharType() const { 5695 // FIXME: derive from "Target" ? 5696 return WCharTy; 5697 } 5698 5699 /// getUnsignedWCharType - Return the type of "unsigned wchar_t". 5700 /// Used when in C++, as a GCC extension. 5701 QualType ASTContext::getUnsignedWCharType() const { 5702 // FIXME: derive from "Target" ? 5703 return UnsignedIntTy; 5704 } 5705 5706 QualType ASTContext::getIntPtrType() const { 5707 return getFromTargetType(Target->getIntPtrType()); 5708 } 5709 5710 QualType ASTContext::getUIntPtrType() const { 5711 return getCorrespondingUnsignedType(getIntPtrType()); 5712 } 5713 5714 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17) 5715 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9). 5716 QualType ASTContext::getPointerDiffType() const { 5717 return getFromTargetType(Target->getPtrDiffType(0)); 5718 } 5719 5720 /// Return the unique unsigned counterpart of "ptrdiff_t" 5721 /// integer type. The standard (C11 7.21.6.1p7) refers to this type 5722 /// in the definition of %tu format specifier. 5723 QualType ASTContext::getUnsignedPointerDiffType() const { 5724 return getFromTargetType(Target->getUnsignedPtrDiffType(0)); 5725 } 5726 5727 /// Return the unique type for "pid_t" defined in 5728 /// <sys/types.h>. We need this to compute the correct type for vfork(). 5729 QualType ASTContext::getProcessIDType() const { 5730 return getFromTargetType(Target->getProcessIDType()); 5731 } 5732 5733 //===----------------------------------------------------------------------===// 5734 // Type Operators 5735 //===----------------------------------------------------------------------===// 5736 5737 CanQualType ASTContext::getCanonicalParamType(QualType T) const { 5738 // Push qualifiers into arrays, and then discard any remaining 5739 // qualifiers. 5740 T = getCanonicalType(T); 5741 T = getVariableArrayDecayedType(T); 5742 const Type *Ty = T.getTypePtr(); 5743 QualType Result; 5744 if (isa<ArrayType>(Ty)) { 5745 Result = getArrayDecayedType(QualType(Ty,0)); 5746 } else if (isa<FunctionType>(Ty)) { 5747 Result = getPointerType(QualType(Ty, 0)); 5748 } else { 5749 Result = QualType(Ty, 0); 5750 } 5751 5752 return CanQualType::CreateUnsafe(Result); 5753 } 5754 5755 QualType ASTContext::getUnqualifiedArrayType(QualType type, 5756 Qualifiers &quals) { 5757 SplitQualType splitType = type.getSplitUnqualifiedType(); 5758 5759 // FIXME: getSplitUnqualifiedType() actually walks all the way to 5760 // the unqualified desugared type and then drops it on the floor. 5761 // We then have to strip that sugar back off with 5762 // getUnqualifiedDesugaredType(), which is silly. 5763 const auto *AT = 5764 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType()); 5765 5766 // If we don't have an array, just use the results in splitType. 5767 if (!AT) { 5768 quals = splitType.Quals; 5769 return QualType(splitType.Ty, 0); 5770 } 5771 5772 // Otherwise, recurse on the array's element type. 5773 QualType elementType = AT->getElementType(); 5774 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals); 5775 5776 // If that didn't change the element type, AT has no qualifiers, so we 5777 // can just use the results in splitType. 5778 if (elementType == unqualElementType) { 5779 assert(quals.empty()); // from the recursive call 5780 quals = splitType.Quals; 5781 return QualType(splitType.Ty, 0); 5782 } 5783 5784 // Otherwise, add in the qualifiers from the outermost type, then 5785 // build the type back up. 5786 quals.addConsistentQualifiers(splitType.Quals); 5787 5788 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 5789 return getConstantArrayType(unqualElementType, CAT->getSize(), 5790 CAT->getSizeExpr(), CAT->getSizeModifier(), 0); 5791 } 5792 5793 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) { 5794 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0); 5795 } 5796 5797 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) { 5798 return getVariableArrayType(unqualElementType, 5799 VAT->getSizeExpr(), 5800 VAT->getSizeModifier(), 5801 VAT->getIndexTypeCVRQualifiers(), 5802 VAT->getBracketsRange()); 5803 } 5804 5805 const auto *DSAT = cast<DependentSizedArrayType>(AT); 5806 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(), 5807 DSAT->getSizeModifier(), 0, 5808 SourceRange()); 5809 } 5810 5811 /// Attempt to unwrap two types that may both be array types with the same bound 5812 /// (or both be array types of unknown bound) for the purpose of comparing the 5813 /// cv-decomposition of two types per C++ [conv.qual]. 5814 void ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2) { 5815 while (true) { 5816 auto *AT1 = getAsArrayType(T1); 5817 if (!AT1) 5818 return; 5819 5820 auto *AT2 = getAsArrayType(T2); 5821 if (!AT2) 5822 return; 5823 5824 // If we don't have two array types with the same constant bound nor two 5825 // incomplete array types, we've unwrapped everything we can. 5826 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) { 5827 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2); 5828 if (!CAT2 || CAT1->getSize() != CAT2->getSize()) 5829 return; 5830 } else if (!isa<IncompleteArrayType>(AT1) || 5831 !isa<IncompleteArrayType>(AT2)) { 5832 return; 5833 } 5834 5835 T1 = AT1->getElementType(); 5836 T2 = AT2->getElementType(); 5837 } 5838 } 5839 5840 /// Attempt to unwrap two types that may be similar (C++ [conv.qual]). 5841 /// 5842 /// If T1 and T2 are both pointer types of the same kind, or both array types 5843 /// with the same bound, unwraps layers from T1 and T2 until a pointer type is 5844 /// unwrapped. Top-level qualifiers on T1 and T2 are ignored. 5845 /// 5846 /// This function will typically be called in a loop that successively 5847 /// "unwraps" pointer and pointer-to-member types to compare them at each 5848 /// level. 5849 /// 5850 /// \return \c true if a pointer type was unwrapped, \c false if we reached a 5851 /// pair of types that can't be unwrapped further. 5852 bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) { 5853 UnwrapSimilarArrayTypes(T1, T2); 5854 5855 const auto *T1PtrType = T1->getAs<PointerType>(); 5856 const auto *T2PtrType = T2->getAs<PointerType>(); 5857 if (T1PtrType && T2PtrType) { 5858 T1 = T1PtrType->getPointeeType(); 5859 T2 = T2PtrType->getPointeeType(); 5860 return true; 5861 } 5862 5863 const auto *T1MPType = T1->getAs<MemberPointerType>(); 5864 const auto *T2MPType = T2->getAs<MemberPointerType>(); 5865 if (T1MPType && T2MPType && 5866 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0), 5867 QualType(T2MPType->getClass(), 0))) { 5868 T1 = T1MPType->getPointeeType(); 5869 T2 = T2MPType->getPointeeType(); 5870 return true; 5871 } 5872 5873 if (getLangOpts().ObjC) { 5874 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>(); 5875 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>(); 5876 if (T1OPType && T2OPType) { 5877 T1 = T1OPType->getPointeeType(); 5878 T2 = T2OPType->getPointeeType(); 5879 return true; 5880 } 5881 } 5882 5883 // FIXME: Block pointers, too? 5884 5885 return false; 5886 } 5887 5888 bool ASTContext::hasSimilarType(QualType T1, QualType T2) { 5889 while (true) { 5890 Qualifiers Quals; 5891 T1 = getUnqualifiedArrayType(T1, Quals); 5892 T2 = getUnqualifiedArrayType(T2, Quals); 5893 if (hasSameType(T1, T2)) 5894 return true; 5895 if (!UnwrapSimilarTypes(T1, T2)) 5896 return false; 5897 } 5898 } 5899 5900 bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) { 5901 while (true) { 5902 Qualifiers Quals1, Quals2; 5903 T1 = getUnqualifiedArrayType(T1, Quals1); 5904 T2 = getUnqualifiedArrayType(T2, Quals2); 5905 5906 Quals1.removeCVRQualifiers(); 5907 Quals2.removeCVRQualifiers(); 5908 if (Quals1 != Quals2) 5909 return false; 5910 5911 if (hasSameType(T1, T2)) 5912 return true; 5913 5914 if (!UnwrapSimilarTypes(T1, T2)) 5915 return false; 5916 } 5917 } 5918 5919 DeclarationNameInfo 5920 ASTContext::getNameForTemplate(TemplateName Name, 5921 SourceLocation NameLoc) const { 5922 switch (Name.getKind()) { 5923 case TemplateName::QualifiedTemplate: 5924 case TemplateName::Template: 5925 // DNInfo work in progress: CHECKME: what about DNLoc? 5926 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(), 5927 NameLoc); 5928 5929 case TemplateName::OverloadedTemplate: { 5930 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate(); 5931 // DNInfo work in progress: CHECKME: what about DNLoc? 5932 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc); 5933 } 5934 5935 case TemplateName::AssumedTemplate: { 5936 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName(); 5937 return DeclarationNameInfo(Storage->getDeclName(), NameLoc); 5938 } 5939 5940 case TemplateName::DependentTemplate: { 5941 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 5942 DeclarationName DName; 5943 if (DTN->isIdentifier()) { 5944 DName = DeclarationNames.getIdentifier(DTN->getIdentifier()); 5945 return DeclarationNameInfo(DName, NameLoc); 5946 } else { 5947 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator()); 5948 // DNInfo work in progress: FIXME: source locations? 5949 DeclarationNameLoc DNLoc = 5950 DeclarationNameLoc::makeCXXOperatorNameLoc(SourceRange()); 5951 return DeclarationNameInfo(DName, NameLoc, DNLoc); 5952 } 5953 } 5954 5955 case TemplateName::SubstTemplateTemplateParm: { 5956 SubstTemplateTemplateParmStorage *subst 5957 = Name.getAsSubstTemplateTemplateParm(); 5958 return DeclarationNameInfo(subst->getParameter()->getDeclName(), 5959 NameLoc); 5960 } 5961 5962 case TemplateName::SubstTemplateTemplateParmPack: { 5963 SubstTemplateTemplateParmPackStorage *subst 5964 = Name.getAsSubstTemplateTemplateParmPack(); 5965 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(), 5966 NameLoc); 5967 } 5968 } 5969 5970 llvm_unreachable("bad template name kind!"); 5971 } 5972 5973 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const { 5974 switch (Name.getKind()) { 5975 case TemplateName::QualifiedTemplate: 5976 case TemplateName::Template: { 5977 TemplateDecl *Template = Name.getAsTemplateDecl(); 5978 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template)) 5979 Template = getCanonicalTemplateTemplateParmDecl(TTP); 5980 5981 // The canonical template name is the canonical template declaration. 5982 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl())); 5983 } 5984 5985 case TemplateName::OverloadedTemplate: 5986 case TemplateName::AssumedTemplate: 5987 llvm_unreachable("cannot canonicalize unresolved template"); 5988 5989 case TemplateName::DependentTemplate: { 5990 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 5991 assert(DTN && "Non-dependent template names must refer to template decls."); 5992 return DTN->CanonicalTemplateName; 5993 } 5994 5995 case TemplateName::SubstTemplateTemplateParm: { 5996 SubstTemplateTemplateParmStorage *subst 5997 = Name.getAsSubstTemplateTemplateParm(); 5998 return getCanonicalTemplateName(subst->getReplacement()); 5999 } 6000 6001 case TemplateName::SubstTemplateTemplateParmPack: { 6002 SubstTemplateTemplateParmPackStorage *subst 6003 = Name.getAsSubstTemplateTemplateParmPack(); 6004 TemplateTemplateParmDecl *canonParameter 6005 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack()); 6006 TemplateArgument canonArgPack 6007 = getCanonicalTemplateArgument(subst->getArgumentPack()); 6008 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack); 6009 } 6010 } 6011 6012 llvm_unreachable("bad template name!"); 6013 } 6014 6015 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) { 6016 X = getCanonicalTemplateName(X); 6017 Y = getCanonicalTemplateName(Y); 6018 return X.getAsVoidPointer() == Y.getAsVoidPointer(); 6019 } 6020 6021 TemplateArgument 6022 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const { 6023 switch (Arg.getKind()) { 6024 case TemplateArgument::Null: 6025 return Arg; 6026 6027 case TemplateArgument::Expression: 6028 return Arg; 6029 6030 case TemplateArgument::Declaration: { 6031 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl()); 6032 return TemplateArgument(D, Arg.getParamTypeForDecl()); 6033 } 6034 6035 case TemplateArgument::NullPtr: 6036 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()), 6037 /*isNullPtr*/true); 6038 6039 case TemplateArgument::Template: 6040 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate())); 6041 6042 case TemplateArgument::TemplateExpansion: 6043 return TemplateArgument(getCanonicalTemplateName( 6044 Arg.getAsTemplateOrTemplatePattern()), 6045 Arg.getNumTemplateExpansions()); 6046 6047 case TemplateArgument::Integral: 6048 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType())); 6049 6050 case TemplateArgument::Type: 6051 return TemplateArgument(getCanonicalType(Arg.getAsType())); 6052 6053 case TemplateArgument::Pack: { 6054 if (Arg.pack_size() == 0) 6055 return Arg; 6056 6057 auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()]; 6058 unsigned Idx = 0; 6059 for (TemplateArgument::pack_iterator A = Arg.pack_begin(), 6060 AEnd = Arg.pack_end(); 6061 A != AEnd; (void)++A, ++Idx) 6062 CanonArgs[Idx] = getCanonicalTemplateArgument(*A); 6063 6064 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size())); 6065 } 6066 } 6067 6068 // Silence GCC warning 6069 llvm_unreachable("Unhandled template argument kind"); 6070 } 6071 6072 NestedNameSpecifier * 6073 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const { 6074 if (!NNS) 6075 return nullptr; 6076 6077 switch (NNS->getKind()) { 6078 case NestedNameSpecifier::Identifier: 6079 // Canonicalize the prefix but keep the identifier the same. 6080 return NestedNameSpecifier::Create(*this, 6081 getCanonicalNestedNameSpecifier(NNS->getPrefix()), 6082 NNS->getAsIdentifier()); 6083 6084 case NestedNameSpecifier::Namespace: 6085 // A namespace is canonical; build a nested-name-specifier with 6086 // this namespace and no prefix. 6087 return NestedNameSpecifier::Create(*this, nullptr, 6088 NNS->getAsNamespace()->getOriginalNamespace()); 6089 6090 case NestedNameSpecifier::NamespaceAlias: 6091 // A namespace is canonical; build a nested-name-specifier with 6092 // this namespace and no prefix. 6093 return NestedNameSpecifier::Create(*this, nullptr, 6094 NNS->getAsNamespaceAlias()->getNamespace() 6095 ->getOriginalNamespace()); 6096 6097 // The difference between TypeSpec and TypeSpecWithTemplate is that the 6098 // latter will have the 'template' keyword when printed. 6099 case NestedNameSpecifier::TypeSpec: 6100 case NestedNameSpecifier::TypeSpecWithTemplate: { 6101 const Type *T = getCanonicalType(NNS->getAsType()); 6102 6103 // If we have some kind of dependent-named type (e.g., "typename T::type"), 6104 // break it apart into its prefix and identifier, then reconsititute those 6105 // as the canonical nested-name-specifier. This is required to canonicalize 6106 // a dependent nested-name-specifier involving typedefs of dependent-name 6107 // types, e.g., 6108 // typedef typename T::type T1; 6109 // typedef typename T1::type T2; 6110 if (const auto *DNT = T->getAs<DependentNameType>()) 6111 return NestedNameSpecifier::Create( 6112 *this, DNT->getQualifier(), 6113 const_cast<IdentifierInfo *>(DNT->getIdentifier())); 6114 if (const auto *DTST = T->getAs<DependentTemplateSpecializationType>()) 6115 return NestedNameSpecifier::Create(*this, DTST->getQualifier(), true, 6116 const_cast<Type *>(T)); 6117 6118 // TODO: Set 'Template' parameter to true for other template types. 6119 return NestedNameSpecifier::Create(*this, nullptr, false, 6120 const_cast<Type *>(T)); 6121 } 6122 6123 case NestedNameSpecifier::Global: 6124 case NestedNameSpecifier::Super: 6125 // The global specifier and __super specifer are canonical and unique. 6126 return NNS; 6127 } 6128 6129 llvm_unreachable("Invalid NestedNameSpecifier::Kind!"); 6130 } 6131 6132 const ArrayType *ASTContext::getAsArrayType(QualType T) const { 6133 // Handle the non-qualified case efficiently. 6134 if (!T.hasLocalQualifiers()) { 6135 // Handle the common positive case fast. 6136 if (const auto *AT = dyn_cast<ArrayType>(T)) 6137 return AT; 6138 } 6139 6140 // Handle the common negative case fast. 6141 if (!isa<ArrayType>(T.getCanonicalType())) 6142 return nullptr; 6143 6144 // Apply any qualifiers from the array type to the element type. This 6145 // implements C99 6.7.3p8: "If the specification of an array type includes 6146 // any type qualifiers, the element type is so qualified, not the array type." 6147 6148 // If we get here, we either have type qualifiers on the type, or we have 6149 // sugar such as a typedef in the way. If we have type qualifiers on the type 6150 // we must propagate them down into the element type. 6151 6152 SplitQualType split = T.getSplitDesugaredType(); 6153 Qualifiers qs = split.Quals; 6154 6155 // If we have a simple case, just return now. 6156 const auto *ATy = dyn_cast<ArrayType>(split.Ty); 6157 if (!ATy || qs.empty()) 6158 return ATy; 6159 6160 // Otherwise, we have an array and we have qualifiers on it. Push the 6161 // qualifiers into the array element type and return a new array type. 6162 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs); 6163 6164 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy)) 6165 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(), 6166 CAT->getSizeExpr(), 6167 CAT->getSizeModifier(), 6168 CAT->getIndexTypeCVRQualifiers())); 6169 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy)) 6170 return cast<ArrayType>(getIncompleteArrayType(NewEltTy, 6171 IAT->getSizeModifier(), 6172 IAT->getIndexTypeCVRQualifiers())); 6173 6174 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy)) 6175 return cast<ArrayType>( 6176 getDependentSizedArrayType(NewEltTy, 6177 DSAT->getSizeExpr(), 6178 DSAT->getSizeModifier(), 6179 DSAT->getIndexTypeCVRQualifiers(), 6180 DSAT->getBracketsRange())); 6181 6182 const auto *VAT = cast<VariableArrayType>(ATy); 6183 return cast<ArrayType>(getVariableArrayType(NewEltTy, 6184 VAT->getSizeExpr(), 6185 VAT->getSizeModifier(), 6186 VAT->getIndexTypeCVRQualifiers(), 6187 VAT->getBracketsRange())); 6188 } 6189 6190 QualType ASTContext::getAdjustedParameterType(QualType T) const { 6191 if (T->isArrayType() || T->isFunctionType()) 6192 return getDecayedType(T); 6193 return T; 6194 } 6195 6196 QualType ASTContext::getSignatureParameterType(QualType T) const { 6197 T = getVariableArrayDecayedType(T); 6198 T = getAdjustedParameterType(T); 6199 return T.getUnqualifiedType(); 6200 } 6201 6202 QualType ASTContext::getExceptionObjectType(QualType T) const { 6203 // C++ [except.throw]p3: 6204 // A throw-expression initializes a temporary object, called the exception 6205 // object, the type of which is determined by removing any top-level 6206 // cv-qualifiers from the static type of the operand of throw and adjusting 6207 // the type from "array of T" or "function returning T" to "pointer to T" 6208 // or "pointer to function returning T", [...] 6209 T = getVariableArrayDecayedType(T); 6210 if (T->isArrayType() || T->isFunctionType()) 6211 T = getDecayedType(T); 6212 return T.getUnqualifiedType(); 6213 } 6214 6215 /// getArrayDecayedType - Return the properly qualified result of decaying the 6216 /// specified array type to a pointer. This operation is non-trivial when 6217 /// handling typedefs etc. The canonical type of "T" must be an array type, 6218 /// this returns a pointer to a properly qualified element of the array. 6219 /// 6220 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3. 6221 QualType ASTContext::getArrayDecayedType(QualType Ty) const { 6222 // Get the element type with 'getAsArrayType' so that we don't lose any 6223 // typedefs in the element type of the array. This also handles propagation 6224 // of type qualifiers from the array type into the element type if present 6225 // (C99 6.7.3p8). 6226 const ArrayType *PrettyArrayType = getAsArrayType(Ty); 6227 assert(PrettyArrayType && "Not an array type!"); 6228 6229 QualType PtrTy = getPointerType(PrettyArrayType->getElementType()); 6230 6231 // int x[restrict 4] -> int *restrict 6232 QualType Result = getQualifiedType(PtrTy, 6233 PrettyArrayType->getIndexTypeQualifiers()); 6234 6235 // int x[_Nullable] -> int * _Nullable 6236 if (auto Nullability = Ty->getNullability(*this)) { 6237 Result = const_cast<ASTContext *>(this)->getAttributedType( 6238 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result); 6239 } 6240 return Result; 6241 } 6242 6243 QualType ASTContext::getBaseElementType(const ArrayType *array) const { 6244 return getBaseElementType(array->getElementType()); 6245 } 6246 6247 QualType ASTContext::getBaseElementType(QualType type) const { 6248 Qualifiers qs; 6249 while (true) { 6250 SplitQualType split = type.getSplitDesugaredType(); 6251 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe(); 6252 if (!array) break; 6253 6254 type = array->getElementType(); 6255 qs.addConsistentQualifiers(split.Quals); 6256 } 6257 6258 return getQualifiedType(type, qs); 6259 } 6260 6261 /// getConstantArrayElementCount - Returns number of constant array elements. 6262 uint64_t 6263 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const { 6264 uint64_t ElementCount = 1; 6265 do { 6266 ElementCount *= CA->getSize().getZExtValue(); 6267 CA = dyn_cast_or_null<ConstantArrayType>( 6268 CA->getElementType()->getAsArrayTypeUnsafe()); 6269 } while (CA); 6270 return ElementCount; 6271 } 6272 6273 /// getFloatingRank - Return a relative rank for floating point types. 6274 /// This routine will assert if passed a built-in type that isn't a float. 6275 static FloatingRank getFloatingRank(QualType T) { 6276 if (const auto *CT = T->getAs<ComplexType>()) 6277 return getFloatingRank(CT->getElementType()); 6278 6279 switch (T->castAs<BuiltinType>()->getKind()) { 6280 default: llvm_unreachable("getFloatingRank(): not a floating type"); 6281 case BuiltinType::Float16: return Float16Rank; 6282 case BuiltinType::Half: return HalfRank; 6283 case BuiltinType::Float: return FloatRank; 6284 case BuiltinType::Double: return DoubleRank; 6285 case BuiltinType::LongDouble: return LongDoubleRank; 6286 case BuiltinType::Float128: return Float128Rank; 6287 case BuiltinType::BFloat16: return BFloat16Rank; 6288 } 6289 } 6290 6291 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating 6292 /// point or a complex type (based on typeDomain/typeSize). 6293 /// 'typeDomain' is a real floating point or complex type. 6294 /// 'typeSize' is a real floating point or complex type. 6295 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size, 6296 QualType Domain) const { 6297 FloatingRank EltRank = getFloatingRank(Size); 6298 if (Domain->isComplexType()) { 6299 switch (EltRank) { 6300 case BFloat16Rank: llvm_unreachable("Complex bfloat16 is not supported"); 6301 case Float16Rank: 6302 case HalfRank: llvm_unreachable("Complex half is not supported"); 6303 case FloatRank: return FloatComplexTy; 6304 case DoubleRank: return DoubleComplexTy; 6305 case LongDoubleRank: return LongDoubleComplexTy; 6306 case Float128Rank: return Float128ComplexTy; 6307 } 6308 } 6309 6310 assert(Domain->isRealFloatingType() && "Unknown domain!"); 6311 switch (EltRank) { 6312 case Float16Rank: return HalfTy; 6313 case BFloat16Rank: return BFloat16Ty; 6314 case HalfRank: return HalfTy; 6315 case FloatRank: return FloatTy; 6316 case DoubleRank: return DoubleTy; 6317 case LongDoubleRank: return LongDoubleTy; 6318 case Float128Rank: return Float128Ty; 6319 } 6320 llvm_unreachable("getFloatingRank(): illegal value for rank"); 6321 } 6322 6323 /// getFloatingTypeOrder - Compare the rank of the two specified floating 6324 /// point types, ignoring the domain of the type (i.e. 'double' == 6325 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If 6326 /// LHS < RHS, return -1. 6327 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const { 6328 FloatingRank LHSR = getFloatingRank(LHS); 6329 FloatingRank RHSR = getFloatingRank(RHS); 6330 6331 if (LHSR == RHSR) 6332 return 0; 6333 if (LHSR > RHSR) 6334 return 1; 6335 return -1; 6336 } 6337 6338 int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const { 6339 if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS)) 6340 return 0; 6341 return getFloatingTypeOrder(LHS, RHS); 6342 } 6343 6344 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This 6345 /// routine will assert if passed a built-in type that isn't an integer or enum, 6346 /// or if it is not canonicalized. 6347 unsigned ASTContext::getIntegerRank(const Type *T) const { 6348 assert(T->isCanonicalUnqualified() && "T should be canonicalized"); 6349 6350 // Results in this 'losing' to any type of the same size, but winning if 6351 // larger. 6352 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 6353 return 0 + (EIT->getNumBits() << 3); 6354 6355 switch (cast<BuiltinType>(T)->getKind()) { 6356 default: llvm_unreachable("getIntegerRank(): not a built-in integer"); 6357 case BuiltinType::Bool: 6358 return 1 + (getIntWidth(BoolTy) << 3); 6359 case BuiltinType::Char_S: 6360 case BuiltinType::Char_U: 6361 case BuiltinType::SChar: 6362 case BuiltinType::UChar: 6363 return 2 + (getIntWidth(CharTy) << 3); 6364 case BuiltinType::Short: 6365 case BuiltinType::UShort: 6366 return 3 + (getIntWidth(ShortTy) << 3); 6367 case BuiltinType::Int: 6368 case BuiltinType::UInt: 6369 return 4 + (getIntWidth(IntTy) << 3); 6370 case BuiltinType::Long: 6371 case BuiltinType::ULong: 6372 return 5 + (getIntWidth(LongTy) << 3); 6373 case BuiltinType::LongLong: 6374 case BuiltinType::ULongLong: 6375 return 6 + (getIntWidth(LongLongTy) << 3); 6376 case BuiltinType::Int128: 6377 case BuiltinType::UInt128: 6378 return 7 + (getIntWidth(Int128Ty) << 3); 6379 } 6380 } 6381 6382 /// Whether this is a promotable bitfield reference according 6383 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions). 6384 /// 6385 /// \returns the type this bit-field will promote to, or NULL if no 6386 /// promotion occurs. 6387 QualType ASTContext::isPromotableBitField(Expr *E) const { 6388 if (E->isTypeDependent() || E->isValueDependent()) 6389 return {}; 6390 6391 // C++ [conv.prom]p5: 6392 // If the bit-field has an enumerated type, it is treated as any other 6393 // value of that type for promotion purposes. 6394 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType()) 6395 return {}; 6396 6397 // FIXME: We should not do this unless E->refersToBitField() is true. This 6398 // matters in C where getSourceBitField() will find bit-fields for various 6399 // cases where the source expression is not a bit-field designator. 6400 6401 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields? 6402 if (!Field) 6403 return {}; 6404 6405 QualType FT = Field->getType(); 6406 6407 uint64_t BitWidth = Field->getBitWidthValue(*this); 6408 uint64_t IntSize = getTypeSize(IntTy); 6409 // C++ [conv.prom]p5: 6410 // A prvalue for an integral bit-field can be converted to a prvalue of type 6411 // int if int can represent all the values of the bit-field; otherwise, it 6412 // can be converted to unsigned int if unsigned int can represent all the 6413 // values of the bit-field. If the bit-field is larger yet, no integral 6414 // promotion applies to it. 6415 // C11 6.3.1.1/2: 6416 // [For a bit-field of type _Bool, int, signed int, or unsigned int:] 6417 // If an int can represent all values of the original type (as restricted by 6418 // the width, for a bit-field), the value is converted to an int; otherwise, 6419 // it is converted to an unsigned int. 6420 // 6421 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int. 6422 // We perform that promotion here to match GCC and C++. 6423 // FIXME: C does not permit promotion of an enum bit-field whose rank is 6424 // greater than that of 'int'. We perform that promotion to match GCC. 6425 if (BitWidth < IntSize) 6426 return IntTy; 6427 6428 if (BitWidth == IntSize) 6429 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy; 6430 6431 // Bit-fields wider than int are not subject to promotions, and therefore act 6432 // like the base type. GCC has some weird bugs in this area that we 6433 // deliberately do not follow (GCC follows a pre-standard resolution to 6434 // C's DR315 which treats bit-width as being part of the type, and this leaks 6435 // into their semantics in some cases). 6436 return {}; 6437 } 6438 6439 /// getPromotedIntegerType - Returns the type that Promotable will 6440 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable 6441 /// integer type. 6442 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const { 6443 assert(!Promotable.isNull()); 6444 assert(Promotable->isPromotableIntegerType()); 6445 if (const auto *ET = Promotable->getAs<EnumType>()) 6446 return ET->getDecl()->getPromotionType(); 6447 6448 if (const auto *BT = Promotable->getAs<BuiltinType>()) { 6449 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t 6450 // (3.9.1) can be converted to a prvalue of the first of the following 6451 // types that can represent all the values of its underlying type: 6452 // int, unsigned int, long int, unsigned long int, long long int, or 6453 // unsigned long long int [...] 6454 // FIXME: Is there some better way to compute this? 6455 if (BT->getKind() == BuiltinType::WChar_S || 6456 BT->getKind() == BuiltinType::WChar_U || 6457 BT->getKind() == BuiltinType::Char8 || 6458 BT->getKind() == BuiltinType::Char16 || 6459 BT->getKind() == BuiltinType::Char32) { 6460 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S; 6461 uint64_t FromSize = getTypeSize(BT); 6462 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy, 6463 LongLongTy, UnsignedLongLongTy }; 6464 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) { 6465 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]); 6466 if (FromSize < ToSize || 6467 (FromSize == ToSize && 6468 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) 6469 return PromoteTypes[Idx]; 6470 } 6471 llvm_unreachable("char type should fit into long long"); 6472 } 6473 } 6474 6475 // At this point, we should have a signed or unsigned integer type. 6476 if (Promotable->isSignedIntegerType()) 6477 return IntTy; 6478 uint64_t PromotableSize = getIntWidth(Promotable); 6479 uint64_t IntSize = getIntWidth(IntTy); 6480 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize); 6481 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy; 6482 } 6483 6484 /// Recurses in pointer/array types until it finds an objc retainable 6485 /// type and returns its ownership. 6486 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const { 6487 while (!T.isNull()) { 6488 if (T.getObjCLifetime() != Qualifiers::OCL_None) 6489 return T.getObjCLifetime(); 6490 if (T->isArrayType()) 6491 T = getBaseElementType(T); 6492 else if (const auto *PT = T->getAs<PointerType>()) 6493 T = PT->getPointeeType(); 6494 else if (const auto *RT = T->getAs<ReferenceType>()) 6495 T = RT->getPointeeType(); 6496 else 6497 break; 6498 } 6499 6500 return Qualifiers::OCL_None; 6501 } 6502 6503 static const Type *getIntegerTypeForEnum(const EnumType *ET) { 6504 // Incomplete enum types are not treated as integer types. 6505 // FIXME: In C++, enum types are never integer types. 6506 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped()) 6507 return ET->getDecl()->getIntegerType().getTypePtr(); 6508 return nullptr; 6509 } 6510 6511 /// getIntegerTypeOrder - Returns the highest ranked integer type: 6512 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If 6513 /// LHS < RHS, return -1. 6514 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const { 6515 const Type *LHSC = getCanonicalType(LHS).getTypePtr(); 6516 const Type *RHSC = getCanonicalType(RHS).getTypePtr(); 6517 6518 // Unwrap enums to their underlying type. 6519 if (const auto *ET = dyn_cast<EnumType>(LHSC)) 6520 LHSC = getIntegerTypeForEnum(ET); 6521 if (const auto *ET = dyn_cast<EnumType>(RHSC)) 6522 RHSC = getIntegerTypeForEnum(ET); 6523 6524 if (LHSC == RHSC) return 0; 6525 6526 bool LHSUnsigned = LHSC->isUnsignedIntegerType(); 6527 bool RHSUnsigned = RHSC->isUnsignedIntegerType(); 6528 6529 unsigned LHSRank = getIntegerRank(LHSC); 6530 unsigned RHSRank = getIntegerRank(RHSC); 6531 6532 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned. 6533 if (LHSRank == RHSRank) return 0; 6534 return LHSRank > RHSRank ? 1 : -1; 6535 } 6536 6537 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa. 6538 if (LHSUnsigned) { 6539 // If the unsigned [LHS] type is larger, return it. 6540 if (LHSRank >= RHSRank) 6541 return 1; 6542 6543 // If the signed type can represent all values of the unsigned type, it 6544 // wins. Because we are dealing with 2's complement and types that are 6545 // powers of two larger than each other, this is always safe. 6546 return -1; 6547 } 6548 6549 // If the unsigned [RHS] type is larger, return it. 6550 if (RHSRank >= LHSRank) 6551 return -1; 6552 6553 // If the signed type can represent all values of the unsigned type, it 6554 // wins. Because we are dealing with 2's complement and types that are 6555 // powers of two larger than each other, this is always safe. 6556 return 1; 6557 } 6558 6559 TypedefDecl *ASTContext::getCFConstantStringDecl() const { 6560 if (CFConstantStringTypeDecl) 6561 return CFConstantStringTypeDecl; 6562 6563 assert(!CFConstantStringTagDecl && 6564 "tag and typedef should be initialized together"); 6565 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag"); 6566 CFConstantStringTagDecl->startDefinition(); 6567 6568 struct { 6569 QualType Type; 6570 const char *Name; 6571 } Fields[5]; 6572 unsigned Count = 0; 6573 6574 /// Objective-C ABI 6575 /// 6576 /// typedef struct __NSConstantString_tag { 6577 /// const int *isa; 6578 /// int flags; 6579 /// const char *str; 6580 /// long length; 6581 /// } __NSConstantString; 6582 /// 6583 /// Swift ABI (4.1, 4.2) 6584 /// 6585 /// typedef struct __NSConstantString_tag { 6586 /// uintptr_t _cfisa; 6587 /// uintptr_t _swift_rc; 6588 /// _Atomic(uint64_t) _cfinfoa; 6589 /// const char *_ptr; 6590 /// uint32_t _length; 6591 /// } __NSConstantString; 6592 /// 6593 /// Swift ABI (5.0) 6594 /// 6595 /// typedef struct __NSConstantString_tag { 6596 /// uintptr_t _cfisa; 6597 /// uintptr_t _swift_rc; 6598 /// _Atomic(uint64_t) _cfinfoa; 6599 /// const char *_ptr; 6600 /// uintptr_t _length; 6601 /// } __NSConstantString; 6602 6603 const auto CFRuntime = getLangOpts().CFRuntime; 6604 if (static_cast<unsigned>(CFRuntime) < 6605 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) { 6606 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" }; 6607 Fields[Count++] = { IntTy, "flags" }; 6608 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" }; 6609 Fields[Count++] = { LongTy, "length" }; 6610 } else { 6611 Fields[Count++] = { getUIntPtrType(), "_cfisa" }; 6612 Fields[Count++] = { getUIntPtrType(), "_swift_rc" }; 6613 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" }; 6614 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" }; 6615 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 || 6616 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2) 6617 Fields[Count++] = { IntTy, "_ptr" }; 6618 else 6619 Fields[Count++] = { getUIntPtrType(), "_ptr" }; 6620 } 6621 6622 // Create fields 6623 for (unsigned i = 0; i < Count; ++i) { 6624 FieldDecl *Field = 6625 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(), 6626 SourceLocation(), &Idents.get(Fields[i].Name), 6627 Fields[i].Type, /*TInfo=*/nullptr, 6628 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); 6629 Field->setAccess(AS_public); 6630 CFConstantStringTagDecl->addDecl(Field); 6631 } 6632 6633 CFConstantStringTagDecl->completeDefinition(); 6634 // This type is designed to be compatible with NSConstantString, but cannot 6635 // use the same name, since NSConstantString is an interface. 6636 auto tagType = getTagDeclType(CFConstantStringTagDecl); 6637 CFConstantStringTypeDecl = 6638 buildImplicitTypedef(tagType, "__NSConstantString"); 6639 6640 return CFConstantStringTypeDecl; 6641 } 6642 6643 RecordDecl *ASTContext::getCFConstantStringTagDecl() const { 6644 if (!CFConstantStringTagDecl) 6645 getCFConstantStringDecl(); // Build the tag and the typedef. 6646 return CFConstantStringTagDecl; 6647 } 6648 6649 // getCFConstantStringType - Return the type used for constant CFStrings. 6650 QualType ASTContext::getCFConstantStringType() const { 6651 return getTypedefType(getCFConstantStringDecl()); 6652 } 6653 6654 QualType ASTContext::getObjCSuperType() const { 6655 if (ObjCSuperType.isNull()) { 6656 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super"); 6657 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl); 6658 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl); 6659 } 6660 return ObjCSuperType; 6661 } 6662 6663 void ASTContext::setCFConstantStringType(QualType T) { 6664 const auto *TD = T->castAs<TypedefType>(); 6665 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl()); 6666 const auto *TagType = 6667 CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>(); 6668 CFConstantStringTagDecl = TagType->getDecl(); 6669 } 6670 6671 QualType ASTContext::getBlockDescriptorType() const { 6672 if (BlockDescriptorType) 6673 return getTagDeclType(BlockDescriptorType); 6674 6675 RecordDecl *RD; 6676 // FIXME: Needs the FlagAppleBlock bit. 6677 RD = buildImplicitRecord("__block_descriptor"); 6678 RD->startDefinition(); 6679 6680 QualType FieldTypes[] = { 6681 UnsignedLongTy, 6682 UnsignedLongTy, 6683 }; 6684 6685 static const char *const FieldNames[] = { 6686 "reserved", 6687 "Size" 6688 }; 6689 6690 for (size_t i = 0; i < 2; ++i) { 6691 FieldDecl *Field = FieldDecl::Create( 6692 *this, RD, SourceLocation(), SourceLocation(), 6693 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, 6694 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); 6695 Field->setAccess(AS_public); 6696 RD->addDecl(Field); 6697 } 6698 6699 RD->completeDefinition(); 6700 6701 BlockDescriptorType = RD; 6702 6703 return getTagDeclType(BlockDescriptorType); 6704 } 6705 6706 QualType ASTContext::getBlockDescriptorExtendedType() const { 6707 if (BlockDescriptorExtendedType) 6708 return getTagDeclType(BlockDescriptorExtendedType); 6709 6710 RecordDecl *RD; 6711 // FIXME: Needs the FlagAppleBlock bit. 6712 RD = buildImplicitRecord("__block_descriptor_withcopydispose"); 6713 RD->startDefinition(); 6714 6715 QualType FieldTypes[] = { 6716 UnsignedLongTy, 6717 UnsignedLongTy, 6718 getPointerType(VoidPtrTy), 6719 getPointerType(VoidPtrTy) 6720 }; 6721 6722 static const char *const FieldNames[] = { 6723 "reserved", 6724 "Size", 6725 "CopyFuncPtr", 6726 "DestroyFuncPtr" 6727 }; 6728 6729 for (size_t i = 0; i < 4; ++i) { 6730 FieldDecl *Field = FieldDecl::Create( 6731 *this, RD, SourceLocation(), SourceLocation(), 6732 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, 6733 /*BitWidth=*/nullptr, 6734 /*Mutable=*/false, ICIS_NoInit); 6735 Field->setAccess(AS_public); 6736 RD->addDecl(Field); 6737 } 6738 6739 RD->completeDefinition(); 6740 6741 BlockDescriptorExtendedType = RD; 6742 return getTagDeclType(BlockDescriptorExtendedType); 6743 } 6744 6745 OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const { 6746 const auto *BT = dyn_cast<BuiltinType>(T); 6747 6748 if (!BT) { 6749 if (isa<PipeType>(T)) 6750 return OCLTK_Pipe; 6751 6752 return OCLTK_Default; 6753 } 6754 6755 switch (BT->getKind()) { 6756 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6757 case BuiltinType::Id: \ 6758 return OCLTK_Image; 6759 #include "clang/Basic/OpenCLImageTypes.def" 6760 6761 case BuiltinType::OCLClkEvent: 6762 return OCLTK_ClkEvent; 6763 6764 case BuiltinType::OCLEvent: 6765 return OCLTK_Event; 6766 6767 case BuiltinType::OCLQueue: 6768 return OCLTK_Queue; 6769 6770 case BuiltinType::OCLReserveID: 6771 return OCLTK_ReserveID; 6772 6773 case BuiltinType::OCLSampler: 6774 return OCLTK_Sampler; 6775 6776 default: 6777 return OCLTK_Default; 6778 } 6779 } 6780 6781 LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const { 6782 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)); 6783 } 6784 6785 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty" 6786 /// requires copy/dispose. Note that this must match the logic 6787 /// in buildByrefHelpers. 6788 bool ASTContext::BlockRequiresCopying(QualType Ty, 6789 const VarDecl *D) { 6790 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) { 6791 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr(); 6792 if (!copyExpr && record->hasTrivialDestructor()) return false; 6793 6794 return true; 6795 } 6796 6797 // The block needs copy/destroy helpers if Ty is non-trivial to destructively 6798 // move or destroy. 6799 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType()) 6800 return true; 6801 6802 if (!Ty->isObjCRetainableType()) return false; 6803 6804 Qualifiers qs = Ty.getQualifiers(); 6805 6806 // If we have lifetime, that dominates. 6807 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) { 6808 switch (lifetime) { 6809 case Qualifiers::OCL_None: llvm_unreachable("impossible"); 6810 6811 // These are just bits as far as the runtime is concerned. 6812 case Qualifiers::OCL_ExplicitNone: 6813 case Qualifiers::OCL_Autoreleasing: 6814 return false; 6815 6816 // These cases should have been taken care of when checking the type's 6817 // non-triviality. 6818 case Qualifiers::OCL_Weak: 6819 case Qualifiers::OCL_Strong: 6820 llvm_unreachable("impossible"); 6821 } 6822 llvm_unreachable("fell out of lifetime switch!"); 6823 } 6824 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) || 6825 Ty->isObjCObjectPointerType()); 6826 } 6827 6828 bool ASTContext::getByrefLifetime(QualType Ty, 6829 Qualifiers::ObjCLifetime &LifeTime, 6830 bool &HasByrefExtendedLayout) const { 6831 if (!getLangOpts().ObjC || 6832 getLangOpts().getGC() != LangOptions::NonGC) 6833 return false; 6834 6835 HasByrefExtendedLayout = false; 6836 if (Ty->isRecordType()) { 6837 HasByrefExtendedLayout = true; 6838 LifeTime = Qualifiers::OCL_None; 6839 } else if ((LifeTime = Ty.getObjCLifetime())) { 6840 // Honor the ARC qualifiers. 6841 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) { 6842 // The MRR rule. 6843 LifeTime = Qualifiers::OCL_ExplicitNone; 6844 } else { 6845 LifeTime = Qualifiers::OCL_None; 6846 } 6847 return true; 6848 } 6849 6850 CanQualType ASTContext::getNSUIntegerType() const { 6851 assert(Target && "Expected target to be initialized"); 6852 const llvm::Triple &T = Target->getTriple(); 6853 // Windows is LLP64 rather than LP64 6854 if (T.isOSWindows() && T.isArch64Bit()) 6855 return UnsignedLongLongTy; 6856 return UnsignedLongTy; 6857 } 6858 6859 CanQualType ASTContext::getNSIntegerType() const { 6860 assert(Target && "Expected target to be initialized"); 6861 const llvm::Triple &T = Target->getTriple(); 6862 // Windows is LLP64 rather than LP64 6863 if (T.isOSWindows() && T.isArch64Bit()) 6864 return LongLongTy; 6865 return LongTy; 6866 } 6867 6868 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() { 6869 if (!ObjCInstanceTypeDecl) 6870 ObjCInstanceTypeDecl = 6871 buildImplicitTypedef(getObjCIdType(), "instancetype"); 6872 return ObjCInstanceTypeDecl; 6873 } 6874 6875 // This returns true if a type has been typedefed to BOOL: 6876 // typedef <type> BOOL; 6877 static bool isTypeTypedefedAsBOOL(QualType T) { 6878 if (const auto *TT = dyn_cast<TypedefType>(T)) 6879 if (IdentifierInfo *II = TT->getDecl()->getIdentifier()) 6880 return II->isStr("BOOL"); 6881 6882 return false; 6883 } 6884 6885 /// getObjCEncodingTypeSize returns size of type for objective-c encoding 6886 /// purpose. 6887 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const { 6888 if (!type->isIncompleteArrayType() && type->isIncompleteType()) 6889 return CharUnits::Zero(); 6890 6891 CharUnits sz = getTypeSizeInChars(type); 6892 6893 // Make all integer and enum types at least as large as an int 6894 if (sz.isPositive() && type->isIntegralOrEnumerationType()) 6895 sz = std::max(sz, getTypeSizeInChars(IntTy)); 6896 // Treat arrays as pointers, since that's how they're passed in. 6897 else if (type->isArrayType()) 6898 sz = getTypeSizeInChars(VoidPtrTy); 6899 return sz; 6900 } 6901 6902 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const { 6903 return getTargetInfo().getCXXABI().isMicrosoft() && 6904 VD->isStaticDataMember() && 6905 VD->getType()->isIntegralOrEnumerationType() && 6906 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit(); 6907 } 6908 6909 ASTContext::InlineVariableDefinitionKind 6910 ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const { 6911 if (!VD->isInline()) 6912 return InlineVariableDefinitionKind::None; 6913 6914 // In almost all cases, it's a weak definition. 6915 auto *First = VD->getFirstDecl(); 6916 if (First->isInlineSpecified() || !First->isStaticDataMember()) 6917 return InlineVariableDefinitionKind::Weak; 6918 6919 // If there's a file-context declaration in this translation unit, it's a 6920 // non-discardable definition. 6921 for (auto *D : VD->redecls()) 6922 if (D->getLexicalDeclContext()->isFileContext() && 6923 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr())) 6924 return InlineVariableDefinitionKind::Strong; 6925 6926 // If we've not seen one yet, we don't know. 6927 return InlineVariableDefinitionKind::WeakUnknown; 6928 } 6929 6930 static std::string charUnitsToString(const CharUnits &CU) { 6931 return llvm::itostr(CU.getQuantity()); 6932 } 6933 6934 /// getObjCEncodingForBlock - Return the encoded type for this block 6935 /// declaration. 6936 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const { 6937 std::string S; 6938 6939 const BlockDecl *Decl = Expr->getBlockDecl(); 6940 QualType BlockTy = 6941 Expr->getType()->castAs<BlockPointerType>()->getPointeeType(); 6942 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType(); 6943 // Encode result type. 6944 if (getLangOpts().EncodeExtendedBlockSig) 6945 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, BlockReturnTy, S, 6946 true /*Extended*/); 6947 else 6948 getObjCEncodingForType(BlockReturnTy, S); 6949 // Compute size of all parameters. 6950 // Start with computing size of a pointer in number of bytes. 6951 // FIXME: There might(should) be a better way of doing this computation! 6952 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 6953 CharUnits ParmOffset = PtrSize; 6954 for (auto PI : Decl->parameters()) { 6955 QualType PType = PI->getType(); 6956 CharUnits sz = getObjCEncodingTypeSize(PType); 6957 if (sz.isZero()) 6958 continue; 6959 assert(sz.isPositive() && "BlockExpr - Incomplete param type"); 6960 ParmOffset += sz; 6961 } 6962 // Size of the argument frame 6963 S += charUnitsToString(ParmOffset); 6964 // Block pointer and offset. 6965 S += "@?0"; 6966 6967 // Argument types. 6968 ParmOffset = PtrSize; 6969 for (auto PVDecl : Decl->parameters()) { 6970 QualType PType = PVDecl->getOriginalType(); 6971 if (const auto *AT = 6972 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 6973 // Use array's original type only if it has known number of 6974 // elements. 6975 if (!isa<ConstantArrayType>(AT)) 6976 PType = PVDecl->getType(); 6977 } else if (PType->isFunctionType()) 6978 PType = PVDecl->getType(); 6979 if (getLangOpts().EncodeExtendedBlockSig) 6980 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType, 6981 S, true /*Extended*/); 6982 else 6983 getObjCEncodingForType(PType, S); 6984 S += charUnitsToString(ParmOffset); 6985 ParmOffset += getObjCEncodingTypeSize(PType); 6986 } 6987 6988 return S; 6989 } 6990 6991 std::string 6992 ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const { 6993 std::string S; 6994 // Encode result type. 6995 getObjCEncodingForType(Decl->getReturnType(), S); 6996 CharUnits ParmOffset; 6997 // Compute size of all parameters. 6998 for (auto PI : Decl->parameters()) { 6999 QualType PType = PI->getType(); 7000 CharUnits sz = getObjCEncodingTypeSize(PType); 7001 if (sz.isZero()) 7002 continue; 7003 7004 assert(sz.isPositive() && 7005 "getObjCEncodingForFunctionDecl - Incomplete param type"); 7006 ParmOffset += sz; 7007 } 7008 S += charUnitsToString(ParmOffset); 7009 ParmOffset = CharUnits::Zero(); 7010 7011 // Argument types. 7012 for (auto PVDecl : Decl->parameters()) { 7013 QualType PType = PVDecl->getOriginalType(); 7014 if (const auto *AT = 7015 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 7016 // Use array's original type only if it has known number of 7017 // elements. 7018 if (!isa<ConstantArrayType>(AT)) 7019 PType = PVDecl->getType(); 7020 } else if (PType->isFunctionType()) 7021 PType = PVDecl->getType(); 7022 getObjCEncodingForType(PType, S); 7023 S += charUnitsToString(ParmOffset); 7024 ParmOffset += getObjCEncodingTypeSize(PType); 7025 } 7026 7027 return S; 7028 } 7029 7030 /// getObjCEncodingForMethodParameter - Return the encoded type for a single 7031 /// method parameter or return type. If Extended, include class names and 7032 /// block object types. 7033 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, 7034 QualType T, std::string& S, 7035 bool Extended) const { 7036 // Encode type qualifer, 'in', 'inout', etc. for the parameter. 7037 getObjCEncodingForTypeQualifier(QT, S); 7038 // Encode parameter type. 7039 ObjCEncOptions Options = ObjCEncOptions() 7040 .setExpandPointedToStructures() 7041 .setExpandStructures() 7042 .setIsOutermostType(); 7043 if (Extended) 7044 Options.setEncodeBlockParameters().setEncodeClassNames(); 7045 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr); 7046 } 7047 7048 /// getObjCEncodingForMethodDecl - Return the encoded type for this method 7049 /// declaration. 7050 std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, 7051 bool Extended) const { 7052 // FIXME: This is not very efficient. 7053 // Encode return type. 7054 std::string S; 7055 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(), 7056 Decl->getReturnType(), S, Extended); 7057 // Compute size of all parameters. 7058 // Start with computing size of a pointer in number of bytes. 7059 // FIXME: There might(should) be a better way of doing this computation! 7060 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 7061 // The first two arguments (self and _cmd) are pointers; account for 7062 // their size. 7063 CharUnits ParmOffset = 2 * PtrSize; 7064 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 7065 E = Decl->sel_param_end(); PI != E; ++PI) { 7066 QualType PType = (*PI)->getType(); 7067 CharUnits sz = getObjCEncodingTypeSize(PType); 7068 if (sz.isZero()) 7069 continue; 7070 7071 assert(sz.isPositive() && 7072 "getObjCEncodingForMethodDecl - Incomplete param type"); 7073 ParmOffset += sz; 7074 } 7075 S += charUnitsToString(ParmOffset); 7076 S += "@0:"; 7077 S += charUnitsToString(PtrSize); 7078 7079 // Argument types. 7080 ParmOffset = 2 * PtrSize; 7081 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 7082 E = Decl->sel_param_end(); PI != E; ++PI) { 7083 const ParmVarDecl *PVDecl = *PI; 7084 QualType PType = PVDecl->getOriginalType(); 7085 if (const auto *AT = 7086 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 7087 // Use array's original type only if it has known number of 7088 // elements. 7089 if (!isa<ConstantArrayType>(AT)) 7090 PType = PVDecl->getType(); 7091 } else if (PType->isFunctionType()) 7092 PType = PVDecl->getType(); 7093 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(), 7094 PType, S, Extended); 7095 S += charUnitsToString(ParmOffset); 7096 ParmOffset += getObjCEncodingTypeSize(PType); 7097 } 7098 7099 return S; 7100 } 7101 7102 ObjCPropertyImplDecl * 7103 ASTContext::getObjCPropertyImplDeclForPropertyDecl( 7104 const ObjCPropertyDecl *PD, 7105 const Decl *Container) const { 7106 if (!Container) 7107 return nullptr; 7108 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) { 7109 for (auto *PID : CID->property_impls()) 7110 if (PID->getPropertyDecl() == PD) 7111 return PID; 7112 } else { 7113 const auto *OID = cast<ObjCImplementationDecl>(Container); 7114 for (auto *PID : OID->property_impls()) 7115 if (PID->getPropertyDecl() == PD) 7116 return PID; 7117 } 7118 return nullptr; 7119 } 7120 7121 /// getObjCEncodingForPropertyDecl - Return the encoded type for this 7122 /// property declaration. If non-NULL, Container must be either an 7123 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be 7124 /// NULL when getting encodings for protocol properties. 7125 /// Property attributes are stored as a comma-delimited C string. The simple 7126 /// attributes readonly and bycopy are encoded as single characters. The 7127 /// parametrized attributes, getter=name, setter=name, and ivar=name, are 7128 /// encoded as single characters, followed by an identifier. Property types 7129 /// are also encoded as a parametrized attribute. The characters used to encode 7130 /// these attributes are defined by the following enumeration: 7131 /// @code 7132 /// enum PropertyAttributes { 7133 /// kPropertyReadOnly = 'R', // property is read-only. 7134 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned 7135 /// kPropertyByref = '&', // property is a reference to the value last assigned 7136 /// kPropertyDynamic = 'D', // property is dynamic 7137 /// kPropertyGetter = 'G', // followed by getter selector name 7138 /// kPropertySetter = 'S', // followed by setter selector name 7139 /// kPropertyInstanceVariable = 'V' // followed by instance variable name 7140 /// kPropertyType = 'T' // followed by old-style type encoding. 7141 /// kPropertyWeak = 'W' // 'weak' property 7142 /// kPropertyStrong = 'P' // property GC'able 7143 /// kPropertyNonAtomic = 'N' // property non-atomic 7144 /// }; 7145 /// @endcode 7146 std::string 7147 ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, 7148 const Decl *Container) const { 7149 // Collect information from the property implementation decl(s). 7150 bool Dynamic = false; 7151 ObjCPropertyImplDecl *SynthesizePID = nullptr; 7152 7153 if (ObjCPropertyImplDecl *PropertyImpDecl = 7154 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) { 7155 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) 7156 Dynamic = true; 7157 else 7158 SynthesizePID = PropertyImpDecl; 7159 } 7160 7161 // FIXME: This is not very efficient. 7162 std::string S = "T"; 7163 7164 // Encode result type. 7165 // GCC has some special rules regarding encoding of properties which 7166 // closely resembles encoding of ivars. 7167 getObjCEncodingForPropertyType(PD->getType(), S); 7168 7169 if (PD->isReadOnly()) { 7170 S += ",R"; 7171 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy) 7172 S += ",C"; 7173 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain) 7174 S += ",&"; 7175 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak) 7176 S += ",W"; 7177 } else { 7178 switch (PD->getSetterKind()) { 7179 case ObjCPropertyDecl::Assign: break; 7180 case ObjCPropertyDecl::Copy: S += ",C"; break; 7181 case ObjCPropertyDecl::Retain: S += ",&"; break; 7182 case ObjCPropertyDecl::Weak: S += ",W"; break; 7183 } 7184 } 7185 7186 // It really isn't clear at all what this means, since properties 7187 // are "dynamic by default". 7188 if (Dynamic) 7189 S += ",D"; 7190 7191 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_nonatomic) 7192 S += ",N"; 7193 7194 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) { 7195 S += ",G"; 7196 S += PD->getGetterName().getAsString(); 7197 } 7198 7199 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) { 7200 S += ",S"; 7201 S += PD->getSetterName().getAsString(); 7202 } 7203 7204 if (SynthesizePID) { 7205 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl(); 7206 S += ",V"; 7207 S += OID->getNameAsString(); 7208 } 7209 7210 // FIXME: OBJCGC: weak & strong 7211 return S; 7212 } 7213 7214 /// getLegacyIntegralTypeEncoding - 7215 /// Another legacy compatibility encoding: 32-bit longs are encoded as 7216 /// 'l' or 'L' , but not always. For typedefs, we need to use 7217 /// 'i' or 'I' instead if encoding a struct field, or a pointer! 7218 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const { 7219 if (isa<TypedefType>(PointeeTy.getTypePtr())) { 7220 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) { 7221 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32) 7222 PointeeTy = UnsignedIntTy; 7223 else 7224 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32) 7225 PointeeTy = IntTy; 7226 } 7227 } 7228 } 7229 7230 void ASTContext::getObjCEncodingForType(QualType T, std::string& S, 7231 const FieldDecl *Field, 7232 QualType *NotEncodedT) const { 7233 // We follow the behavior of gcc, expanding structures which are 7234 // directly pointed to, and expanding embedded structures. Note that 7235 // these rules are sufficient to prevent recursive encoding of the 7236 // same type. 7237 getObjCEncodingForTypeImpl(T, S, 7238 ObjCEncOptions() 7239 .setExpandPointedToStructures() 7240 .setExpandStructures() 7241 .setIsOutermostType(), 7242 Field, NotEncodedT); 7243 } 7244 7245 void ASTContext::getObjCEncodingForPropertyType(QualType T, 7246 std::string& S) const { 7247 // Encode result type. 7248 // GCC has some special rules regarding encoding of properties which 7249 // closely resembles encoding of ivars. 7250 getObjCEncodingForTypeImpl(T, S, 7251 ObjCEncOptions() 7252 .setExpandPointedToStructures() 7253 .setExpandStructures() 7254 .setIsOutermostType() 7255 .setEncodingProperty(), 7256 /*Field=*/nullptr); 7257 } 7258 7259 static char getObjCEncodingForPrimitiveType(const ASTContext *C, 7260 const BuiltinType *BT) { 7261 BuiltinType::Kind kind = BT->getKind(); 7262 switch (kind) { 7263 case BuiltinType::Void: return 'v'; 7264 case BuiltinType::Bool: return 'B'; 7265 case BuiltinType::Char8: 7266 case BuiltinType::Char_U: 7267 case BuiltinType::UChar: return 'C'; 7268 case BuiltinType::Char16: 7269 case BuiltinType::UShort: return 'S'; 7270 case BuiltinType::Char32: 7271 case BuiltinType::UInt: return 'I'; 7272 case BuiltinType::ULong: 7273 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q'; 7274 case BuiltinType::UInt128: return 'T'; 7275 case BuiltinType::ULongLong: return 'Q'; 7276 case BuiltinType::Char_S: 7277 case BuiltinType::SChar: return 'c'; 7278 case BuiltinType::Short: return 's'; 7279 case BuiltinType::WChar_S: 7280 case BuiltinType::WChar_U: 7281 case BuiltinType::Int: return 'i'; 7282 case BuiltinType::Long: 7283 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q'; 7284 case BuiltinType::LongLong: return 'q'; 7285 case BuiltinType::Int128: return 't'; 7286 case BuiltinType::Float: return 'f'; 7287 case BuiltinType::Double: return 'd'; 7288 case BuiltinType::LongDouble: return 'D'; 7289 case BuiltinType::NullPtr: return '*'; // like char* 7290 7291 case BuiltinType::BFloat16: 7292 case BuiltinType::Float16: 7293 case BuiltinType::Float128: 7294 case BuiltinType::Half: 7295 case BuiltinType::ShortAccum: 7296 case BuiltinType::Accum: 7297 case BuiltinType::LongAccum: 7298 case BuiltinType::UShortAccum: 7299 case BuiltinType::UAccum: 7300 case BuiltinType::ULongAccum: 7301 case BuiltinType::ShortFract: 7302 case BuiltinType::Fract: 7303 case BuiltinType::LongFract: 7304 case BuiltinType::UShortFract: 7305 case BuiltinType::UFract: 7306 case BuiltinType::ULongFract: 7307 case BuiltinType::SatShortAccum: 7308 case BuiltinType::SatAccum: 7309 case BuiltinType::SatLongAccum: 7310 case BuiltinType::SatUShortAccum: 7311 case BuiltinType::SatUAccum: 7312 case BuiltinType::SatULongAccum: 7313 case BuiltinType::SatShortFract: 7314 case BuiltinType::SatFract: 7315 case BuiltinType::SatLongFract: 7316 case BuiltinType::SatUShortFract: 7317 case BuiltinType::SatUFract: 7318 case BuiltinType::SatULongFract: 7319 // FIXME: potentially need @encodes for these! 7320 return ' '; 7321 7322 #define SVE_TYPE(Name, Id, SingletonId) \ 7323 case BuiltinType::Id: 7324 #include "clang/Basic/AArch64SVEACLETypes.def" 7325 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 7326 #include "clang/Basic/RISCVVTypes.def" 7327 { 7328 DiagnosticsEngine &Diags = C->getDiagnostics(); 7329 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 7330 "cannot yet @encode type %0"); 7331 Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy()); 7332 return ' '; 7333 } 7334 7335 case BuiltinType::ObjCId: 7336 case BuiltinType::ObjCClass: 7337 case BuiltinType::ObjCSel: 7338 llvm_unreachable("@encoding ObjC primitive type"); 7339 7340 // OpenCL and placeholder types don't need @encodings. 7341 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 7342 case BuiltinType::Id: 7343 #include "clang/Basic/OpenCLImageTypes.def" 7344 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 7345 case BuiltinType::Id: 7346 #include "clang/Basic/OpenCLExtensionTypes.def" 7347 case BuiltinType::OCLEvent: 7348 case BuiltinType::OCLClkEvent: 7349 case BuiltinType::OCLQueue: 7350 case BuiltinType::OCLReserveID: 7351 case BuiltinType::OCLSampler: 7352 case BuiltinType::Dependent: 7353 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 7354 case BuiltinType::Id: 7355 #include "clang/Basic/PPCTypes.def" 7356 #define BUILTIN_TYPE(KIND, ID) 7357 #define PLACEHOLDER_TYPE(KIND, ID) \ 7358 case BuiltinType::KIND: 7359 #include "clang/AST/BuiltinTypes.def" 7360 llvm_unreachable("invalid builtin type for @encode"); 7361 } 7362 llvm_unreachable("invalid BuiltinType::Kind value"); 7363 } 7364 7365 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) { 7366 EnumDecl *Enum = ET->getDecl(); 7367 7368 // The encoding of an non-fixed enum type is always 'i', regardless of size. 7369 if (!Enum->isFixed()) 7370 return 'i'; 7371 7372 // The encoding of a fixed enum type matches its fixed underlying type. 7373 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>(); 7374 return getObjCEncodingForPrimitiveType(C, BT); 7375 } 7376 7377 static void EncodeBitField(const ASTContext *Ctx, std::string& S, 7378 QualType T, const FieldDecl *FD) { 7379 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl"); 7380 S += 'b'; 7381 // The NeXT runtime encodes bit fields as b followed by the number of bits. 7382 // The GNU runtime requires more information; bitfields are encoded as b, 7383 // then the offset (in bits) of the first element, then the type of the 7384 // bitfield, then the size in bits. For example, in this structure: 7385 // 7386 // struct 7387 // { 7388 // int integer; 7389 // int flags:2; 7390 // }; 7391 // On a 32-bit system, the encoding for flags would be b2 for the NeXT 7392 // runtime, but b32i2 for the GNU runtime. The reason for this extra 7393 // information is not especially sensible, but we're stuck with it for 7394 // compatibility with GCC, although providing it breaks anything that 7395 // actually uses runtime introspection and wants to work on both runtimes... 7396 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) { 7397 uint64_t Offset; 7398 7399 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) { 7400 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr, 7401 IVD); 7402 } else { 7403 const RecordDecl *RD = FD->getParent(); 7404 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD); 7405 Offset = RL.getFieldOffset(FD->getFieldIndex()); 7406 } 7407 7408 S += llvm::utostr(Offset); 7409 7410 if (const auto *ET = T->getAs<EnumType>()) 7411 S += ObjCEncodingForEnumType(Ctx, ET); 7412 else { 7413 const auto *BT = T->castAs<BuiltinType>(); 7414 S += getObjCEncodingForPrimitiveType(Ctx, BT); 7415 } 7416 } 7417 S += llvm::utostr(FD->getBitWidthValue(*Ctx)); 7418 } 7419 7420 // Helper function for determining whether the encoded type string would include 7421 // a template specialization type. 7422 static bool hasTemplateSpecializationInEncodedString(const Type *T, 7423 bool VisitBasesAndFields) { 7424 T = T->getBaseElementTypeUnsafe(); 7425 7426 if (auto *PT = T->getAs<PointerType>()) 7427 return hasTemplateSpecializationInEncodedString( 7428 PT->getPointeeType().getTypePtr(), false); 7429 7430 auto *CXXRD = T->getAsCXXRecordDecl(); 7431 7432 if (!CXXRD) 7433 return false; 7434 7435 if (isa<ClassTemplateSpecializationDecl>(CXXRD)) 7436 return true; 7437 7438 if (!CXXRD->hasDefinition() || !VisitBasesAndFields) 7439 return false; 7440 7441 for (auto B : CXXRD->bases()) 7442 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(), 7443 true)) 7444 return true; 7445 7446 for (auto *FD : CXXRD->fields()) 7447 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(), 7448 true)) 7449 return true; 7450 7451 return false; 7452 } 7453 7454 // FIXME: Use SmallString for accumulating string. 7455 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S, 7456 const ObjCEncOptions Options, 7457 const FieldDecl *FD, 7458 QualType *NotEncodedT) const { 7459 CanQualType CT = getCanonicalType(T); 7460 switch (CT->getTypeClass()) { 7461 case Type::Builtin: 7462 case Type::Enum: 7463 if (FD && FD->isBitField()) 7464 return EncodeBitField(this, S, T, FD); 7465 if (const auto *BT = dyn_cast<BuiltinType>(CT)) 7466 S += getObjCEncodingForPrimitiveType(this, BT); 7467 else 7468 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT)); 7469 return; 7470 7471 case Type::Complex: 7472 S += 'j'; 7473 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S, 7474 ObjCEncOptions(), 7475 /*Field=*/nullptr); 7476 return; 7477 7478 case Type::Atomic: 7479 S += 'A'; 7480 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S, 7481 ObjCEncOptions(), 7482 /*Field=*/nullptr); 7483 return; 7484 7485 // encoding for pointer or reference types. 7486 case Type::Pointer: 7487 case Type::LValueReference: 7488 case Type::RValueReference: { 7489 QualType PointeeTy; 7490 if (isa<PointerType>(CT)) { 7491 const auto *PT = T->castAs<PointerType>(); 7492 if (PT->isObjCSelType()) { 7493 S += ':'; 7494 return; 7495 } 7496 PointeeTy = PT->getPointeeType(); 7497 } else { 7498 PointeeTy = T->castAs<ReferenceType>()->getPointeeType(); 7499 } 7500 7501 bool isReadOnly = false; 7502 // For historical/compatibility reasons, the read-only qualifier of the 7503 // pointee gets emitted _before_ the '^'. The read-only qualifier of 7504 // the pointer itself gets ignored, _unless_ we are looking at a typedef! 7505 // Also, do not emit the 'r' for anything but the outermost type! 7506 if (isa<TypedefType>(T.getTypePtr())) { 7507 if (Options.IsOutermostType() && T.isConstQualified()) { 7508 isReadOnly = true; 7509 S += 'r'; 7510 } 7511 } else if (Options.IsOutermostType()) { 7512 QualType P = PointeeTy; 7513 while (auto PT = P->getAs<PointerType>()) 7514 P = PT->getPointeeType(); 7515 if (P.isConstQualified()) { 7516 isReadOnly = true; 7517 S += 'r'; 7518 } 7519 } 7520 if (isReadOnly) { 7521 // Another legacy compatibility encoding. Some ObjC qualifier and type 7522 // combinations need to be rearranged. 7523 // Rewrite "in const" from "nr" to "rn" 7524 if (StringRef(S).endswith("nr")) 7525 S.replace(S.end()-2, S.end(), "rn"); 7526 } 7527 7528 if (PointeeTy->isCharType()) { 7529 // char pointer types should be encoded as '*' unless it is a 7530 // type that has been typedef'd to 'BOOL'. 7531 if (!isTypeTypedefedAsBOOL(PointeeTy)) { 7532 S += '*'; 7533 return; 7534 } 7535 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) { 7536 // GCC binary compat: Need to convert "struct objc_class *" to "#". 7537 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) { 7538 S += '#'; 7539 return; 7540 } 7541 // GCC binary compat: Need to convert "struct objc_object *" to "@". 7542 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) { 7543 S += '@'; 7544 return; 7545 } 7546 // If the encoded string for the class includes template names, just emit 7547 // "^v" for pointers to the class. 7548 if (getLangOpts().CPlusPlus && 7549 (!getLangOpts().EncodeCXXClassTemplateSpec && 7550 hasTemplateSpecializationInEncodedString( 7551 RTy, Options.ExpandPointedToStructures()))) { 7552 S += "^v"; 7553 return; 7554 } 7555 // fall through... 7556 } 7557 S += '^'; 7558 getLegacyIntegralTypeEncoding(PointeeTy); 7559 7560 ObjCEncOptions NewOptions; 7561 if (Options.ExpandPointedToStructures()) 7562 NewOptions.setExpandStructures(); 7563 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions, 7564 /*Field=*/nullptr, NotEncodedT); 7565 return; 7566 } 7567 7568 case Type::ConstantArray: 7569 case Type::IncompleteArray: 7570 case Type::VariableArray: { 7571 const auto *AT = cast<ArrayType>(CT); 7572 7573 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) { 7574 // Incomplete arrays are encoded as a pointer to the array element. 7575 S += '^'; 7576 7577 getObjCEncodingForTypeImpl( 7578 AT->getElementType(), S, 7579 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD); 7580 } else { 7581 S += '['; 7582 7583 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) 7584 S += llvm::utostr(CAT->getSize().getZExtValue()); 7585 else { 7586 //Variable length arrays are encoded as a regular array with 0 elements. 7587 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) && 7588 "Unknown array type!"); 7589 S += '0'; 7590 } 7591 7592 getObjCEncodingForTypeImpl( 7593 AT->getElementType(), S, 7594 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD, 7595 NotEncodedT); 7596 S += ']'; 7597 } 7598 return; 7599 } 7600 7601 case Type::FunctionNoProto: 7602 case Type::FunctionProto: 7603 S += '?'; 7604 return; 7605 7606 case Type::Record: { 7607 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl(); 7608 S += RDecl->isUnion() ? '(' : '{'; 7609 // Anonymous structures print as '?' 7610 if (const IdentifierInfo *II = RDecl->getIdentifier()) { 7611 S += II->getName(); 7612 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) { 7613 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 7614 llvm::raw_string_ostream OS(S); 7615 printTemplateArgumentList(OS, TemplateArgs.asArray(), 7616 getPrintingPolicy()); 7617 } 7618 } else { 7619 S += '?'; 7620 } 7621 if (Options.ExpandStructures()) { 7622 S += '='; 7623 if (!RDecl->isUnion()) { 7624 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT); 7625 } else { 7626 for (const auto *Field : RDecl->fields()) { 7627 if (FD) { 7628 S += '"'; 7629 S += Field->getNameAsString(); 7630 S += '"'; 7631 } 7632 7633 // Special case bit-fields. 7634 if (Field->isBitField()) { 7635 getObjCEncodingForTypeImpl(Field->getType(), S, 7636 ObjCEncOptions().setExpandStructures(), 7637 Field); 7638 } else { 7639 QualType qt = Field->getType(); 7640 getLegacyIntegralTypeEncoding(qt); 7641 getObjCEncodingForTypeImpl( 7642 qt, S, 7643 ObjCEncOptions().setExpandStructures().setIsStructField(), FD, 7644 NotEncodedT); 7645 } 7646 } 7647 } 7648 } 7649 S += RDecl->isUnion() ? ')' : '}'; 7650 return; 7651 } 7652 7653 case Type::BlockPointer: { 7654 const auto *BT = T->castAs<BlockPointerType>(); 7655 S += "@?"; // Unlike a pointer-to-function, which is "^?". 7656 if (Options.EncodeBlockParameters()) { 7657 const auto *FT = BT->getPointeeType()->castAs<FunctionType>(); 7658 7659 S += '<'; 7660 // Block return type 7661 getObjCEncodingForTypeImpl(FT->getReturnType(), S, 7662 Options.forComponentType(), FD, NotEncodedT); 7663 // Block self 7664 S += "@?"; 7665 // Block parameters 7666 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) { 7667 for (const auto &I : FPT->param_types()) 7668 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD, 7669 NotEncodedT); 7670 } 7671 S += '>'; 7672 } 7673 return; 7674 } 7675 7676 case Type::ObjCObject: { 7677 // hack to match legacy encoding of *id and *Class 7678 QualType Ty = getObjCObjectPointerType(CT); 7679 if (Ty->isObjCIdType()) { 7680 S += "{objc_object=}"; 7681 return; 7682 } 7683 else if (Ty->isObjCClassType()) { 7684 S += "{objc_class=}"; 7685 return; 7686 } 7687 // TODO: Double check to make sure this intentionally falls through. 7688 LLVM_FALLTHROUGH; 7689 } 7690 7691 case Type::ObjCInterface: { 7692 // Ignore protocol qualifiers when mangling at this level. 7693 // @encode(class_name) 7694 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface(); 7695 S += '{'; 7696 S += OI->getObjCRuntimeNameAsString(); 7697 if (Options.ExpandStructures()) { 7698 S += '='; 7699 SmallVector<const ObjCIvarDecl*, 32> Ivars; 7700 DeepCollectObjCIvars(OI, true, Ivars); 7701 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) { 7702 const FieldDecl *Field = Ivars[i]; 7703 if (Field->isBitField()) 7704 getObjCEncodingForTypeImpl(Field->getType(), S, 7705 ObjCEncOptions().setExpandStructures(), 7706 Field); 7707 else 7708 getObjCEncodingForTypeImpl(Field->getType(), S, 7709 ObjCEncOptions().setExpandStructures(), FD, 7710 NotEncodedT); 7711 } 7712 } 7713 S += '}'; 7714 return; 7715 } 7716 7717 case Type::ObjCObjectPointer: { 7718 const auto *OPT = T->castAs<ObjCObjectPointerType>(); 7719 if (OPT->isObjCIdType()) { 7720 S += '@'; 7721 return; 7722 } 7723 7724 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) { 7725 // FIXME: Consider if we need to output qualifiers for 'Class<p>'. 7726 // Since this is a binary compatibility issue, need to consult with 7727 // runtime folks. Fortunately, this is a *very* obscure construct. 7728 S += '#'; 7729 return; 7730 } 7731 7732 if (OPT->isObjCQualifiedIdType()) { 7733 getObjCEncodingForTypeImpl( 7734 getObjCIdType(), S, 7735 Options.keepingOnly(ObjCEncOptions() 7736 .setExpandPointedToStructures() 7737 .setExpandStructures()), 7738 FD); 7739 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) { 7740 // Note that we do extended encoding of protocol qualifer list 7741 // Only when doing ivar or property encoding. 7742 S += '"'; 7743 for (const auto *I : OPT->quals()) { 7744 S += '<'; 7745 S += I->getObjCRuntimeNameAsString(); 7746 S += '>'; 7747 } 7748 S += '"'; 7749 } 7750 return; 7751 } 7752 7753 S += '@'; 7754 if (OPT->getInterfaceDecl() && 7755 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) { 7756 S += '"'; 7757 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString(); 7758 for (const auto *I : OPT->quals()) { 7759 S += '<'; 7760 S += I->getObjCRuntimeNameAsString(); 7761 S += '>'; 7762 } 7763 S += '"'; 7764 } 7765 return; 7766 } 7767 7768 // gcc just blithely ignores member pointers. 7769 // FIXME: we should do better than that. 'M' is available. 7770 case Type::MemberPointer: 7771 // This matches gcc's encoding, even though technically it is insufficient. 7772 //FIXME. We should do a better job than gcc. 7773 case Type::Vector: 7774 case Type::ExtVector: 7775 // Until we have a coherent encoding of these three types, issue warning. 7776 if (NotEncodedT) 7777 *NotEncodedT = T; 7778 return; 7779 7780 case Type::ConstantMatrix: 7781 if (NotEncodedT) 7782 *NotEncodedT = T; 7783 return; 7784 7785 // We could see an undeduced auto type here during error recovery. 7786 // Just ignore it. 7787 case Type::Auto: 7788 case Type::DeducedTemplateSpecialization: 7789 return; 7790 7791 case Type::Pipe: 7792 case Type::ExtInt: 7793 #define ABSTRACT_TYPE(KIND, BASE) 7794 #define TYPE(KIND, BASE) 7795 #define DEPENDENT_TYPE(KIND, BASE) \ 7796 case Type::KIND: 7797 #define NON_CANONICAL_TYPE(KIND, BASE) \ 7798 case Type::KIND: 7799 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \ 7800 case Type::KIND: 7801 #include "clang/AST/TypeNodes.inc" 7802 llvm_unreachable("@encode for dependent type!"); 7803 } 7804 llvm_unreachable("bad type kind!"); 7805 } 7806 7807 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl, 7808 std::string &S, 7809 const FieldDecl *FD, 7810 bool includeVBases, 7811 QualType *NotEncodedT) const { 7812 assert(RDecl && "Expected non-null RecordDecl"); 7813 assert(!RDecl->isUnion() && "Should not be called for unions"); 7814 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl()) 7815 return; 7816 7817 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl); 7818 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets; 7819 const ASTRecordLayout &layout = getASTRecordLayout(RDecl); 7820 7821 if (CXXRec) { 7822 for (const auto &BI : CXXRec->bases()) { 7823 if (!BI.isVirtual()) { 7824 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); 7825 if (base->isEmpty()) 7826 continue; 7827 uint64_t offs = toBits(layout.getBaseClassOffset(base)); 7828 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 7829 std::make_pair(offs, base)); 7830 } 7831 } 7832 } 7833 7834 unsigned i = 0; 7835 for (FieldDecl *Field : RDecl->fields()) { 7836 if (!Field->isZeroLengthBitField(*this) && Field->isZeroSize(*this)) 7837 continue; 7838 uint64_t offs = layout.getFieldOffset(i); 7839 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 7840 std::make_pair(offs, Field)); 7841 ++i; 7842 } 7843 7844 if (CXXRec && includeVBases) { 7845 for (const auto &BI : CXXRec->vbases()) { 7846 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); 7847 if (base->isEmpty()) 7848 continue; 7849 uint64_t offs = toBits(layout.getVBaseClassOffset(base)); 7850 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) && 7851 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end()) 7852 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(), 7853 std::make_pair(offs, base)); 7854 } 7855 } 7856 7857 CharUnits size; 7858 if (CXXRec) { 7859 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize(); 7860 } else { 7861 size = layout.getSize(); 7862 } 7863 7864 #ifndef NDEBUG 7865 uint64_t CurOffs = 0; 7866 #endif 7867 std::multimap<uint64_t, NamedDecl *>::iterator 7868 CurLayObj = FieldOrBaseOffsets.begin(); 7869 7870 if (CXXRec && CXXRec->isDynamicClass() && 7871 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) { 7872 if (FD) { 7873 S += "\"_vptr$"; 7874 std::string recname = CXXRec->getNameAsString(); 7875 if (recname.empty()) recname = "?"; 7876 S += recname; 7877 S += '"'; 7878 } 7879 S += "^^?"; 7880 #ifndef NDEBUG 7881 CurOffs += getTypeSize(VoidPtrTy); 7882 #endif 7883 } 7884 7885 if (!RDecl->hasFlexibleArrayMember()) { 7886 // Mark the end of the structure. 7887 uint64_t offs = toBits(size); 7888 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 7889 std::make_pair(offs, nullptr)); 7890 } 7891 7892 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) { 7893 #ifndef NDEBUG 7894 assert(CurOffs <= CurLayObj->first); 7895 if (CurOffs < CurLayObj->first) { 7896 uint64_t padding = CurLayObj->first - CurOffs; 7897 // FIXME: There doesn't seem to be a way to indicate in the encoding that 7898 // packing/alignment of members is different that normal, in which case 7899 // the encoding will be out-of-sync with the real layout. 7900 // If the runtime switches to just consider the size of types without 7901 // taking into account alignment, we could make padding explicit in the 7902 // encoding (e.g. using arrays of chars). The encoding strings would be 7903 // longer then though. 7904 CurOffs += padding; 7905 } 7906 #endif 7907 7908 NamedDecl *dcl = CurLayObj->second; 7909 if (!dcl) 7910 break; // reached end of structure. 7911 7912 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) { 7913 // We expand the bases without their virtual bases since those are going 7914 // in the initial structure. Note that this differs from gcc which 7915 // expands virtual bases each time one is encountered in the hierarchy, 7916 // making the encoding type bigger than it really is. 7917 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false, 7918 NotEncodedT); 7919 assert(!base->isEmpty()); 7920 #ifndef NDEBUG 7921 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize()); 7922 #endif 7923 } else { 7924 const auto *field = cast<FieldDecl>(dcl); 7925 if (FD) { 7926 S += '"'; 7927 S += field->getNameAsString(); 7928 S += '"'; 7929 } 7930 7931 if (field->isBitField()) { 7932 EncodeBitField(this, S, field->getType(), field); 7933 #ifndef NDEBUG 7934 CurOffs += field->getBitWidthValue(*this); 7935 #endif 7936 } else { 7937 QualType qt = field->getType(); 7938 getLegacyIntegralTypeEncoding(qt); 7939 getObjCEncodingForTypeImpl( 7940 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(), 7941 FD, NotEncodedT); 7942 #ifndef NDEBUG 7943 CurOffs += getTypeSize(field->getType()); 7944 #endif 7945 } 7946 } 7947 } 7948 } 7949 7950 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, 7951 std::string& S) const { 7952 if (QT & Decl::OBJC_TQ_In) 7953 S += 'n'; 7954 if (QT & Decl::OBJC_TQ_Inout) 7955 S += 'N'; 7956 if (QT & Decl::OBJC_TQ_Out) 7957 S += 'o'; 7958 if (QT & Decl::OBJC_TQ_Bycopy) 7959 S += 'O'; 7960 if (QT & Decl::OBJC_TQ_Byref) 7961 S += 'R'; 7962 if (QT & Decl::OBJC_TQ_Oneway) 7963 S += 'V'; 7964 } 7965 7966 TypedefDecl *ASTContext::getObjCIdDecl() const { 7967 if (!ObjCIdDecl) { 7968 QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {}); 7969 T = getObjCObjectPointerType(T); 7970 ObjCIdDecl = buildImplicitTypedef(T, "id"); 7971 } 7972 return ObjCIdDecl; 7973 } 7974 7975 TypedefDecl *ASTContext::getObjCSelDecl() const { 7976 if (!ObjCSelDecl) { 7977 QualType T = getPointerType(ObjCBuiltinSelTy); 7978 ObjCSelDecl = buildImplicitTypedef(T, "SEL"); 7979 } 7980 return ObjCSelDecl; 7981 } 7982 7983 TypedefDecl *ASTContext::getObjCClassDecl() const { 7984 if (!ObjCClassDecl) { 7985 QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {}); 7986 T = getObjCObjectPointerType(T); 7987 ObjCClassDecl = buildImplicitTypedef(T, "Class"); 7988 } 7989 return ObjCClassDecl; 7990 } 7991 7992 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const { 7993 if (!ObjCProtocolClassDecl) { 7994 ObjCProtocolClassDecl 7995 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(), 7996 SourceLocation(), 7997 &Idents.get("Protocol"), 7998 /*typeParamList=*/nullptr, 7999 /*PrevDecl=*/nullptr, 8000 SourceLocation(), true); 8001 } 8002 8003 return ObjCProtocolClassDecl; 8004 } 8005 8006 //===----------------------------------------------------------------------===// 8007 // __builtin_va_list Construction Functions 8008 //===----------------------------------------------------------------------===// 8009 8010 static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context, 8011 StringRef Name) { 8012 // typedef char* __builtin[_ms]_va_list; 8013 QualType T = Context->getPointerType(Context->CharTy); 8014 return Context->buildImplicitTypedef(T, Name); 8015 } 8016 8017 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) { 8018 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list"); 8019 } 8020 8021 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) { 8022 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list"); 8023 } 8024 8025 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) { 8026 // typedef void* __builtin_va_list; 8027 QualType T = Context->getPointerType(Context->VoidTy); 8028 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 8029 } 8030 8031 static TypedefDecl * 8032 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) { 8033 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list"); 8034 // namespace std { struct __va_list { 8035 // Note that we create the namespace even in C. This is intentional so that 8036 // the type is consistent between C and C++, which is important in cases where 8037 // the types need to match between translation units (e.g. with 8038 // -fsanitize=cfi-icall). Ideally we wouldn't have created this namespace at 8039 // all, but it's now part of the ABI (e.g. in mangled names), so we can't 8040 // change it. 8041 auto *NS = NamespaceDecl::Create( 8042 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(), 8043 /*Inline*/ false, SourceLocation(), SourceLocation(), 8044 &Context->Idents.get("std"), 8045 /*PrevDecl*/ nullptr); 8046 NS->setImplicit(); 8047 VaListTagDecl->setDeclContext(NS); 8048 8049 VaListTagDecl->startDefinition(); 8050 8051 const size_t NumFields = 5; 8052 QualType FieldTypes[NumFields]; 8053 const char *FieldNames[NumFields]; 8054 8055 // void *__stack; 8056 FieldTypes[0] = Context->getPointerType(Context->VoidTy); 8057 FieldNames[0] = "__stack"; 8058 8059 // void *__gr_top; 8060 FieldTypes[1] = Context->getPointerType(Context->VoidTy); 8061 FieldNames[1] = "__gr_top"; 8062 8063 // void *__vr_top; 8064 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8065 FieldNames[2] = "__vr_top"; 8066 8067 // int __gr_offs; 8068 FieldTypes[3] = Context->IntTy; 8069 FieldNames[3] = "__gr_offs"; 8070 8071 // int __vr_offs; 8072 FieldTypes[4] = Context->IntTy; 8073 FieldNames[4] = "__vr_offs"; 8074 8075 // Create fields 8076 for (unsigned i = 0; i < NumFields; ++i) { 8077 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8078 VaListTagDecl, 8079 SourceLocation(), 8080 SourceLocation(), 8081 &Context->Idents.get(FieldNames[i]), 8082 FieldTypes[i], /*TInfo=*/nullptr, 8083 /*BitWidth=*/nullptr, 8084 /*Mutable=*/false, 8085 ICIS_NoInit); 8086 Field->setAccess(AS_public); 8087 VaListTagDecl->addDecl(Field); 8088 } 8089 VaListTagDecl->completeDefinition(); 8090 Context->VaListTagDecl = VaListTagDecl; 8091 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8092 8093 // } __builtin_va_list; 8094 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list"); 8095 } 8096 8097 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) { 8098 // typedef struct __va_list_tag { 8099 RecordDecl *VaListTagDecl; 8100 8101 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8102 VaListTagDecl->startDefinition(); 8103 8104 const size_t NumFields = 5; 8105 QualType FieldTypes[NumFields]; 8106 const char *FieldNames[NumFields]; 8107 8108 // unsigned char gpr; 8109 FieldTypes[0] = Context->UnsignedCharTy; 8110 FieldNames[0] = "gpr"; 8111 8112 // unsigned char fpr; 8113 FieldTypes[1] = Context->UnsignedCharTy; 8114 FieldNames[1] = "fpr"; 8115 8116 // unsigned short reserved; 8117 FieldTypes[2] = Context->UnsignedShortTy; 8118 FieldNames[2] = "reserved"; 8119 8120 // void* overflow_arg_area; 8121 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 8122 FieldNames[3] = "overflow_arg_area"; 8123 8124 // void* reg_save_area; 8125 FieldTypes[4] = Context->getPointerType(Context->VoidTy); 8126 FieldNames[4] = "reg_save_area"; 8127 8128 // Create fields 8129 for (unsigned i = 0; i < NumFields; ++i) { 8130 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl, 8131 SourceLocation(), 8132 SourceLocation(), 8133 &Context->Idents.get(FieldNames[i]), 8134 FieldTypes[i], /*TInfo=*/nullptr, 8135 /*BitWidth=*/nullptr, 8136 /*Mutable=*/false, 8137 ICIS_NoInit); 8138 Field->setAccess(AS_public); 8139 VaListTagDecl->addDecl(Field); 8140 } 8141 VaListTagDecl->completeDefinition(); 8142 Context->VaListTagDecl = VaListTagDecl; 8143 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8144 8145 // } __va_list_tag; 8146 TypedefDecl *VaListTagTypedefDecl = 8147 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); 8148 8149 QualType VaListTagTypedefType = 8150 Context->getTypedefType(VaListTagTypedefDecl); 8151 8152 // typedef __va_list_tag __builtin_va_list[1]; 8153 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8154 QualType VaListTagArrayType 8155 = Context->getConstantArrayType(VaListTagTypedefType, 8156 Size, nullptr, ArrayType::Normal, 0); 8157 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8158 } 8159 8160 static TypedefDecl * 8161 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) { 8162 // struct __va_list_tag { 8163 RecordDecl *VaListTagDecl; 8164 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8165 VaListTagDecl->startDefinition(); 8166 8167 const size_t NumFields = 4; 8168 QualType FieldTypes[NumFields]; 8169 const char *FieldNames[NumFields]; 8170 8171 // unsigned gp_offset; 8172 FieldTypes[0] = Context->UnsignedIntTy; 8173 FieldNames[0] = "gp_offset"; 8174 8175 // unsigned fp_offset; 8176 FieldTypes[1] = Context->UnsignedIntTy; 8177 FieldNames[1] = "fp_offset"; 8178 8179 // void* overflow_arg_area; 8180 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8181 FieldNames[2] = "overflow_arg_area"; 8182 8183 // void* reg_save_area; 8184 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 8185 FieldNames[3] = "reg_save_area"; 8186 8187 // Create fields 8188 for (unsigned i = 0; i < NumFields; ++i) { 8189 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8190 VaListTagDecl, 8191 SourceLocation(), 8192 SourceLocation(), 8193 &Context->Idents.get(FieldNames[i]), 8194 FieldTypes[i], /*TInfo=*/nullptr, 8195 /*BitWidth=*/nullptr, 8196 /*Mutable=*/false, 8197 ICIS_NoInit); 8198 Field->setAccess(AS_public); 8199 VaListTagDecl->addDecl(Field); 8200 } 8201 VaListTagDecl->completeDefinition(); 8202 Context->VaListTagDecl = VaListTagDecl; 8203 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8204 8205 // }; 8206 8207 // typedef struct __va_list_tag __builtin_va_list[1]; 8208 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8209 QualType VaListTagArrayType = Context->getConstantArrayType( 8210 VaListTagType, Size, nullptr, ArrayType::Normal, 0); 8211 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8212 } 8213 8214 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) { 8215 // typedef int __builtin_va_list[4]; 8216 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4); 8217 QualType IntArrayType = Context->getConstantArrayType( 8218 Context->IntTy, Size, nullptr, ArrayType::Normal, 0); 8219 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list"); 8220 } 8221 8222 static TypedefDecl * 8223 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) { 8224 // struct __va_list 8225 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list"); 8226 if (Context->getLangOpts().CPlusPlus) { 8227 // namespace std { struct __va_list { 8228 NamespaceDecl *NS; 8229 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context), 8230 Context->getTranslationUnitDecl(), 8231 /*Inline*/false, SourceLocation(), 8232 SourceLocation(), &Context->Idents.get("std"), 8233 /*PrevDecl*/ nullptr); 8234 NS->setImplicit(); 8235 VaListDecl->setDeclContext(NS); 8236 } 8237 8238 VaListDecl->startDefinition(); 8239 8240 // void * __ap; 8241 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8242 VaListDecl, 8243 SourceLocation(), 8244 SourceLocation(), 8245 &Context->Idents.get("__ap"), 8246 Context->getPointerType(Context->VoidTy), 8247 /*TInfo=*/nullptr, 8248 /*BitWidth=*/nullptr, 8249 /*Mutable=*/false, 8250 ICIS_NoInit); 8251 Field->setAccess(AS_public); 8252 VaListDecl->addDecl(Field); 8253 8254 // }; 8255 VaListDecl->completeDefinition(); 8256 Context->VaListTagDecl = VaListDecl; 8257 8258 // typedef struct __va_list __builtin_va_list; 8259 QualType T = Context->getRecordType(VaListDecl); 8260 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 8261 } 8262 8263 static TypedefDecl * 8264 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) { 8265 // struct __va_list_tag { 8266 RecordDecl *VaListTagDecl; 8267 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8268 VaListTagDecl->startDefinition(); 8269 8270 const size_t NumFields = 4; 8271 QualType FieldTypes[NumFields]; 8272 const char *FieldNames[NumFields]; 8273 8274 // long __gpr; 8275 FieldTypes[0] = Context->LongTy; 8276 FieldNames[0] = "__gpr"; 8277 8278 // long __fpr; 8279 FieldTypes[1] = Context->LongTy; 8280 FieldNames[1] = "__fpr"; 8281 8282 // void *__overflow_arg_area; 8283 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8284 FieldNames[2] = "__overflow_arg_area"; 8285 8286 // void *__reg_save_area; 8287 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 8288 FieldNames[3] = "__reg_save_area"; 8289 8290 // Create fields 8291 for (unsigned i = 0; i < NumFields; ++i) { 8292 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8293 VaListTagDecl, 8294 SourceLocation(), 8295 SourceLocation(), 8296 &Context->Idents.get(FieldNames[i]), 8297 FieldTypes[i], /*TInfo=*/nullptr, 8298 /*BitWidth=*/nullptr, 8299 /*Mutable=*/false, 8300 ICIS_NoInit); 8301 Field->setAccess(AS_public); 8302 VaListTagDecl->addDecl(Field); 8303 } 8304 VaListTagDecl->completeDefinition(); 8305 Context->VaListTagDecl = VaListTagDecl; 8306 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8307 8308 // }; 8309 8310 // typedef __va_list_tag __builtin_va_list[1]; 8311 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8312 QualType VaListTagArrayType = Context->getConstantArrayType( 8313 VaListTagType, Size, nullptr, ArrayType::Normal, 0); 8314 8315 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8316 } 8317 8318 static TypedefDecl *CreateHexagonBuiltinVaListDecl(const ASTContext *Context) { 8319 // typedef struct __va_list_tag { 8320 RecordDecl *VaListTagDecl; 8321 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8322 VaListTagDecl->startDefinition(); 8323 8324 const size_t NumFields = 3; 8325 QualType FieldTypes[NumFields]; 8326 const char *FieldNames[NumFields]; 8327 8328 // void *CurrentSavedRegisterArea; 8329 FieldTypes[0] = Context->getPointerType(Context->VoidTy); 8330 FieldNames[0] = "__current_saved_reg_area_pointer"; 8331 8332 // void *SavedRegAreaEnd; 8333 FieldTypes[1] = Context->getPointerType(Context->VoidTy); 8334 FieldNames[1] = "__saved_reg_area_end_pointer"; 8335 8336 // void *OverflowArea; 8337 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8338 FieldNames[2] = "__overflow_area_pointer"; 8339 8340 // Create fields 8341 for (unsigned i = 0; i < NumFields; ++i) { 8342 FieldDecl *Field = FieldDecl::Create( 8343 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(), 8344 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i], 8345 /*TInfo=*/0, 8346 /*BitWidth=*/0, 8347 /*Mutable=*/false, ICIS_NoInit); 8348 Field->setAccess(AS_public); 8349 VaListTagDecl->addDecl(Field); 8350 } 8351 VaListTagDecl->completeDefinition(); 8352 Context->VaListTagDecl = VaListTagDecl; 8353 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8354 8355 // } __va_list_tag; 8356 TypedefDecl *VaListTagTypedefDecl = 8357 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); 8358 8359 QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl); 8360 8361 // typedef __va_list_tag __builtin_va_list[1]; 8362 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8363 QualType VaListTagArrayType = Context->getConstantArrayType( 8364 VaListTagTypedefType, Size, nullptr, ArrayType::Normal, 0); 8365 8366 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8367 } 8368 8369 static TypedefDecl *CreateVaListDecl(const ASTContext *Context, 8370 TargetInfo::BuiltinVaListKind Kind) { 8371 switch (Kind) { 8372 case TargetInfo::CharPtrBuiltinVaList: 8373 return CreateCharPtrBuiltinVaListDecl(Context); 8374 case TargetInfo::VoidPtrBuiltinVaList: 8375 return CreateVoidPtrBuiltinVaListDecl(Context); 8376 case TargetInfo::AArch64ABIBuiltinVaList: 8377 return CreateAArch64ABIBuiltinVaListDecl(Context); 8378 case TargetInfo::PowerABIBuiltinVaList: 8379 return CreatePowerABIBuiltinVaListDecl(Context); 8380 case TargetInfo::X86_64ABIBuiltinVaList: 8381 return CreateX86_64ABIBuiltinVaListDecl(Context); 8382 case TargetInfo::PNaClABIBuiltinVaList: 8383 return CreatePNaClABIBuiltinVaListDecl(Context); 8384 case TargetInfo::AAPCSABIBuiltinVaList: 8385 return CreateAAPCSABIBuiltinVaListDecl(Context); 8386 case TargetInfo::SystemZBuiltinVaList: 8387 return CreateSystemZBuiltinVaListDecl(Context); 8388 case TargetInfo::HexagonBuiltinVaList: 8389 return CreateHexagonBuiltinVaListDecl(Context); 8390 } 8391 8392 llvm_unreachable("Unhandled __builtin_va_list type kind"); 8393 } 8394 8395 TypedefDecl *ASTContext::getBuiltinVaListDecl() const { 8396 if (!BuiltinVaListDecl) { 8397 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind()); 8398 assert(BuiltinVaListDecl->isImplicit()); 8399 } 8400 8401 return BuiltinVaListDecl; 8402 } 8403 8404 Decl *ASTContext::getVaListTagDecl() const { 8405 // Force the creation of VaListTagDecl by building the __builtin_va_list 8406 // declaration. 8407 if (!VaListTagDecl) 8408 (void)getBuiltinVaListDecl(); 8409 8410 return VaListTagDecl; 8411 } 8412 8413 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const { 8414 if (!BuiltinMSVaListDecl) 8415 BuiltinMSVaListDecl = CreateMSVaListDecl(this); 8416 8417 return BuiltinMSVaListDecl; 8418 } 8419 8420 bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const { 8421 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID()); 8422 } 8423 8424 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) { 8425 assert(ObjCConstantStringType.isNull() && 8426 "'NSConstantString' type already set!"); 8427 8428 ObjCConstantStringType = getObjCInterfaceType(Decl); 8429 } 8430 8431 /// Retrieve the template name that corresponds to a non-empty 8432 /// lookup. 8433 TemplateName 8434 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin, 8435 UnresolvedSetIterator End) const { 8436 unsigned size = End - Begin; 8437 assert(size > 1 && "set is not overloaded!"); 8438 8439 void *memory = Allocate(sizeof(OverloadedTemplateStorage) + 8440 size * sizeof(FunctionTemplateDecl*)); 8441 auto *OT = new (memory) OverloadedTemplateStorage(size); 8442 8443 NamedDecl **Storage = OT->getStorage(); 8444 for (UnresolvedSetIterator I = Begin; I != End; ++I) { 8445 NamedDecl *D = *I; 8446 assert(isa<FunctionTemplateDecl>(D) || 8447 isa<UnresolvedUsingValueDecl>(D) || 8448 (isa<UsingShadowDecl>(D) && 8449 isa<FunctionTemplateDecl>(D->getUnderlyingDecl()))); 8450 *Storage++ = D; 8451 } 8452 8453 return TemplateName(OT); 8454 } 8455 8456 /// Retrieve a template name representing an unqualified-id that has been 8457 /// assumed to name a template for ADL purposes. 8458 TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const { 8459 auto *OT = new (*this) AssumedTemplateStorage(Name); 8460 return TemplateName(OT); 8461 } 8462 8463 /// Retrieve the template name that represents a qualified 8464 /// template name such as \c std::vector. 8465 TemplateName 8466 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, 8467 bool TemplateKeyword, 8468 TemplateDecl *Template) const { 8469 assert(NNS && "Missing nested-name-specifier in qualified template name"); 8470 8471 // FIXME: Canonicalization? 8472 llvm::FoldingSetNodeID ID; 8473 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template); 8474 8475 void *InsertPos = nullptr; 8476 QualifiedTemplateName *QTN = 8477 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 8478 if (!QTN) { 8479 QTN = new (*this, alignof(QualifiedTemplateName)) 8480 QualifiedTemplateName(NNS, TemplateKeyword, Template); 8481 QualifiedTemplateNames.InsertNode(QTN, InsertPos); 8482 } 8483 8484 return TemplateName(QTN); 8485 } 8486 8487 /// Retrieve the template name that represents a dependent 8488 /// template name such as \c MetaFun::template apply. 8489 TemplateName 8490 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 8491 const IdentifierInfo *Name) const { 8492 assert((!NNS || NNS->isDependent()) && 8493 "Nested name specifier must be dependent"); 8494 8495 llvm::FoldingSetNodeID ID; 8496 DependentTemplateName::Profile(ID, NNS, Name); 8497 8498 void *InsertPos = nullptr; 8499 DependentTemplateName *QTN = 8500 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 8501 8502 if (QTN) 8503 return TemplateName(QTN); 8504 8505 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 8506 if (CanonNNS == NNS) { 8507 QTN = new (*this, alignof(DependentTemplateName)) 8508 DependentTemplateName(NNS, Name); 8509 } else { 8510 TemplateName Canon = getDependentTemplateName(CanonNNS, Name); 8511 QTN = new (*this, alignof(DependentTemplateName)) 8512 DependentTemplateName(NNS, Name, Canon); 8513 DependentTemplateName *CheckQTN = 8514 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 8515 assert(!CheckQTN && "Dependent type name canonicalization broken"); 8516 (void)CheckQTN; 8517 } 8518 8519 DependentTemplateNames.InsertNode(QTN, InsertPos); 8520 return TemplateName(QTN); 8521 } 8522 8523 /// Retrieve the template name that represents a dependent 8524 /// template name such as \c MetaFun::template operator+. 8525 TemplateName 8526 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 8527 OverloadedOperatorKind Operator) const { 8528 assert((!NNS || NNS->isDependent()) && 8529 "Nested name specifier must be dependent"); 8530 8531 llvm::FoldingSetNodeID ID; 8532 DependentTemplateName::Profile(ID, NNS, Operator); 8533 8534 void *InsertPos = nullptr; 8535 DependentTemplateName *QTN 8536 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 8537 8538 if (QTN) 8539 return TemplateName(QTN); 8540 8541 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 8542 if (CanonNNS == NNS) { 8543 QTN = new (*this, alignof(DependentTemplateName)) 8544 DependentTemplateName(NNS, Operator); 8545 } else { 8546 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator); 8547 QTN = new (*this, alignof(DependentTemplateName)) 8548 DependentTemplateName(NNS, Operator, Canon); 8549 8550 DependentTemplateName *CheckQTN 8551 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 8552 assert(!CheckQTN && "Dependent template name canonicalization broken"); 8553 (void)CheckQTN; 8554 } 8555 8556 DependentTemplateNames.InsertNode(QTN, InsertPos); 8557 return TemplateName(QTN); 8558 } 8559 8560 TemplateName 8561 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param, 8562 TemplateName replacement) const { 8563 llvm::FoldingSetNodeID ID; 8564 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement); 8565 8566 void *insertPos = nullptr; 8567 SubstTemplateTemplateParmStorage *subst 8568 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos); 8569 8570 if (!subst) { 8571 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement); 8572 SubstTemplateTemplateParms.InsertNode(subst, insertPos); 8573 } 8574 8575 return TemplateName(subst); 8576 } 8577 8578 TemplateName 8579 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param, 8580 const TemplateArgument &ArgPack) const { 8581 auto &Self = const_cast<ASTContext &>(*this); 8582 llvm::FoldingSetNodeID ID; 8583 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack); 8584 8585 void *InsertPos = nullptr; 8586 SubstTemplateTemplateParmPackStorage *Subst 8587 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos); 8588 8589 if (!Subst) { 8590 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param, 8591 ArgPack.pack_size(), 8592 ArgPack.pack_begin()); 8593 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos); 8594 } 8595 8596 return TemplateName(Subst); 8597 } 8598 8599 /// getFromTargetType - Given one of the integer types provided by 8600 /// TargetInfo, produce the corresponding type. The unsigned @p Type 8601 /// is actually a value of type @c TargetInfo::IntType. 8602 CanQualType ASTContext::getFromTargetType(unsigned Type) const { 8603 switch (Type) { 8604 case TargetInfo::NoInt: return {}; 8605 case TargetInfo::SignedChar: return SignedCharTy; 8606 case TargetInfo::UnsignedChar: return UnsignedCharTy; 8607 case TargetInfo::SignedShort: return ShortTy; 8608 case TargetInfo::UnsignedShort: return UnsignedShortTy; 8609 case TargetInfo::SignedInt: return IntTy; 8610 case TargetInfo::UnsignedInt: return UnsignedIntTy; 8611 case TargetInfo::SignedLong: return LongTy; 8612 case TargetInfo::UnsignedLong: return UnsignedLongTy; 8613 case TargetInfo::SignedLongLong: return LongLongTy; 8614 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy; 8615 } 8616 8617 llvm_unreachable("Unhandled TargetInfo::IntType value"); 8618 } 8619 8620 //===----------------------------------------------------------------------===// 8621 // Type Predicates. 8622 //===----------------------------------------------------------------------===// 8623 8624 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's 8625 /// garbage collection attribute. 8626 /// 8627 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const { 8628 if (getLangOpts().getGC() == LangOptions::NonGC) 8629 return Qualifiers::GCNone; 8630 8631 assert(getLangOpts().ObjC); 8632 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr(); 8633 8634 // Default behaviour under objective-C's gc is for ObjC pointers 8635 // (or pointers to them) be treated as though they were declared 8636 // as __strong. 8637 if (GCAttrs == Qualifiers::GCNone) { 8638 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) 8639 return Qualifiers::Strong; 8640 else if (Ty->isPointerType()) 8641 return getObjCGCAttrKind(Ty->castAs<PointerType>()->getPointeeType()); 8642 } else { 8643 // It's not valid to set GC attributes on anything that isn't a 8644 // pointer. 8645 #ifndef NDEBUG 8646 QualType CT = Ty->getCanonicalTypeInternal(); 8647 while (const auto *AT = dyn_cast<ArrayType>(CT)) 8648 CT = AT->getElementType(); 8649 assert(CT->isAnyPointerType() || CT->isBlockPointerType()); 8650 #endif 8651 } 8652 return GCAttrs; 8653 } 8654 8655 //===----------------------------------------------------------------------===// 8656 // Type Compatibility Testing 8657 //===----------------------------------------------------------------------===// 8658 8659 /// areCompatVectorTypes - Return true if the two specified vector types are 8660 /// compatible. 8661 static bool areCompatVectorTypes(const VectorType *LHS, 8662 const VectorType *RHS) { 8663 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 8664 return LHS->getElementType() == RHS->getElementType() && 8665 LHS->getNumElements() == RHS->getNumElements(); 8666 } 8667 8668 /// areCompatMatrixTypes - Return true if the two specified matrix types are 8669 /// compatible. 8670 static bool areCompatMatrixTypes(const ConstantMatrixType *LHS, 8671 const ConstantMatrixType *RHS) { 8672 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 8673 return LHS->getElementType() == RHS->getElementType() && 8674 LHS->getNumRows() == RHS->getNumRows() && 8675 LHS->getNumColumns() == RHS->getNumColumns(); 8676 } 8677 8678 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec, 8679 QualType SecondVec) { 8680 assert(FirstVec->isVectorType() && "FirstVec should be a vector type"); 8681 assert(SecondVec->isVectorType() && "SecondVec should be a vector type"); 8682 8683 if (hasSameUnqualifiedType(FirstVec, SecondVec)) 8684 return true; 8685 8686 // Treat Neon vector types and most AltiVec vector types as if they are the 8687 // equivalent GCC vector types. 8688 const auto *First = FirstVec->castAs<VectorType>(); 8689 const auto *Second = SecondVec->castAs<VectorType>(); 8690 if (First->getNumElements() == Second->getNumElements() && 8691 hasSameType(First->getElementType(), Second->getElementType()) && 8692 First->getVectorKind() != VectorType::AltiVecPixel && 8693 First->getVectorKind() != VectorType::AltiVecBool && 8694 Second->getVectorKind() != VectorType::AltiVecPixel && 8695 Second->getVectorKind() != VectorType::AltiVecBool && 8696 First->getVectorKind() != VectorType::SveFixedLengthDataVector && 8697 First->getVectorKind() != VectorType::SveFixedLengthPredicateVector && 8698 Second->getVectorKind() != VectorType::SveFixedLengthDataVector && 8699 Second->getVectorKind() != VectorType::SveFixedLengthPredicateVector) 8700 return true; 8701 8702 return false; 8703 } 8704 8705 /// getSVETypeSize - Return SVE vector or predicate register size. 8706 static uint64_t getSVETypeSize(ASTContext &Context, const BuiltinType *Ty) { 8707 assert(Ty->isVLSTBuiltinType() && "Invalid SVE Type"); 8708 return Ty->getKind() == BuiltinType::SveBool 8709 ? Context.getLangOpts().ArmSveVectorBits / Context.getCharWidth() 8710 : Context.getLangOpts().ArmSveVectorBits; 8711 } 8712 8713 bool ASTContext::areCompatibleSveTypes(QualType FirstType, 8714 QualType SecondType) { 8715 assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) || 8716 (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) && 8717 "Expected SVE builtin type and vector type!"); 8718 8719 auto IsValidCast = [this](QualType FirstType, QualType SecondType) { 8720 if (const auto *BT = FirstType->getAs<BuiltinType>()) { 8721 if (const auto *VT = SecondType->getAs<VectorType>()) { 8722 // Predicates have the same representation as uint8 so we also have to 8723 // check the kind to make these types incompatible. 8724 if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 8725 return BT->getKind() == BuiltinType::SveBool; 8726 else if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) 8727 return VT->getElementType().getCanonicalType() == 8728 FirstType->getSveEltType(*this); 8729 else if (VT->getVectorKind() == VectorType::GenericVector) 8730 return getTypeSize(SecondType) == getSVETypeSize(*this, BT) && 8731 hasSameType(VT->getElementType(), 8732 getBuiltinVectorTypeInfo(BT).ElementType); 8733 } 8734 } 8735 return false; 8736 }; 8737 8738 return IsValidCast(FirstType, SecondType) || 8739 IsValidCast(SecondType, FirstType); 8740 } 8741 8742 bool ASTContext::areLaxCompatibleSveTypes(QualType FirstType, 8743 QualType SecondType) { 8744 assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) || 8745 (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) && 8746 "Expected SVE builtin type and vector type!"); 8747 8748 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) { 8749 const auto *BT = FirstType->getAs<BuiltinType>(); 8750 if (!BT) 8751 return false; 8752 8753 const auto *VecTy = SecondType->getAs<VectorType>(); 8754 if (VecTy && 8755 (VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector || 8756 VecTy->getVectorKind() == VectorType::GenericVector)) { 8757 const LangOptions::LaxVectorConversionKind LVCKind = 8758 getLangOpts().getLaxVectorConversions(); 8759 8760 // Can not convert between sve predicates and sve vectors because of 8761 // different size. 8762 if (BT->getKind() == BuiltinType::SveBool && 8763 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector) 8764 return false; 8765 8766 // If __ARM_FEATURE_SVE_BITS != N do not allow GNU vector lax conversion. 8767 // "Whenever __ARM_FEATURE_SVE_BITS==N, GNUT implicitly 8768 // converts to VLAT and VLAT implicitly converts to GNUT." 8769 // ACLE Spec Version 00bet6, 3.7.3.2. Behavior common to vectors and 8770 // predicates. 8771 if (VecTy->getVectorKind() == VectorType::GenericVector && 8772 getTypeSize(SecondType) != getSVETypeSize(*this, BT)) 8773 return false; 8774 8775 // If -flax-vector-conversions=all is specified, the types are 8776 // certainly compatible. 8777 if (LVCKind == LangOptions::LaxVectorConversionKind::All) 8778 return true; 8779 8780 // If -flax-vector-conversions=integer is specified, the types are 8781 // compatible if the elements are integer types. 8782 if (LVCKind == LangOptions::LaxVectorConversionKind::Integer) 8783 return VecTy->getElementType().getCanonicalType()->isIntegerType() && 8784 FirstType->getSveEltType(*this)->isIntegerType(); 8785 } 8786 8787 return false; 8788 }; 8789 8790 return IsLaxCompatible(FirstType, SecondType) || 8791 IsLaxCompatible(SecondType, FirstType); 8792 } 8793 8794 bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const { 8795 while (true) { 8796 // __strong id 8797 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) { 8798 if (Attr->getAttrKind() == attr::ObjCOwnership) 8799 return true; 8800 8801 Ty = Attr->getModifiedType(); 8802 8803 // X *__strong (...) 8804 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) { 8805 Ty = Paren->getInnerType(); 8806 8807 // We do not want to look through typedefs, typeof(expr), 8808 // typeof(type), or any other way that the type is somehow 8809 // abstracted. 8810 } else { 8811 return false; 8812 } 8813 } 8814 } 8815 8816 //===----------------------------------------------------------------------===// 8817 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's. 8818 //===----------------------------------------------------------------------===// 8819 8820 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the 8821 /// inheritance hierarchy of 'rProto'. 8822 bool 8823 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, 8824 ObjCProtocolDecl *rProto) const { 8825 if (declaresSameEntity(lProto, rProto)) 8826 return true; 8827 for (auto *PI : rProto->protocols()) 8828 if (ProtocolCompatibleWithProtocol(lProto, PI)) 8829 return true; 8830 return false; 8831 } 8832 8833 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and 8834 /// Class<pr1, ...>. 8835 bool ASTContext::ObjCQualifiedClassTypesAreCompatible( 8836 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) { 8837 for (auto *lhsProto : lhs->quals()) { 8838 bool match = false; 8839 for (auto *rhsProto : rhs->quals()) { 8840 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) { 8841 match = true; 8842 break; 8843 } 8844 } 8845 if (!match) 8846 return false; 8847 } 8848 return true; 8849 } 8850 8851 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an 8852 /// ObjCQualifiedIDType. 8853 bool ASTContext::ObjCQualifiedIdTypesAreCompatible( 8854 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs, 8855 bool compare) { 8856 // Allow id<P..> and an 'id' in all cases. 8857 if (lhs->isObjCIdType() || rhs->isObjCIdType()) 8858 return true; 8859 8860 // Don't allow id<P..> to convert to Class or Class<P..> in either direction. 8861 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() || 8862 rhs->isObjCClassType() || rhs->isObjCQualifiedClassType()) 8863 return false; 8864 8865 if (lhs->isObjCQualifiedIdType()) { 8866 if (rhs->qual_empty()) { 8867 // If the RHS is a unqualified interface pointer "NSString*", 8868 // make sure we check the class hierarchy. 8869 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) { 8870 for (auto *I : lhs->quals()) { 8871 // when comparing an id<P> on lhs with a static type on rhs, 8872 // see if static class implements all of id's protocols, directly or 8873 // through its super class and categories. 8874 if (!rhsID->ClassImplementsProtocol(I, true)) 8875 return false; 8876 } 8877 } 8878 // If there are no qualifiers and no interface, we have an 'id'. 8879 return true; 8880 } 8881 // Both the right and left sides have qualifiers. 8882 for (auto *lhsProto : lhs->quals()) { 8883 bool match = false; 8884 8885 // when comparing an id<P> on lhs with a static type on rhs, 8886 // see if static class implements all of id's protocols, directly or 8887 // through its super class and categories. 8888 for (auto *rhsProto : rhs->quals()) { 8889 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 8890 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 8891 match = true; 8892 break; 8893 } 8894 } 8895 // If the RHS is a qualified interface pointer "NSString<P>*", 8896 // make sure we check the class hierarchy. 8897 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) { 8898 for (auto *I : lhs->quals()) { 8899 // when comparing an id<P> on lhs with a static type on rhs, 8900 // see if static class implements all of id's protocols, directly or 8901 // through its super class and categories. 8902 if (rhsID->ClassImplementsProtocol(I, true)) { 8903 match = true; 8904 break; 8905 } 8906 } 8907 } 8908 if (!match) 8909 return false; 8910 } 8911 8912 return true; 8913 } 8914 8915 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>"); 8916 8917 if (lhs->getInterfaceType()) { 8918 // If both the right and left sides have qualifiers. 8919 for (auto *lhsProto : lhs->quals()) { 8920 bool match = false; 8921 8922 // when comparing an id<P> on rhs with a static type on lhs, 8923 // see if static class implements all of id's protocols, directly or 8924 // through its super class and categories. 8925 // First, lhs protocols in the qualifier list must be found, direct 8926 // or indirect in rhs's qualifier list or it is a mismatch. 8927 for (auto *rhsProto : rhs->quals()) { 8928 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 8929 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 8930 match = true; 8931 break; 8932 } 8933 } 8934 if (!match) 8935 return false; 8936 } 8937 8938 // Static class's protocols, or its super class or category protocols 8939 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch. 8940 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) { 8941 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols; 8942 CollectInheritedProtocols(lhsID, LHSInheritedProtocols); 8943 // This is rather dubious but matches gcc's behavior. If lhs has 8944 // no type qualifier and its class has no static protocol(s) 8945 // assume that it is mismatch. 8946 if (LHSInheritedProtocols.empty() && lhs->qual_empty()) 8947 return false; 8948 for (auto *lhsProto : LHSInheritedProtocols) { 8949 bool match = false; 8950 for (auto *rhsProto : rhs->quals()) { 8951 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 8952 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 8953 match = true; 8954 break; 8955 } 8956 } 8957 if (!match) 8958 return false; 8959 } 8960 } 8961 return true; 8962 } 8963 return false; 8964 } 8965 8966 /// canAssignObjCInterfaces - Return true if the two interface types are 8967 /// compatible for assignment from RHS to LHS. This handles validation of any 8968 /// protocol qualifiers on the LHS or RHS. 8969 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, 8970 const ObjCObjectPointerType *RHSOPT) { 8971 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 8972 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 8973 8974 // If either type represents the built-in 'id' type, return true. 8975 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId()) 8976 return true; 8977 8978 // Function object that propagates a successful result or handles 8979 // __kindof types. 8980 auto finish = [&](bool succeeded) -> bool { 8981 if (succeeded) 8982 return true; 8983 8984 if (!RHS->isKindOfType()) 8985 return false; 8986 8987 // Strip off __kindof and protocol qualifiers, then check whether 8988 // we can assign the other way. 8989 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this), 8990 LHSOPT->stripObjCKindOfTypeAndQuals(*this)); 8991 }; 8992 8993 // Casts from or to id<P> are allowed when the other side has compatible 8994 // protocols. 8995 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) { 8996 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false)); 8997 } 8998 8999 // Verify protocol compatibility for casts from Class<P1> to Class<P2>. 9000 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) { 9001 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT)); 9002 } 9003 9004 // Casts from Class to Class<Foo>, or vice-versa, are allowed. 9005 if (LHS->isObjCClass() && RHS->isObjCClass()) { 9006 return true; 9007 } 9008 9009 // If we have 2 user-defined types, fall into that path. 9010 if (LHS->getInterface() && RHS->getInterface()) { 9011 return finish(canAssignObjCInterfaces(LHS, RHS)); 9012 } 9013 9014 return false; 9015 } 9016 9017 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written 9018 /// for providing type-safety for objective-c pointers used to pass/return 9019 /// arguments in block literals. When passed as arguments, passing 'A*' where 9020 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is 9021 /// not OK. For the return type, the opposite is not OK. 9022 bool ASTContext::canAssignObjCInterfacesInBlockPointer( 9023 const ObjCObjectPointerType *LHSOPT, 9024 const ObjCObjectPointerType *RHSOPT, 9025 bool BlockReturnType) { 9026 9027 // Function object that propagates a successful result or handles 9028 // __kindof types. 9029 auto finish = [&](bool succeeded) -> bool { 9030 if (succeeded) 9031 return true; 9032 9033 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT; 9034 if (!Expected->isKindOfType()) 9035 return false; 9036 9037 // Strip off __kindof and protocol qualifiers, then check whether 9038 // we can assign the other way. 9039 return canAssignObjCInterfacesInBlockPointer( 9040 RHSOPT->stripObjCKindOfTypeAndQuals(*this), 9041 LHSOPT->stripObjCKindOfTypeAndQuals(*this), 9042 BlockReturnType); 9043 }; 9044 9045 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType()) 9046 return true; 9047 9048 if (LHSOPT->isObjCBuiltinType()) { 9049 return finish(RHSOPT->isObjCBuiltinType() || 9050 RHSOPT->isObjCQualifiedIdType()); 9051 } 9052 9053 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) { 9054 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking) 9055 // Use for block parameters previous type checking for compatibility. 9056 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) || 9057 // Or corrected type checking as in non-compat mode. 9058 (!BlockReturnType && 9059 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false))); 9060 else 9061 return finish(ObjCQualifiedIdTypesAreCompatible( 9062 (BlockReturnType ? LHSOPT : RHSOPT), 9063 (BlockReturnType ? RHSOPT : LHSOPT), false)); 9064 } 9065 9066 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType(); 9067 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType(); 9068 if (LHS && RHS) { // We have 2 user-defined types. 9069 if (LHS != RHS) { 9070 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl())) 9071 return finish(BlockReturnType); 9072 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl())) 9073 return finish(!BlockReturnType); 9074 } 9075 else 9076 return true; 9077 } 9078 return false; 9079 } 9080 9081 /// Comparison routine for Objective-C protocols to be used with 9082 /// llvm::array_pod_sort. 9083 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs, 9084 ObjCProtocolDecl * const *rhs) { 9085 return (*lhs)->getName().compare((*rhs)->getName()); 9086 } 9087 9088 /// getIntersectionOfProtocols - This routine finds the intersection of set 9089 /// of protocols inherited from two distinct objective-c pointer objects with 9090 /// the given common base. 9091 /// It is used to build composite qualifier list of the composite type of 9092 /// the conditional expression involving two objective-c pointer objects. 9093 static 9094 void getIntersectionOfProtocols(ASTContext &Context, 9095 const ObjCInterfaceDecl *CommonBase, 9096 const ObjCObjectPointerType *LHSOPT, 9097 const ObjCObjectPointerType *RHSOPT, 9098 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) { 9099 9100 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 9101 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 9102 assert(LHS->getInterface() && "LHS must have an interface base"); 9103 assert(RHS->getInterface() && "RHS must have an interface base"); 9104 9105 // Add all of the protocols for the LHS. 9106 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet; 9107 9108 // Start with the protocol qualifiers. 9109 for (auto proto : LHS->quals()) { 9110 Context.CollectInheritedProtocols(proto, LHSProtocolSet); 9111 } 9112 9113 // Also add the protocols associated with the LHS interface. 9114 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet); 9115 9116 // Add all of the protocols for the RHS. 9117 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet; 9118 9119 // Start with the protocol qualifiers. 9120 for (auto proto : RHS->quals()) { 9121 Context.CollectInheritedProtocols(proto, RHSProtocolSet); 9122 } 9123 9124 // Also add the protocols associated with the RHS interface. 9125 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet); 9126 9127 // Compute the intersection of the collected protocol sets. 9128 for (auto proto : LHSProtocolSet) { 9129 if (RHSProtocolSet.count(proto)) 9130 IntersectionSet.push_back(proto); 9131 } 9132 9133 // Compute the set of protocols that is implied by either the common type or 9134 // the protocols within the intersection. 9135 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols; 9136 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols); 9137 9138 // Remove any implied protocols from the list of inherited protocols. 9139 if (!ImpliedProtocols.empty()) { 9140 IntersectionSet.erase( 9141 std::remove_if(IntersectionSet.begin(), 9142 IntersectionSet.end(), 9143 [&](ObjCProtocolDecl *proto) -> bool { 9144 return ImpliedProtocols.count(proto) > 0; 9145 }), 9146 IntersectionSet.end()); 9147 } 9148 9149 // Sort the remaining protocols by name. 9150 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(), 9151 compareObjCProtocolsByName); 9152 } 9153 9154 /// Determine whether the first type is a subtype of the second. 9155 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs, 9156 QualType rhs) { 9157 // Common case: two object pointers. 9158 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>(); 9159 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 9160 if (lhsOPT && rhsOPT) 9161 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT); 9162 9163 // Two block pointers. 9164 const auto *lhsBlock = lhs->getAs<BlockPointerType>(); 9165 const auto *rhsBlock = rhs->getAs<BlockPointerType>(); 9166 if (lhsBlock && rhsBlock) 9167 return ctx.typesAreBlockPointerCompatible(lhs, rhs); 9168 9169 // If either is an unqualified 'id' and the other is a block, it's 9170 // acceptable. 9171 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) || 9172 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock)) 9173 return true; 9174 9175 return false; 9176 } 9177 9178 // Check that the given Objective-C type argument lists are equivalent. 9179 static bool sameObjCTypeArgs(ASTContext &ctx, 9180 const ObjCInterfaceDecl *iface, 9181 ArrayRef<QualType> lhsArgs, 9182 ArrayRef<QualType> rhsArgs, 9183 bool stripKindOf) { 9184 if (lhsArgs.size() != rhsArgs.size()) 9185 return false; 9186 9187 ObjCTypeParamList *typeParams = iface->getTypeParamList(); 9188 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) { 9189 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i])) 9190 continue; 9191 9192 switch (typeParams->begin()[i]->getVariance()) { 9193 case ObjCTypeParamVariance::Invariant: 9194 if (!stripKindOf || 9195 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx), 9196 rhsArgs[i].stripObjCKindOfType(ctx))) { 9197 return false; 9198 } 9199 break; 9200 9201 case ObjCTypeParamVariance::Covariant: 9202 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i])) 9203 return false; 9204 break; 9205 9206 case ObjCTypeParamVariance::Contravariant: 9207 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i])) 9208 return false; 9209 break; 9210 } 9211 } 9212 9213 return true; 9214 } 9215 9216 QualType ASTContext::areCommonBaseCompatible( 9217 const ObjCObjectPointerType *Lptr, 9218 const ObjCObjectPointerType *Rptr) { 9219 const ObjCObjectType *LHS = Lptr->getObjectType(); 9220 const ObjCObjectType *RHS = Rptr->getObjectType(); 9221 const ObjCInterfaceDecl* LDecl = LHS->getInterface(); 9222 const ObjCInterfaceDecl* RDecl = RHS->getInterface(); 9223 9224 if (!LDecl || !RDecl) 9225 return {}; 9226 9227 // When either LHS or RHS is a kindof type, we should return a kindof type. 9228 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return 9229 // kindof(A). 9230 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType(); 9231 9232 // Follow the left-hand side up the class hierarchy until we either hit a 9233 // root or find the RHS. Record the ancestors in case we don't find it. 9234 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4> 9235 LHSAncestors; 9236 while (true) { 9237 // Record this ancestor. We'll need this if the common type isn't in the 9238 // path from the LHS to the root. 9239 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS; 9240 9241 if (declaresSameEntity(LHS->getInterface(), RDecl)) { 9242 // Get the type arguments. 9243 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten(); 9244 bool anyChanges = false; 9245 if (LHS->isSpecialized() && RHS->isSpecialized()) { 9246 // Both have type arguments, compare them. 9247 if (!sameObjCTypeArgs(*this, LHS->getInterface(), 9248 LHS->getTypeArgs(), RHS->getTypeArgs(), 9249 /*stripKindOf=*/true)) 9250 return {}; 9251 } else if (LHS->isSpecialized() != RHS->isSpecialized()) { 9252 // If only one has type arguments, the result will not have type 9253 // arguments. 9254 LHSTypeArgs = {}; 9255 anyChanges = true; 9256 } 9257 9258 // Compute the intersection of protocols. 9259 SmallVector<ObjCProtocolDecl *, 8> Protocols; 9260 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr, 9261 Protocols); 9262 if (!Protocols.empty()) 9263 anyChanges = true; 9264 9265 // If anything in the LHS will have changed, build a new result type. 9266 // If we need to return a kindof type but LHS is not a kindof type, we 9267 // build a new result type. 9268 if (anyChanges || LHS->isKindOfType() != anyKindOf) { 9269 QualType Result = getObjCInterfaceType(LHS->getInterface()); 9270 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols, 9271 anyKindOf || LHS->isKindOfType()); 9272 return getObjCObjectPointerType(Result); 9273 } 9274 9275 return getObjCObjectPointerType(QualType(LHS, 0)); 9276 } 9277 9278 // Find the superclass. 9279 QualType LHSSuperType = LHS->getSuperClassType(); 9280 if (LHSSuperType.isNull()) 9281 break; 9282 9283 LHS = LHSSuperType->castAs<ObjCObjectType>(); 9284 } 9285 9286 // We didn't find anything by following the LHS to its root; now check 9287 // the RHS against the cached set of ancestors. 9288 while (true) { 9289 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl()); 9290 if (KnownLHS != LHSAncestors.end()) { 9291 LHS = KnownLHS->second; 9292 9293 // Get the type arguments. 9294 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten(); 9295 bool anyChanges = false; 9296 if (LHS->isSpecialized() && RHS->isSpecialized()) { 9297 // Both have type arguments, compare them. 9298 if (!sameObjCTypeArgs(*this, LHS->getInterface(), 9299 LHS->getTypeArgs(), RHS->getTypeArgs(), 9300 /*stripKindOf=*/true)) 9301 return {}; 9302 } else if (LHS->isSpecialized() != RHS->isSpecialized()) { 9303 // If only one has type arguments, the result will not have type 9304 // arguments. 9305 RHSTypeArgs = {}; 9306 anyChanges = true; 9307 } 9308 9309 // Compute the intersection of protocols. 9310 SmallVector<ObjCProtocolDecl *, 8> Protocols; 9311 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr, 9312 Protocols); 9313 if (!Protocols.empty()) 9314 anyChanges = true; 9315 9316 // If we need to return a kindof type but RHS is not a kindof type, we 9317 // build a new result type. 9318 if (anyChanges || RHS->isKindOfType() != anyKindOf) { 9319 QualType Result = getObjCInterfaceType(RHS->getInterface()); 9320 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols, 9321 anyKindOf || RHS->isKindOfType()); 9322 return getObjCObjectPointerType(Result); 9323 } 9324 9325 return getObjCObjectPointerType(QualType(RHS, 0)); 9326 } 9327 9328 // Find the superclass of the RHS. 9329 QualType RHSSuperType = RHS->getSuperClassType(); 9330 if (RHSSuperType.isNull()) 9331 break; 9332 9333 RHS = RHSSuperType->castAs<ObjCObjectType>(); 9334 } 9335 9336 return {}; 9337 } 9338 9339 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS, 9340 const ObjCObjectType *RHS) { 9341 assert(LHS->getInterface() && "LHS is not an interface type"); 9342 assert(RHS->getInterface() && "RHS is not an interface type"); 9343 9344 // Verify that the base decls are compatible: the RHS must be a subclass of 9345 // the LHS. 9346 ObjCInterfaceDecl *LHSInterface = LHS->getInterface(); 9347 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface()); 9348 if (!IsSuperClass) 9349 return false; 9350 9351 // If the LHS has protocol qualifiers, determine whether all of them are 9352 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the 9353 // LHS). 9354 if (LHS->getNumProtocols() > 0) { 9355 // OK if conversion of LHS to SuperClass results in narrowing of types 9356 // ; i.e., SuperClass may implement at least one of the protocols 9357 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok. 9358 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>. 9359 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols; 9360 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols); 9361 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's 9362 // qualifiers. 9363 for (auto *RHSPI : RHS->quals()) 9364 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols); 9365 // If there is no protocols associated with RHS, it is not a match. 9366 if (SuperClassInheritedProtocols.empty()) 9367 return false; 9368 9369 for (const auto *LHSProto : LHS->quals()) { 9370 bool SuperImplementsProtocol = false; 9371 for (auto *SuperClassProto : SuperClassInheritedProtocols) 9372 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) { 9373 SuperImplementsProtocol = true; 9374 break; 9375 } 9376 if (!SuperImplementsProtocol) 9377 return false; 9378 } 9379 } 9380 9381 // If the LHS is specialized, we may need to check type arguments. 9382 if (LHS->isSpecialized()) { 9383 // Follow the superclass chain until we've matched the LHS class in the 9384 // hierarchy. This substitutes type arguments through. 9385 const ObjCObjectType *RHSSuper = RHS; 9386 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface)) 9387 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>(); 9388 9389 // If the RHS is specializd, compare type arguments. 9390 if (RHSSuper->isSpecialized() && 9391 !sameObjCTypeArgs(*this, LHS->getInterface(), 9392 LHS->getTypeArgs(), RHSSuper->getTypeArgs(), 9393 /*stripKindOf=*/true)) { 9394 return false; 9395 } 9396 } 9397 9398 return true; 9399 } 9400 9401 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) { 9402 // get the "pointed to" types 9403 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>(); 9404 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>(); 9405 9406 if (!LHSOPT || !RHSOPT) 9407 return false; 9408 9409 return canAssignObjCInterfaces(LHSOPT, RHSOPT) || 9410 canAssignObjCInterfaces(RHSOPT, LHSOPT); 9411 } 9412 9413 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) { 9414 return canAssignObjCInterfaces( 9415 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(), 9416 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>()); 9417 } 9418 9419 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible, 9420 /// both shall have the identically qualified version of a compatible type. 9421 /// C99 6.2.7p1: Two types have compatible types if their types are the 9422 /// same. See 6.7.[2,3,5] for additional rules. 9423 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS, 9424 bool CompareUnqualified) { 9425 if (getLangOpts().CPlusPlus) 9426 return hasSameType(LHS, RHS); 9427 9428 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull(); 9429 } 9430 9431 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) { 9432 return typesAreCompatible(LHS, RHS); 9433 } 9434 9435 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) { 9436 return !mergeTypes(LHS, RHS, true).isNull(); 9437 } 9438 9439 /// mergeTransparentUnionType - if T is a transparent union type and a member 9440 /// of T is compatible with SubType, return the merged type, else return 9441 /// QualType() 9442 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType, 9443 bool OfBlockPointer, 9444 bool Unqualified) { 9445 if (const RecordType *UT = T->getAsUnionType()) { 9446 RecordDecl *UD = UT->getDecl(); 9447 if (UD->hasAttr<TransparentUnionAttr>()) { 9448 for (const auto *I : UD->fields()) { 9449 QualType ET = I->getType().getUnqualifiedType(); 9450 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified); 9451 if (!MT.isNull()) 9452 return MT; 9453 } 9454 } 9455 } 9456 9457 return {}; 9458 } 9459 9460 /// mergeFunctionParameterTypes - merge two types which appear as function 9461 /// parameter types 9462 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs, 9463 bool OfBlockPointer, 9464 bool Unqualified) { 9465 // GNU extension: two types are compatible if they appear as a function 9466 // argument, one of the types is a transparent union type and the other 9467 // type is compatible with a union member 9468 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer, 9469 Unqualified); 9470 if (!lmerge.isNull()) 9471 return lmerge; 9472 9473 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer, 9474 Unqualified); 9475 if (!rmerge.isNull()) 9476 return rmerge; 9477 9478 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified); 9479 } 9480 9481 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, 9482 bool OfBlockPointer, bool Unqualified, 9483 bool AllowCXX) { 9484 const auto *lbase = lhs->castAs<FunctionType>(); 9485 const auto *rbase = rhs->castAs<FunctionType>(); 9486 const auto *lproto = dyn_cast<FunctionProtoType>(lbase); 9487 const auto *rproto = dyn_cast<FunctionProtoType>(rbase); 9488 bool allLTypes = true; 9489 bool allRTypes = true; 9490 9491 // Check return type 9492 QualType retType; 9493 if (OfBlockPointer) { 9494 QualType RHS = rbase->getReturnType(); 9495 QualType LHS = lbase->getReturnType(); 9496 bool UnqualifiedResult = Unqualified; 9497 if (!UnqualifiedResult) 9498 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers()); 9499 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true); 9500 } 9501 else 9502 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false, 9503 Unqualified); 9504 if (retType.isNull()) 9505 return {}; 9506 9507 if (Unqualified) 9508 retType = retType.getUnqualifiedType(); 9509 9510 CanQualType LRetType = getCanonicalType(lbase->getReturnType()); 9511 CanQualType RRetType = getCanonicalType(rbase->getReturnType()); 9512 if (Unqualified) { 9513 LRetType = LRetType.getUnqualifiedType(); 9514 RRetType = RRetType.getUnqualifiedType(); 9515 } 9516 9517 if (getCanonicalType(retType) != LRetType) 9518 allLTypes = false; 9519 if (getCanonicalType(retType) != RRetType) 9520 allRTypes = false; 9521 9522 // FIXME: double check this 9523 // FIXME: should we error if lbase->getRegParmAttr() != 0 && 9524 // rbase->getRegParmAttr() != 0 && 9525 // lbase->getRegParmAttr() != rbase->getRegParmAttr()? 9526 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo(); 9527 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo(); 9528 9529 // Compatible functions must have compatible calling conventions 9530 if (lbaseInfo.getCC() != rbaseInfo.getCC()) 9531 return {}; 9532 9533 // Regparm is part of the calling convention. 9534 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm()) 9535 return {}; 9536 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm()) 9537 return {}; 9538 9539 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult()) 9540 return {}; 9541 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs()) 9542 return {}; 9543 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck()) 9544 return {}; 9545 9546 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'. 9547 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn(); 9548 9549 if (lbaseInfo.getNoReturn() != NoReturn) 9550 allLTypes = false; 9551 if (rbaseInfo.getNoReturn() != NoReturn) 9552 allRTypes = false; 9553 9554 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn); 9555 9556 if (lproto && rproto) { // two C99 style function prototypes 9557 assert((AllowCXX || 9558 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) && 9559 "C++ shouldn't be here"); 9560 // Compatible functions must have the same number of parameters 9561 if (lproto->getNumParams() != rproto->getNumParams()) 9562 return {}; 9563 9564 // Variadic and non-variadic functions aren't compatible 9565 if (lproto->isVariadic() != rproto->isVariadic()) 9566 return {}; 9567 9568 if (lproto->getMethodQuals() != rproto->getMethodQuals()) 9569 return {}; 9570 9571 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos; 9572 bool canUseLeft, canUseRight; 9573 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight, 9574 newParamInfos)) 9575 return {}; 9576 9577 if (!canUseLeft) 9578 allLTypes = false; 9579 if (!canUseRight) 9580 allRTypes = false; 9581 9582 // Check parameter type compatibility 9583 SmallVector<QualType, 10> types; 9584 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) { 9585 QualType lParamType = lproto->getParamType(i).getUnqualifiedType(); 9586 QualType rParamType = rproto->getParamType(i).getUnqualifiedType(); 9587 QualType paramType = mergeFunctionParameterTypes( 9588 lParamType, rParamType, OfBlockPointer, Unqualified); 9589 if (paramType.isNull()) 9590 return {}; 9591 9592 if (Unqualified) 9593 paramType = paramType.getUnqualifiedType(); 9594 9595 types.push_back(paramType); 9596 if (Unqualified) { 9597 lParamType = lParamType.getUnqualifiedType(); 9598 rParamType = rParamType.getUnqualifiedType(); 9599 } 9600 9601 if (getCanonicalType(paramType) != getCanonicalType(lParamType)) 9602 allLTypes = false; 9603 if (getCanonicalType(paramType) != getCanonicalType(rParamType)) 9604 allRTypes = false; 9605 } 9606 9607 if (allLTypes) return lhs; 9608 if (allRTypes) return rhs; 9609 9610 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo(); 9611 EPI.ExtInfo = einfo; 9612 EPI.ExtParameterInfos = 9613 newParamInfos.empty() ? nullptr : newParamInfos.data(); 9614 return getFunctionType(retType, types, EPI); 9615 } 9616 9617 if (lproto) allRTypes = false; 9618 if (rproto) allLTypes = false; 9619 9620 const FunctionProtoType *proto = lproto ? lproto : rproto; 9621 if (proto) { 9622 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here"); 9623 if (proto->isVariadic()) 9624 return {}; 9625 // Check that the types are compatible with the types that 9626 // would result from default argument promotions (C99 6.7.5.3p15). 9627 // The only types actually affected are promotable integer 9628 // types and floats, which would be passed as a different 9629 // type depending on whether the prototype is visible. 9630 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) { 9631 QualType paramTy = proto->getParamType(i); 9632 9633 // Look at the converted type of enum types, since that is the type used 9634 // to pass enum values. 9635 if (const auto *Enum = paramTy->getAs<EnumType>()) { 9636 paramTy = Enum->getDecl()->getIntegerType(); 9637 if (paramTy.isNull()) 9638 return {}; 9639 } 9640 9641 if (paramTy->isPromotableIntegerType() || 9642 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy) 9643 return {}; 9644 } 9645 9646 if (allLTypes) return lhs; 9647 if (allRTypes) return rhs; 9648 9649 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo(); 9650 EPI.ExtInfo = einfo; 9651 return getFunctionType(retType, proto->getParamTypes(), EPI); 9652 } 9653 9654 if (allLTypes) return lhs; 9655 if (allRTypes) return rhs; 9656 return getFunctionNoProtoType(retType, einfo); 9657 } 9658 9659 /// Given that we have an enum type and a non-enum type, try to merge them. 9660 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET, 9661 QualType other, bool isBlockReturnType) { 9662 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char, 9663 // a signed integer type, or an unsigned integer type. 9664 // Compatibility is based on the underlying type, not the promotion 9665 // type. 9666 QualType underlyingType = ET->getDecl()->getIntegerType(); 9667 if (underlyingType.isNull()) 9668 return {}; 9669 if (Context.hasSameType(underlyingType, other)) 9670 return other; 9671 9672 // In block return types, we're more permissive and accept any 9673 // integral type of the same size. 9674 if (isBlockReturnType && other->isIntegerType() && 9675 Context.getTypeSize(underlyingType) == Context.getTypeSize(other)) 9676 return other; 9677 9678 return {}; 9679 } 9680 9681 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, 9682 bool OfBlockPointer, 9683 bool Unqualified, bool BlockReturnType) { 9684 // C++ [expr]: If an expression initially has the type "reference to T", the 9685 // type is adjusted to "T" prior to any further analysis, the expression 9686 // designates the object or function denoted by the reference, and the 9687 // expression is an lvalue unless the reference is an rvalue reference and 9688 // the expression is a function call (possibly inside parentheses). 9689 if (LHS->getAs<ReferenceType>() || RHS->getAs<ReferenceType>()) 9690 return {}; 9691 9692 if (Unqualified) { 9693 LHS = LHS.getUnqualifiedType(); 9694 RHS = RHS.getUnqualifiedType(); 9695 } 9696 9697 QualType LHSCan = getCanonicalType(LHS), 9698 RHSCan = getCanonicalType(RHS); 9699 9700 // If two types are identical, they are compatible. 9701 if (LHSCan == RHSCan) 9702 return LHS; 9703 9704 // If the qualifiers are different, the types aren't compatible... mostly. 9705 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 9706 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 9707 if (LQuals != RQuals) { 9708 // If any of these qualifiers are different, we have a type 9709 // mismatch. 9710 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 9711 LQuals.getAddressSpace() != RQuals.getAddressSpace() || 9712 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() || 9713 LQuals.hasUnaligned() != RQuals.hasUnaligned()) 9714 return {}; 9715 9716 // Exactly one GC qualifier difference is allowed: __strong is 9717 // okay if the other type has no GC qualifier but is an Objective 9718 // C object pointer (i.e. implicitly strong by default). We fix 9719 // this by pretending that the unqualified type was actually 9720 // qualified __strong. 9721 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 9722 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 9723 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 9724 9725 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 9726 return {}; 9727 9728 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) { 9729 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong)); 9730 } 9731 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) { 9732 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS); 9733 } 9734 return {}; 9735 } 9736 9737 // Okay, qualifiers are equal. 9738 9739 Type::TypeClass LHSClass = LHSCan->getTypeClass(); 9740 Type::TypeClass RHSClass = RHSCan->getTypeClass(); 9741 9742 // We want to consider the two function types to be the same for these 9743 // comparisons, just force one to the other. 9744 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto; 9745 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto; 9746 9747 // Same as above for arrays 9748 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray) 9749 LHSClass = Type::ConstantArray; 9750 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray) 9751 RHSClass = Type::ConstantArray; 9752 9753 // ObjCInterfaces are just specialized ObjCObjects. 9754 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject; 9755 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject; 9756 9757 // Canonicalize ExtVector -> Vector. 9758 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector; 9759 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector; 9760 9761 // If the canonical type classes don't match. 9762 if (LHSClass != RHSClass) { 9763 // Note that we only have special rules for turning block enum 9764 // returns into block int returns, not vice-versa. 9765 if (const auto *ETy = LHS->getAs<EnumType>()) { 9766 return mergeEnumWithInteger(*this, ETy, RHS, false); 9767 } 9768 if (const EnumType* ETy = RHS->getAs<EnumType>()) { 9769 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType); 9770 } 9771 // allow block pointer type to match an 'id' type. 9772 if (OfBlockPointer && !BlockReturnType) { 9773 if (LHS->isObjCIdType() && RHS->isBlockPointerType()) 9774 return LHS; 9775 if (RHS->isObjCIdType() && LHS->isBlockPointerType()) 9776 return RHS; 9777 } 9778 9779 return {}; 9780 } 9781 9782 // The canonical type classes match. 9783 switch (LHSClass) { 9784 #define TYPE(Class, Base) 9785 #define ABSTRACT_TYPE(Class, Base) 9786 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 9787 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 9788 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 9789 #include "clang/AST/TypeNodes.inc" 9790 llvm_unreachable("Non-canonical and dependent types shouldn't get here"); 9791 9792 case Type::Auto: 9793 case Type::DeducedTemplateSpecialization: 9794 case Type::LValueReference: 9795 case Type::RValueReference: 9796 case Type::MemberPointer: 9797 llvm_unreachable("C++ should never be in mergeTypes"); 9798 9799 case Type::ObjCInterface: 9800 case Type::IncompleteArray: 9801 case Type::VariableArray: 9802 case Type::FunctionProto: 9803 case Type::ExtVector: 9804 llvm_unreachable("Types are eliminated above"); 9805 9806 case Type::Pointer: 9807 { 9808 // Merge two pointer types, while trying to preserve typedef info 9809 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType(); 9810 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType(); 9811 if (Unqualified) { 9812 LHSPointee = LHSPointee.getUnqualifiedType(); 9813 RHSPointee = RHSPointee.getUnqualifiedType(); 9814 } 9815 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false, 9816 Unqualified); 9817 if (ResultType.isNull()) 9818 return {}; 9819 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 9820 return LHS; 9821 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 9822 return RHS; 9823 return getPointerType(ResultType); 9824 } 9825 case Type::BlockPointer: 9826 { 9827 // Merge two block pointer types, while trying to preserve typedef info 9828 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType(); 9829 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType(); 9830 if (Unqualified) { 9831 LHSPointee = LHSPointee.getUnqualifiedType(); 9832 RHSPointee = RHSPointee.getUnqualifiedType(); 9833 } 9834 if (getLangOpts().OpenCL) { 9835 Qualifiers LHSPteeQual = LHSPointee.getQualifiers(); 9836 Qualifiers RHSPteeQual = RHSPointee.getQualifiers(); 9837 // Blocks can't be an expression in a ternary operator (OpenCL v2.0 9838 // 6.12.5) thus the following check is asymmetric. 9839 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual)) 9840 return {}; 9841 LHSPteeQual.removeAddressSpace(); 9842 RHSPteeQual.removeAddressSpace(); 9843 LHSPointee = 9844 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue()); 9845 RHSPointee = 9846 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue()); 9847 } 9848 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer, 9849 Unqualified); 9850 if (ResultType.isNull()) 9851 return {}; 9852 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 9853 return LHS; 9854 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 9855 return RHS; 9856 return getBlockPointerType(ResultType); 9857 } 9858 case Type::Atomic: 9859 { 9860 // Merge two pointer types, while trying to preserve typedef info 9861 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType(); 9862 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType(); 9863 if (Unqualified) { 9864 LHSValue = LHSValue.getUnqualifiedType(); 9865 RHSValue = RHSValue.getUnqualifiedType(); 9866 } 9867 QualType ResultType = mergeTypes(LHSValue, RHSValue, false, 9868 Unqualified); 9869 if (ResultType.isNull()) 9870 return {}; 9871 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType)) 9872 return LHS; 9873 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType)) 9874 return RHS; 9875 return getAtomicType(ResultType); 9876 } 9877 case Type::ConstantArray: 9878 { 9879 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS); 9880 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS); 9881 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize()) 9882 return {}; 9883 9884 QualType LHSElem = getAsArrayType(LHS)->getElementType(); 9885 QualType RHSElem = getAsArrayType(RHS)->getElementType(); 9886 if (Unqualified) { 9887 LHSElem = LHSElem.getUnqualifiedType(); 9888 RHSElem = RHSElem.getUnqualifiedType(); 9889 } 9890 9891 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified); 9892 if (ResultType.isNull()) 9893 return {}; 9894 9895 const VariableArrayType* LVAT = getAsVariableArrayType(LHS); 9896 const VariableArrayType* RVAT = getAsVariableArrayType(RHS); 9897 9898 // If either side is a variable array, and both are complete, check whether 9899 // the current dimension is definite. 9900 if (LVAT || RVAT) { 9901 auto SizeFetch = [this](const VariableArrayType* VAT, 9902 const ConstantArrayType* CAT) 9903 -> std::pair<bool,llvm::APInt> { 9904 if (VAT) { 9905 Optional<llvm::APSInt> TheInt; 9906 Expr *E = VAT->getSizeExpr(); 9907 if (E && (TheInt = E->getIntegerConstantExpr(*this))) 9908 return std::make_pair(true, *TheInt); 9909 return std::make_pair(false, llvm::APSInt()); 9910 } 9911 if (CAT) 9912 return std::make_pair(true, CAT->getSize()); 9913 return std::make_pair(false, llvm::APInt()); 9914 }; 9915 9916 bool HaveLSize, HaveRSize; 9917 llvm::APInt LSize, RSize; 9918 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT); 9919 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT); 9920 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize)) 9921 return {}; // Definite, but unequal, array dimension 9922 } 9923 9924 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 9925 return LHS; 9926 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 9927 return RHS; 9928 if (LCAT) 9929 return getConstantArrayType(ResultType, LCAT->getSize(), 9930 LCAT->getSizeExpr(), 9931 ArrayType::ArraySizeModifier(), 0); 9932 if (RCAT) 9933 return getConstantArrayType(ResultType, RCAT->getSize(), 9934 RCAT->getSizeExpr(), 9935 ArrayType::ArraySizeModifier(), 0); 9936 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 9937 return LHS; 9938 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 9939 return RHS; 9940 if (LVAT) { 9941 // FIXME: This isn't correct! But tricky to implement because 9942 // the array's size has to be the size of LHS, but the type 9943 // has to be different. 9944 return LHS; 9945 } 9946 if (RVAT) { 9947 // FIXME: This isn't correct! But tricky to implement because 9948 // the array's size has to be the size of RHS, but the type 9949 // has to be different. 9950 return RHS; 9951 } 9952 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS; 9953 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS; 9954 return getIncompleteArrayType(ResultType, 9955 ArrayType::ArraySizeModifier(), 0); 9956 } 9957 case Type::FunctionNoProto: 9958 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified); 9959 case Type::Record: 9960 case Type::Enum: 9961 return {}; 9962 case Type::Builtin: 9963 // Only exactly equal builtin types are compatible, which is tested above. 9964 return {}; 9965 case Type::Complex: 9966 // Distinct complex types are incompatible. 9967 return {}; 9968 case Type::Vector: 9969 // FIXME: The merged type should be an ExtVector! 9970 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(), 9971 RHSCan->castAs<VectorType>())) 9972 return LHS; 9973 return {}; 9974 case Type::ConstantMatrix: 9975 if (areCompatMatrixTypes(LHSCan->castAs<ConstantMatrixType>(), 9976 RHSCan->castAs<ConstantMatrixType>())) 9977 return LHS; 9978 return {}; 9979 case Type::ObjCObject: { 9980 // Check if the types are assignment compatible. 9981 // FIXME: This should be type compatibility, e.g. whether 9982 // "LHS x; RHS x;" at global scope is legal. 9983 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectType>(), 9984 RHS->castAs<ObjCObjectType>())) 9985 return LHS; 9986 return {}; 9987 } 9988 case Type::ObjCObjectPointer: 9989 if (OfBlockPointer) { 9990 if (canAssignObjCInterfacesInBlockPointer( 9991 LHS->castAs<ObjCObjectPointerType>(), 9992 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType)) 9993 return LHS; 9994 return {}; 9995 } 9996 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectPointerType>(), 9997 RHS->castAs<ObjCObjectPointerType>())) 9998 return LHS; 9999 return {}; 10000 case Type::Pipe: 10001 assert(LHS != RHS && 10002 "Equivalent pipe types should have already been handled!"); 10003 return {}; 10004 case Type::ExtInt: { 10005 // Merge two ext-int types, while trying to preserve typedef info. 10006 bool LHSUnsigned = LHS->castAs<ExtIntType>()->isUnsigned(); 10007 bool RHSUnsigned = RHS->castAs<ExtIntType>()->isUnsigned(); 10008 unsigned LHSBits = LHS->castAs<ExtIntType>()->getNumBits(); 10009 unsigned RHSBits = RHS->castAs<ExtIntType>()->getNumBits(); 10010 10011 // Like unsigned/int, shouldn't have a type if they dont match. 10012 if (LHSUnsigned != RHSUnsigned) 10013 return {}; 10014 10015 if (LHSBits != RHSBits) 10016 return {}; 10017 return LHS; 10018 } 10019 } 10020 10021 llvm_unreachable("Invalid Type::Class!"); 10022 } 10023 10024 bool ASTContext::mergeExtParameterInfo( 10025 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType, 10026 bool &CanUseFirst, bool &CanUseSecond, 10027 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) { 10028 assert(NewParamInfos.empty() && "param info list not empty"); 10029 CanUseFirst = CanUseSecond = true; 10030 bool FirstHasInfo = FirstFnType->hasExtParameterInfos(); 10031 bool SecondHasInfo = SecondFnType->hasExtParameterInfos(); 10032 10033 // Fast path: if the first type doesn't have ext parameter infos, 10034 // we match if and only if the second type also doesn't have them. 10035 if (!FirstHasInfo && !SecondHasInfo) 10036 return true; 10037 10038 bool NeedParamInfo = false; 10039 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size() 10040 : SecondFnType->getExtParameterInfos().size(); 10041 10042 for (size_t I = 0; I < E; ++I) { 10043 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam; 10044 if (FirstHasInfo) 10045 FirstParam = FirstFnType->getExtParameterInfo(I); 10046 if (SecondHasInfo) 10047 SecondParam = SecondFnType->getExtParameterInfo(I); 10048 10049 // Cannot merge unless everything except the noescape flag matches. 10050 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false)) 10051 return false; 10052 10053 bool FirstNoEscape = FirstParam.isNoEscape(); 10054 bool SecondNoEscape = SecondParam.isNoEscape(); 10055 bool IsNoEscape = FirstNoEscape && SecondNoEscape; 10056 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape)); 10057 if (NewParamInfos.back().getOpaqueValue()) 10058 NeedParamInfo = true; 10059 if (FirstNoEscape != IsNoEscape) 10060 CanUseFirst = false; 10061 if (SecondNoEscape != IsNoEscape) 10062 CanUseSecond = false; 10063 } 10064 10065 if (!NeedParamInfo) 10066 NewParamInfos.clear(); 10067 10068 return true; 10069 } 10070 10071 void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) { 10072 ObjCLayouts[CD] = nullptr; 10073 } 10074 10075 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 10076 /// 'RHS' attributes and returns the merged version; including for function 10077 /// return types. 10078 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) { 10079 QualType LHSCan = getCanonicalType(LHS), 10080 RHSCan = getCanonicalType(RHS); 10081 // If two types are identical, they are compatible. 10082 if (LHSCan == RHSCan) 10083 return LHS; 10084 if (RHSCan->isFunctionType()) { 10085 if (!LHSCan->isFunctionType()) 10086 return {}; 10087 QualType OldReturnType = 10088 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType(); 10089 QualType NewReturnType = 10090 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType(); 10091 QualType ResReturnType = 10092 mergeObjCGCQualifiers(NewReturnType, OldReturnType); 10093 if (ResReturnType.isNull()) 10094 return {}; 10095 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) { 10096 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo(); 10097 // In either case, use OldReturnType to build the new function type. 10098 const auto *F = LHS->castAs<FunctionType>(); 10099 if (const auto *FPT = cast<FunctionProtoType>(F)) { 10100 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10101 EPI.ExtInfo = getFunctionExtInfo(LHS); 10102 QualType ResultType = 10103 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI); 10104 return ResultType; 10105 } 10106 } 10107 return {}; 10108 } 10109 10110 // If the qualifiers are different, the types can still be merged. 10111 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 10112 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 10113 if (LQuals != RQuals) { 10114 // If any of these qualifiers are different, we have a type mismatch. 10115 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 10116 LQuals.getAddressSpace() != RQuals.getAddressSpace()) 10117 return {}; 10118 10119 // Exactly one GC qualifier difference is allowed: __strong is 10120 // okay if the other type has no GC qualifier but is an Objective 10121 // C object pointer (i.e. implicitly strong by default). We fix 10122 // this by pretending that the unqualified type was actually 10123 // qualified __strong. 10124 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 10125 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 10126 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 10127 10128 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 10129 return {}; 10130 10131 if (GC_L == Qualifiers::Strong) 10132 return LHS; 10133 if (GC_R == Qualifiers::Strong) 10134 return RHS; 10135 return {}; 10136 } 10137 10138 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) { 10139 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType(); 10140 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType(); 10141 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT); 10142 if (ResQT == LHSBaseQT) 10143 return LHS; 10144 if (ResQT == RHSBaseQT) 10145 return RHS; 10146 } 10147 return {}; 10148 } 10149 10150 //===----------------------------------------------------------------------===// 10151 // Integer Predicates 10152 //===----------------------------------------------------------------------===// 10153 10154 unsigned ASTContext::getIntWidth(QualType T) const { 10155 if (const auto *ET = T->getAs<EnumType>()) 10156 T = ET->getDecl()->getIntegerType(); 10157 if (T->isBooleanType()) 10158 return 1; 10159 if(const auto *EIT = T->getAs<ExtIntType>()) 10160 return EIT->getNumBits(); 10161 // For builtin types, just use the standard type sizing method 10162 return (unsigned)getTypeSize(T); 10163 } 10164 10165 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const { 10166 assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) && 10167 "Unexpected type"); 10168 10169 // Turn <4 x signed int> -> <4 x unsigned int> 10170 if (const auto *VTy = T->getAs<VectorType>()) 10171 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()), 10172 VTy->getNumElements(), VTy->getVectorKind()); 10173 10174 // For _ExtInt, return an unsigned _ExtInt with same width. 10175 if (const auto *EITy = T->getAs<ExtIntType>()) 10176 return getExtIntType(/*IsUnsigned=*/true, EITy->getNumBits()); 10177 10178 // For enums, get the underlying integer type of the enum, and let the general 10179 // integer type signchanging code handle it. 10180 if (const auto *ETy = T->getAs<EnumType>()) 10181 T = ETy->getDecl()->getIntegerType(); 10182 10183 switch (T->castAs<BuiltinType>()->getKind()) { 10184 case BuiltinType::Char_S: 10185 case BuiltinType::SChar: 10186 return UnsignedCharTy; 10187 case BuiltinType::Short: 10188 return UnsignedShortTy; 10189 case BuiltinType::Int: 10190 return UnsignedIntTy; 10191 case BuiltinType::Long: 10192 return UnsignedLongTy; 10193 case BuiltinType::LongLong: 10194 return UnsignedLongLongTy; 10195 case BuiltinType::Int128: 10196 return UnsignedInt128Ty; 10197 // wchar_t is special. It is either signed or not, but when it's signed, 10198 // there's no matching "unsigned wchar_t". Therefore we return the unsigned 10199 // version of it's underlying type instead. 10200 case BuiltinType::WChar_S: 10201 return getUnsignedWCharType(); 10202 10203 case BuiltinType::ShortAccum: 10204 return UnsignedShortAccumTy; 10205 case BuiltinType::Accum: 10206 return UnsignedAccumTy; 10207 case BuiltinType::LongAccum: 10208 return UnsignedLongAccumTy; 10209 case BuiltinType::SatShortAccum: 10210 return SatUnsignedShortAccumTy; 10211 case BuiltinType::SatAccum: 10212 return SatUnsignedAccumTy; 10213 case BuiltinType::SatLongAccum: 10214 return SatUnsignedLongAccumTy; 10215 case BuiltinType::ShortFract: 10216 return UnsignedShortFractTy; 10217 case BuiltinType::Fract: 10218 return UnsignedFractTy; 10219 case BuiltinType::LongFract: 10220 return UnsignedLongFractTy; 10221 case BuiltinType::SatShortFract: 10222 return SatUnsignedShortFractTy; 10223 case BuiltinType::SatFract: 10224 return SatUnsignedFractTy; 10225 case BuiltinType::SatLongFract: 10226 return SatUnsignedLongFractTy; 10227 default: 10228 llvm_unreachable("Unexpected signed integer or fixed point type"); 10229 } 10230 } 10231 10232 QualType ASTContext::getCorrespondingSignedType(QualType T) const { 10233 assert((T->hasUnsignedIntegerRepresentation() || 10234 T->isUnsignedFixedPointType()) && 10235 "Unexpected type"); 10236 10237 // Turn <4 x unsigned int> -> <4 x signed int> 10238 if (const auto *VTy = T->getAs<VectorType>()) 10239 return getVectorType(getCorrespondingSignedType(VTy->getElementType()), 10240 VTy->getNumElements(), VTy->getVectorKind()); 10241 10242 // For _ExtInt, return a signed _ExtInt with same width. 10243 if (const auto *EITy = T->getAs<ExtIntType>()) 10244 return getExtIntType(/*IsUnsigned=*/false, EITy->getNumBits()); 10245 10246 // For enums, get the underlying integer type of the enum, and let the general 10247 // integer type signchanging code handle it. 10248 if (const auto *ETy = T->getAs<EnumType>()) 10249 T = ETy->getDecl()->getIntegerType(); 10250 10251 switch (T->castAs<BuiltinType>()->getKind()) { 10252 case BuiltinType::Char_U: 10253 case BuiltinType::UChar: 10254 return SignedCharTy; 10255 case BuiltinType::UShort: 10256 return ShortTy; 10257 case BuiltinType::UInt: 10258 return IntTy; 10259 case BuiltinType::ULong: 10260 return LongTy; 10261 case BuiltinType::ULongLong: 10262 return LongLongTy; 10263 case BuiltinType::UInt128: 10264 return Int128Ty; 10265 // wchar_t is special. It is either unsigned or not, but when it's unsigned, 10266 // there's no matching "signed wchar_t". Therefore we return the signed 10267 // version of it's underlying type instead. 10268 case BuiltinType::WChar_U: 10269 return getSignedWCharType(); 10270 10271 case BuiltinType::UShortAccum: 10272 return ShortAccumTy; 10273 case BuiltinType::UAccum: 10274 return AccumTy; 10275 case BuiltinType::ULongAccum: 10276 return LongAccumTy; 10277 case BuiltinType::SatUShortAccum: 10278 return SatShortAccumTy; 10279 case BuiltinType::SatUAccum: 10280 return SatAccumTy; 10281 case BuiltinType::SatULongAccum: 10282 return SatLongAccumTy; 10283 case BuiltinType::UShortFract: 10284 return ShortFractTy; 10285 case BuiltinType::UFract: 10286 return FractTy; 10287 case BuiltinType::ULongFract: 10288 return LongFractTy; 10289 case BuiltinType::SatUShortFract: 10290 return SatShortFractTy; 10291 case BuiltinType::SatUFract: 10292 return SatFractTy; 10293 case BuiltinType::SatULongFract: 10294 return SatLongFractTy; 10295 default: 10296 llvm_unreachable("Unexpected unsigned integer or fixed point type"); 10297 } 10298 } 10299 10300 ASTMutationListener::~ASTMutationListener() = default; 10301 10302 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD, 10303 QualType ReturnType) {} 10304 10305 //===----------------------------------------------------------------------===// 10306 // Builtin Type Computation 10307 //===----------------------------------------------------------------------===// 10308 10309 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the 10310 /// pointer over the consumed characters. This returns the resultant type. If 10311 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic 10312 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of 10313 /// a vector of "i*". 10314 /// 10315 /// RequiresICE is filled in on return to indicate whether the value is required 10316 /// to be an Integer Constant Expression. 10317 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, 10318 ASTContext::GetBuiltinTypeError &Error, 10319 bool &RequiresICE, 10320 bool AllowTypeModifiers) { 10321 // Modifiers. 10322 int HowLong = 0; 10323 bool Signed = false, Unsigned = false; 10324 RequiresICE = false; 10325 10326 // Read the prefixed modifiers first. 10327 bool Done = false; 10328 #ifndef NDEBUG 10329 bool IsSpecial = false; 10330 #endif 10331 while (!Done) { 10332 switch (*Str++) { 10333 default: Done = true; --Str; break; 10334 case 'I': 10335 RequiresICE = true; 10336 break; 10337 case 'S': 10338 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!"); 10339 assert(!Signed && "Can't use 'S' modifier multiple times!"); 10340 Signed = true; 10341 break; 10342 case 'U': 10343 assert(!Signed && "Can't use both 'S' and 'U' modifiers!"); 10344 assert(!Unsigned && "Can't use 'U' modifier multiple times!"); 10345 Unsigned = true; 10346 break; 10347 case 'L': 10348 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers"); 10349 assert(HowLong <= 2 && "Can't have LLLL modifier"); 10350 ++HowLong; 10351 break; 10352 case 'N': 10353 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise. 10354 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10355 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!"); 10356 #ifndef NDEBUG 10357 IsSpecial = true; 10358 #endif 10359 if (Context.getTargetInfo().getLongWidth() == 32) 10360 ++HowLong; 10361 break; 10362 case 'W': 10363 // This modifier represents int64 type. 10364 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10365 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!"); 10366 #ifndef NDEBUG 10367 IsSpecial = true; 10368 #endif 10369 switch (Context.getTargetInfo().getInt64Type()) { 10370 default: 10371 llvm_unreachable("Unexpected integer type"); 10372 case TargetInfo::SignedLong: 10373 HowLong = 1; 10374 break; 10375 case TargetInfo::SignedLongLong: 10376 HowLong = 2; 10377 break; 10378 } 10379 break; 10380 case 'Z': 10381 // This modifier represents int32 type. 10382 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10383 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!"); 10384 #ifndef NDEBUG 10385 IsSpecial = true; 10386 #endif 10387 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) { 10388 default: 10389 llvm_unreachable("Unexpected integer type"); 10390 case TargetInfo::SignedInt: 10391 HowLong = 0; 10392 break; 10393 case TargetInfo::SignedLong: 10394 HowLong = 1; 10395 break; 10396 case TargetInfo::SignedLongLong: 10397 HowLong = 2; 10398 break; 10399 } 10400 break; 10401 case 'O': 10402 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10403 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!"); 10404 #ifndef NDEBUG 10405 IsSpecial = true; 10406 #endif 10407 if (Context.getLangOpts().OpenCL) 10408 HowLong = 1; 10409 else 10410 HowLong = 2; 10411 break; 10412 } 10413 } 10414 10415 QualType Type; 10416 10417 // Read the base type. 10418 switch (*Str++) { 10419 default: llvm_unreachable("Unknown builtin type letter!"); 10420 case 'x': 10421 assert(HowLong == 0 && !Signed && !Unsigned && 10422 "Bad modifiers used with 'x'!"); 10423 Type = Context.Float16Ty; 10424 break; 10425 case 'y': 10426 assert(HowLong == 0 && !Signed && !Unsigned && 10427 "Bad modifiers used with 'y'!"); 10428 Type = Context.BFloat16Ty; 10429 break; 10430 case 'v': 10431 assert(HowLong == 0 && !Signed && !Unsigned && 10432 "Bad modifiers used with 'v'!"); 10433 Type = Context.VoidTy; 10434 break; 10435 case 'h': 10436 assert(HowLong == 0 && !Signed && !Unsigned && 10437 "Bad modifiers used with 'h'!"); 10438 Type = Context.HalfTy; 10439 break; 10440 case 'f': 10441 assert(HowLong == 0 && !Signed && !Unsigned && 10442 "Bad modifiers used with 'f'!"); 10443 Type = Context.FloatTy; 10444 break; 10445 case 'd': 10446 assert(HowLong < 3 && !Signed && !Unsigned && 10447 "Bad modifiers used with 'd'!"); 10448 if (HowLong == 1) 10449 Type = Context.LongDoubleTy; 10450 else if (HowLong == 2) 10451 Type = Context.Float128Ty; 10452 else 10453 Type = Context.DoubleTy; 10454 break; 10455 case 's': 10456 assert(HowLong == 0 && "Bad modifiers used with 's'!"); 10457 if (Unsigned) 10458 Type = Context.UnsignedShortTy; 10459 else 10460 Type = Context.ShortTy; 10461 break; 10462 case 'i': 10463 if (HowLong == 3) 10464 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty; 10465 else if (HowLong == 2) 10466 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy; 10467 else if (HowLong == 1) 10468 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy; 10469 else 10470 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy; 10471 break; 10472 case 'c': 10473 assert(HowLong == 0 && "Bad modifiers used with 'c'!"); 10474 if (Signed) 10475 Type = Context.SignedCharTy; 10476 else if (Unsigned) 10477 Type = Context.UnsignedCharTy; 10478 else 10479 Type = Context.CharTy; 10480 break; 10481 case 'b': // boolean 10482 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!"); 10483 Type = Context.BoolTy; 10484 break; 10485 case 'z': // size_t. 10486 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!"); 10487 Type = Context.getSizeType(); 10488 break; 10489 case 'w': // wchar_t. 10490 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!"); 10491 Type = Context.getWideCharType(); 10492 break; 10493 case 'F': 10494 Type = Context.getCFConstantStringType(); 10495 break; 10496 case 'G': 10497 Type = Context.getObjCIdType(); 10498 break; 10499 case 'H': 10500 Type = Context.getObjCSelType(); 10501 break; 10502 case 'M': 10503 Type = Context.getObjCSuperType(); 10504 break; 10505 case 'a': 10506 Type = Context.getBuiltinVaListType(); 10507 assert(!Type.isNull() && "builtin va list type not initialized!"); 10508 break; 10509 case 'A': 10510 // This is a "reference" to a va_list; however, what exactly 10511 // this means depends on how va_list is defined. There are two 10512 // different kinds of va_list: ones passed by value, and ones 10513 // passed by reference. An example of a by-value va_list is 10514 // x86, where va_list is a char*. An example of by-ref va_list 10515 // is x86-64, where va_list is a __va_list_tag[1]. For x86, 10516 // we want this argument to be a char*&; for x86-64, we want 10517 // it to be a __va_list_tag*. 10518 Type = Context.getBuiltinVaListType(); 10519 assert(!Type.isNull() && "builtin va list type not initialized!"); 10520 if (Type->isArrayType()) 10521 Type = Context.getArrayDecayedType(Type); 10522 else 10523 Type = Context.getLValueReferenceType(Type); 10524 break; 10525 case 'q': { 10526 char *End; 10527 unsigned NumElements = strtoul(Str, &End, 10); 10528 assert(End != Str && "Missing vector size"); 10529 Str = End; 10530 10531 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 10532 RequiresICE, false); 10533 assert(!RequiresICE && "Can't require vector ICE"); 10534 10535 Type = Context.getScalableVectorType(ElementType, NumElements); 10536 break; 10537 } 10538 case 'V': { 10539 char *End; 10540 unsigned NumElements = strtoul(Str, &End, 10); 10541 assert(End != Str && "Missing vector size"); 10542 Str = End; 10543 10544 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 10545 RequiresICE, false); 10546 assert(!RequiresICE && "Can't require vector ICE"); 10547 10548 // TODO: No way to make AltiVec vectors in builtins yet. 10549 Type = Context.getVectorType(ElementType, NumElements, 10550 VectorType::GenericVector); 10551 break; 10552 } 10553 case 'E': { 10554 char *End; 10555 10556 unsigned NumElements = strtoul(Str, &End, 10); 10557 assert(End != Str && "Missing vector size"); 10558 10559 Str = End; 10560 10561 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 10562 false); 10563 Type = Context.getExtVectorType(ElementType, NumElements); 10564 break; 10565 } 10566 case 'X': { 10567 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 10568 false); 10569 assert(!RequiresICE && "Can't require complex ICE"); 10570 Type = Context.getComplexType(ElementType); 10571 break; 10572 } 10573 case 'Y': 10574 Type = Context.getPointerDiffType(); 10575 break; 10576 case 'P': 10577 Type = Context.getFILEType(); 10578 if (Type.isNull()) { 10579 Error = ASTContext::GE_Missing_stdio; 10580 return {}; 10581 } 10582 break; 10583 case 'J': 10584 if (Signed) 10585 Type = Context.getsigjmp_bufType(); 10586 else 10587 Type = Context.getjmp_bufType(); 10588 10589 if (Type.isNull()) { 10590 Error = ASTContext::GE_Missing_setjmp; 10591 return {}; 10592 } 10593 break; 10594 case 'K': 10595 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!"); 10596 Type = Context.getucontext_tType(); 10597 10598 if (Type.isNull()) { 10599 Error = ASTContext::GE_Missing_ucontext; 10600 return {}; 10601 } 10602 break; 10603 case 'p': 10604 Type = Context.getProcessIDType(); 10605 break; 10606 } 10607 10608 // If there are modifiers and if we're allowed to parse them, go for it. 10609 Done = !AllowTypeModifiers; 10610 while (!Done) { 10611 switch (char c = *Str++) { 10612 default: Done = true; --Str; break; 10613 case '*': 10614 case '&': { 10615 // Both pointers and references can have their pointee types 10616 // qualified with an address space. 10617 char *End; 10618 unsigned AddrSpace = strtoul(Str, &End, 10); 10619 if (End != Str) { 10620 // Note AddrSpace == 0 is not the same as an unspecified address space. 10621 Type = Context.getAddrSpaceQualType( 10622 Type, 10623 Context.getLangASForBuiltinAddressSpace(AddrSpace)); 10624 Str = End; 10625 } 10626 if (c == '*') 10627 Type = Context.getPointerType(Type); 10628 else 10629 Type = Context.getLValueReferenceType(Type); 10630 break; 10631 } 10632 // FIXME: There's no way to have a built-in with an rvalue ref arg. 10633 case 'C': 10634 Type = Type.withConst(); 10635 break; 10636 case 'D': 10637 Type = Context.getVolatileType(Type); 10638 break; 10639 case 'R': 10640 Type = Type.withRestrict(); 10641 break; 10642 } 10643 } 10644 10645 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) && 10646 "Integer constant 'I' type must be an integer"); 10647 10648 return Type; 10649 } 10650 10651 // On some targets such as PowerPC, some of the builtins are defined with custom 10652 // type decriptors for target-dependent types. These descriptors are decoded in 10653 // other functions, but it may be useful to be able to fall back to default 10654 // descriptor decoding to define builtins mixing target-dependent and target- 10655 // independent types. This function allows decoding one type descriptor with 10656 // default decoding. 10657 QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context, 10658 GetBuiltinTypeError &Error, bool &RequireICE, 10659 bool AllowTypeModifiers) const { 10660 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers); 10661 } 10662 10663 /// GetBuiltinType - Return the type for the specified builtin. 10664 QualType ASTContext::GetBuiltinType(unsigned Id, 10665 GetBuiltinTypeError &Error, 10666 unsigned *IntegerConstantArgs) const { 10667 const char *TypeStr = BuiltinInfo.getTypeString(Id); 10668 if (TypeStr[0] == '\0') { 10669 Error = GE_Missing_type; 10670 return {}; 10671 } 10672 10673 SmallVector<QualType, 8> ArgTypes; 10674 10675 bool RequiresICE = false; 10676 Error = GE_None; 10677 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error, 10678 RequiresICE, true); 10679 if (Error != GE_None) 10680 return {}; 10681 10682 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE"); 10683 10684 while (TypeStr[0] && TypeStr[0] != '.') { 10685 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true); 10686 if (Error != GE_None) 10687 return {}; 10688 10689 // If this argument is required to be an IntegerConstantExpression and the 10690 // caller cares, fill in the bitmask we return. 10691 if (RequiresICE && IntegerConstantArgs) 10692 *IntegerConstantArgs |= 1 << ArgTypes.size(); 10693 10694 // Do array -> pointer decay. The builtin should use the decayed type. 10695 if (Ty->isArrayType()) 10696 Ty = getArrayDecayedType(Ty); 10697 10698 ArgTypes.push_back(Ty); 10699 } 10700 10701 if (Id == Builtin::BI__GetExceptionInfo) 10702 return {}; 10703 10704 assert((TypeStr[0] != '.' || TypeStr[1] == 0) && 10705 "'.' should only occur at end of builtin type list!"); 10706 10707 bool Variadic = (TypeStr[0] == '.'); 10708 10709 FunctionType::ExtInfo EI(getDefaultCallingConvention( 10710 Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true)); 10711 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true); 10712 10713 10714 // We really shouldn't be making a no-proto type here. 10715 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus) 10716 return getFunctionNoProtoType(ResType, EI); 10717 10718 FunctionProtoType::ExtProtoInfo EPI; 10719 EPI.ExtInfo = EI; 10720 EPI.Variadic = Variadic; 10721 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id)) 10722 EPI.ExceptionSpec.Type = 10723 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone; 10724 10725 return getFunctionType(ResType, ArgTypes, EPI); 10726 } 10727 10728 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, 10729 const FunctionDecl *FD) { 10730 if (!FD->isExternallyVisible()) 10731 return GVA_Internal; 10732 10733 // Non-user-provided functions get emitted as weak definitions with every 10734 // use, no matter whether they've been explicitly instantiated etc. 10735 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 10736 if (!MD->isUserProvided()) 10737 return GVA_DiscardableODR; 10738 10739 GVALinkage External; 10740 switch (FD->getTemplateSpecializationKind()) { 10741 case TSK_Undeclared: 10742 case TSK_ExplicitSpecialization: 10743 External = GVA_StrongExternal; 10744 break; 10745 10746 case TSK_ExplicitInstantiationDefinition: 10747 return GVA_StrongODR; 10748 10749 // C++11 [temp.explicit]p10: 10750 // [ Note: The intent is that an inline function that is the subject of 10751 // an explicit instantiation declaration will still be implicitly 10752 // instantiated when used so that the body can be considered for 10753 // inlining, but that no out-of-line copy of the inline function would be 10754 // generated in the translation unit. -- end note ] 10755 case TSK_ExplicitInstantiationDeclaration: 10756 return GVA_AvailableExternally; 10757 10758 case TSK_ImplicitInstantiation: 10759 External = GVA_DiscardableODR; 10760 break; 10761 } 10762 10763 if (!FD->isInlined()) 10764 return External; 10765 10766 if ((!Context.getLangOpts().CPlusPlus && 10767 !Context.getTargetInfo().getCXXABI().isMicrosoft() && 10768 !FD->hasAttr<DLLExportAttr>()) || 10769 FD->hasAttr<GNUInlineAttr>()) { 10770 // FIXME: This doesn't match gcc's behavior for dllexport inline functions. 10771 10772 // GNU or C99 inline semantics. Determine whether this symbol should be 10773 // externally visible. 10774 if (FD->isInlineDefinitionExternallyVisible()) 10775 return External; 10776 10777 // C99 inline semantics, where the symbol is not externally visible. 10778 return GVA_AvailableExternally; 10779 } 10780 10781 // Functions specified with extern and inline in -fms-compatibility mode 10782 // forcibly get emitted. While the body of the function cannot be later 10783 // replaced, the function definition cannot be discarded. 10784 if (FD->isMSExternInline()) 10785 return GVA_StrongODR; 10786 10787 return GVA_DiscardableODR; 10788 } 10789 10790 static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context, 10791 const Decl *D, GVALinkage L) { 10792 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx 10793 // dllexport/dllimport on inline functions. 10794 if (D->hasAttr<DLLImportAttr>()) { 10795 if (L == GVA_DiscardableODR || L == GVA_StrongODR) 10796 return GVA_AvailableExternally; 10797 } else if (D->hasAttr<DLLExportAttr>()) { 10798 if (L == GVA_DiscardableODR) 10799 return GVA_StrongODR; 10800 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) { 10801 // Device-side functions with __global__ attribute must always be 10802 // visible externally so they can be launched from host. 10803 if (D->hasAttr<CUDAGlobalAttr>() && 10804 (L == GVA_DiscardableODR || L == GVA_Internal)) 10805 return GVA_StrongODR; 10806 // Single source offloading languages like CUDA/HIP need to be able to 10807 // access static device variables from host code of the same compilation 10808 // unit. This is done by externalizing the static variable with a shared 10809 // name between the host and device compilation which is the same for the 10810 // same compilation unit whereas different among different compilation 10811 // units. 10812 if (Context.shouldExternalizeStaticVar(D)) 10813 return GVA_StrongExternal; 10814 } 10815 return L; 10816 } 10817 10818 /// Adjust the GVALinkage for a declaration based on what an external AST source 10819 /// knows about whether there can be other definitions of this declaration. 10820 static GVALinkage 10821 adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D, 10822 GVALinkage L) { 10823 ExternalASTSource *Source = Ctx.getExternalSource(); 10824 if (!Source) 10825 return L; 10826 10827 switch (Source->hasExternalDefinitions(D)) { 10828 case ExternalASTSource::EK_Never: 10829 // Other translation units rely on us to provide the definition. 10830 if (L == GVA_DiscardableODR) 10831 return GVA_StrongODR; 10832 break; 10833 10834 case ExternalASTSource::EK_Always: 10835 return GVA_AvailableExternally; 10836 10837 case ExternalASTSource::EK_ReplyHazy: 10838 break; 10839 } 10840 return L; 10841 } 10842 10843 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const { 10844 return adjustGVALinkageForExternalDefinitionKind(*this, FD, 10845 adjustGVALinkageForAttributes(*this, FD, 10846 basicGVALinkageForFunction(*this, FD))); 10847 } 10848 10849 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context, 10850 const VarDecl *VD) { 10851 if (!VD->isExternallyVisible()) 10852 return GVA_Internal; 10853 10854 if (VD->isStaticLocal()) { 10855 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod(); 10856 while (LexicalContext && !isa<FunctionDecl>(LexicalContext)) 10857 LexicalContext = LexicalContext->getLexicalParent(); 10858 10859 // ObjC Blocks can create local variables that don't have a FunctionDecl 10860 // LexicalContext. 10861 if (!LexicalContext) 10862 return GVA_DiscardableODR; 10863 10864 // Otherwise, let the static local variable inherit its linkage from the 10865 // nearest enclosing function. 10866 auto StaticLocalLinkage = 10867 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext)); 10868 10869 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must 10870 // be emitted in any object with references to the symbol for the object it 10871 // contains, whether inline or out-of-line." 10872 // Similar behavior is observed with MSVC. An alternative ABI could use 10873 // StrongODR/AvailableExternally to match the function, but none are 10874 // known/supported currently. 10875 if (StaticLocalLinkage == GVA_StrongODR || 10876 StaticLocalLinkage == GVA_AvailableExternally) 10877 return GVA_DiscardableODR; 10878 return StaticLocalLinkage; 10879 } 10880 10881 // MSVC treats in-class initialized static data members as definitions. 10882 // By giving them non-strong linkage, out-of-line definitions won't 10883 // cause link errors. 10884 if (Context.isMSStaticDataMemberInlineDefinition(VD)) 10885 return GVA_DiscardableODR; 10886 10887 // Most non-template variables have strong linkage; inline variables are 10888 // linkonce_odr or (occasionally, for compatibility) weak_odr. 10889 GVALinkage StrongLinkage; 10890 switch (Context.getInlineVariableDefinitionKind(VD)) { 10891 case ASTContext::InlineVariableDefinitionKind::None: 10892 StrongLinkage = GVA_StrongExternal; 10893 break; 10894 case ASTContext::InlineVariableDefinitionKind::Weak: 10895 case ASTContext::InlineVariableDefinitionKind::WeakUnknown: 10896 StrongLinkage = GVA_DiscardableODR; 10897 break; 10898 case ASTContext::InlineVariableDefinitionKind::Strong: 10899 StrongLinkage = GVA_StrongODR; 10900 break; 10901 } 10902 10903 switch (VD->getTemplateSpecializationKind()) { 10904 case TSK_Undeclared: 10905 return StrongLinkage; 10906 10907 case TSK_ExplicitSpecialization: 10908 return Context.getTargetInfo().getCXXABI().isMicrosoft() && 10909 VD->isStaticDataMember() 10910 ? GVA_StrongODR 10911 : StrongLinkage; 10912 10913 case TSK_ExplicitInstantiationDefinition: 10914 return GVA_StrongODR; 10915 10916 case TSK_ExplicitInstantiationDeclaration: 10917 return GVA_AvailableExternally; 10918 10919 case TSK_ImplicitInstantiation: 10920 return GVA_DiscardableODR; 10921 } 10922 10923 llvm_unreachable("Invalid Linkage!"); 10924 } 10925 10926 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) { 10927 return adjustGVALinkageForExternalDefinitionKind(*this, VD, 10928 adjustGVALinkageForAttributes(*this, VD, 10929 basicGVALinkageForVariable(*this, VD))); 10930 } 10931 10932 bool ASTContext::DeclMustBeEmitted(const Decl *D) { 10933 if (const auto *VD = dyn_cast<VarDecl>(D)) { 10934 if (!VD->isFileVarDecl()) 10935 return false; 10936 // Global named register variables (GNU extension) are never emitted. 10937 if (VD->getStorageClass() == SC_Register) 10938 return false; 10939 if (VD->getDescribedVarTemplate() || 10940 isa<VarTemplatePartialSpecializationDecl>(VD)) 10941 return false; 10942 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 10943 // We never need to emit an uninstantiated function template. 10944 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10945 return false; 10946 } else if (isa<PragmaCommentDecl>(D)) 10947 return true; 10948 else if (isa<PragmaDetectMismatchDecl>(D)) 10949 return true; 10950 else if (isa<OMPRequiresDecl>(D)) 10951 return true; 10952 else if (isa<OMPThreadPrivateDecl>(D)) 10953 return !D->getDeclContext()->isDependentContext(); 10954 else if (isa<OMPAllocateDecl>(D)) 10955 return !D->getDeclContext()->isDependentContext(); 10956 else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D)) 10957 return !D->getDeclContext()->isDependentContext(); 10958 else if (isa<ImportDecl>(D)) 10959 return true; 10960 else 10961 return false; 10962 10963 // If this is a member of a class template, we do not need to emit it. 10964 if (D->getDeclContext()->isDependentContext()) 10965 return false; 10966 10967 // Weak references don't produce any output by themselves. 10968 if (D->hasAttr<WeakRefAttr>()) 10969 return false; 10970 10971 // Aliases and used decls are required. 10972 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>()) 10973 return true; 10974 10975 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 10976 // Forward declarations aren't required. 10977 if (!FD->doesThisDeclarationHaveABody()) 10978 return FD->doesDeclarationForceExternallyVisibleDefinition(); 10979 10980 // Constructors and destructors are required. 10981 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>()) 10982 return true; 10983 10984 // The key function for a class is required. This rule only comes 10985 // into play when inline functions can be key functions, though. 10986 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 10987 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 10988 const CXXRecordDecl *RD = MD->getParent(); 10989 if (MD->isOutOfLine() && RD->isDynamicClass()) { 10990 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD); 10991 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl()) 10992 return true; 10993 } 10994 } 10995 } 10996 10997 GVALinkage Linkage = GetGVALinkageForFunction(FD); 10998 10999 // static, static inline, always_inline, and extern inline functions can 11000 // always be deferred. Normal inline functions can be deferred in C99/C++. 11001 // Implicit template instantiations can also be deferred in C++. 11002 return !isDiscardableGVALinkage(Linkage); 11003 } 11004 11005 const auto *VD = cast<VarDecl>(D); 11006 assert(VD->isFileVarDecl() && "Expected file scoped var"); 11007 11008 // If the decl is marked as `declare target to`, it should be emitted for the 11009 // host and for the device. 11010 if (LangOpts.OpenMP && 11011 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 11012 return true; 11013 11014 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly && 11015 !isMSStaticDataMemberInlineDefinition(VD)) 11016 return false; 11017 11018 // Variables that can be needed in other TUs are required. 11019 auto Linkage = GetGVALinkageForVariable(VD); 11020 if (!isDiscardableGVALinkage(Linkage)) 11021 return true; 11022 11023 // We never need to emit a variable that is available in another TU. 11024 if (Linkage == GVA_AvailableExternally) 11025 return false; 11026 11027 // Variables that have destruction with side-effects are required. 11028 if (VD->needsDestruction(*this)) 11029 return true; 11030 11031 // Variables that have initialization with side-effects are required. 11032 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) && 11033 // We can get a value-dependent initializer during error recovery. 11034 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 11035 return true; 11036 11037 // Likewise, variables with tuple-like bindings are required if their 11038 // bindings have side-effects. 11039 if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) 11040 for (const auto *BD : DD->bindings()) 11041 if (const auto *BindingVD = BD->getHoldingVar()) 11042 if (DeclMustBeEmitted(BindingVD)) 11043 return true; 11044 11045 return false; 11046 } 11047 11048 void ASTContext::forEachMultiversionedFunctionVersion( 11049 const FunctionDecl *FD, 11050 llvm::function_ref<void(FunctionDecl *)> Pred) const { 11051 assert(FD->isMultiVersion() && "Only valid for multiversioned functions"); 11052 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls; 11053 FD = FD->getMostRecentDecl(); 11054 // FIXME: The order of traversal here matters and depends on the order of 11055 // lookup results, which happens to be (mostly) oldest-to-newest, but we 11056 // shouldn't rely on that. 11057 for (auto *CurDecl : 11058 FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) { 11059 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl(); 11060 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) && 11061 std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) { 11062 SeenDecls.insert(CurFD); 11063 Pred(CurFD); 11064 } 11065 } 11066 } 11067 11068 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic, 11069 bool IsCXXMethod, 11070 bool IsBuiltin) const { 11071 // Pass through to the C++ ABI object 11072 if (IsCXXMethod) 11073 return ABI->getDefaultMethodCallConv(IsVariadic); 11074 11075 // Builtins ignore user-specified default calling convention and remain the 11076 // Target's default calling convention. 11077 if (!IsBuiltin) { 11078 switch (LangOpts.getDefaultCallingConv()) { 11079 case LangOptions::DCC_None: 11080 break; 11081 case LangOptions::DCC_CDecl: 11082 return CC_C; 11083 case LangOptions::DCC_FastCall: 11084 if (getTargetInfo().hasFeature("sse2") && !IsVariadic) 11085 return CC_X86FastCall; 11086 break; 11087 case LangOptions::DCC_StdCall: 11088 if (!IsVariadic) 11089 return CC_X86StdCall; 11090 break; 11091 case LangOptions::DCC_VectorCall: 11092 // __vectorcall cannot be applied to variadic functions. 11093 if (!IsVariadic) 11094 return CC_X86VectorCall; 11095 break; 11096 case LangOptions::DCC_RegCall: 11097 // __regcall cannot be applied to variadic functions. 11098 if (!IsVariadic) 11099 return CC_X86RegCall; 11100 break; 11101 } 11102 } 11103 return Target->getDefaultCallingConv(); 11104 } 11105 11106 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const { 11107 // Pass through to the C++ ABI object 11108 return ABI->isNearlyEmpty(RD); 11109 } 11110 11111 VTableContextBase *ASTContext::getVTableContext() { 11112 if (!VTContext.get()) { 11113 auto ABI = Target->getCXXABI(); 11114 if (ABI.isMicrosoft()) 11115 VTContext.reset(new MicrosoftVTableContext(*this)); 11116 else { 11117 auto ComponentLayout = getLangOpts().RelativeCXXABIVTables 11118 ? ItaniumVTableContext::Relative 11119 : ItaniumVTableContext::Pointer; 11120 VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout)); 11121 } 11122 } 11123 return VTContext.get(); 11124 } 11125 11126 MangleContext *ASTContext::createMangleContext(const TargetInfo *T) { 11127 if (!T) 11128 T = Target; 11129 switch (T->getCXXABI().getKind()) { 11130 case TargetCXXABI::AppleARM64: 11131 case TargetCXXABI::Fuchsia: 11132 case TargetCXXABI::GenericAArch64: 11133 case TargetCXXABI::GenericItanium: 11134 case TargetCXXABI::GenericARM: 11135 case TargetCXXABI::GenericMIPS: 11136 case TargetCXXABI::iOS: 11137 case TargetCXXABI::WebAssembly: 11138 case TargetCXXABI::WatchOS: 11139 case TargetCXXABI::XL: 11140 return ItaniumMangleContext::create(*this, getDiagnostics()); 11141 case TargetCXXABI::Microsoft: 11142 return MicrosoftMangleContext::create(*this, getDiagnostics()); 11143 } 11144 llvm_unreachable("Unsupported ABI"); 11145 } 11146 11147 MangleContext *ASTContext::createDeviceMangleContext(const TargetInfo &T) { 11148 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft && 11149 "Device mangle context does not support Microsoft mangling."); 11150 switch (T.getCXXABI().getKind()) { 11151 case TargetCXXABI::AppleARM64: 11152 case TargetCXXABI::Fuchsia: 11153 case TargetCXXABI::GenericAArch64: 11154 case TargetCXXABI::GenericItanium: 11155 case TargetCXXABI::GenericARM: 11156 case TargetCXXABI::GenericMIPS: 11157 case TargetCXXABI::iOS: 11158 case TargetCXXABI::WebAssembly: 11159 case TargetCXXABI::WatchOS: 11160 case TargetCXXABI::XL: 11161 return ItaniumMangleContext::create( 11162 *this, getDiagnostics(), 11163 [](ASTContext &, const NamedDecl *ND) -> llvm::Optional<unsigned> { 11164 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) 11165 return RD->getDeviceLambdaManglingNumber(); 11166 return llvm::None; 11167 }); 11168 case TargetCXXABI::Microsoft: 11169 return MicrosoftMangleContext::create(*this, getDiagnostics()); 11170 } 11171 llvm_unreachable("Unsupported ABI"); 11172 } 11173 11174 CXXABI::~CXXABI() = default; 11175 11176 size_t ASTContext::getSideTableAllocatedMemory() const { 11177 return ASTRecordLayouts.getMemorySize() + 11178 llvm::capacity_in_bytes(ObjCLayouts) + 11179 llvm::capacity_in_bytes(KeyFunctions) + 11180 llvm::capacity_in_bytes(ObjCImpls) + 11181 llvm::capacity_in_bytes(BlockVarCopyInits) + 11182 llvm::capacity_in_bytes(DeclAttrs) + 11183 llvm::capacity_in_bytes(TemplateOrInstantiation) + 11184 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) + 11185 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) + 11186 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) + 11187 llvm::capacity_in_bytes(OverriddenMethods) + 11188 llvm::capacity_in_bytes(Types) + 11189 llvm::capacity_in_bytes(VariableArrayTypes); 11190 } 11191 11192 /// getIntTypeForBitwidth - 11193 /// sets integer QualTy according to specified details: 11194 /// bitwidth, signed/unsigned. 11195 /// Returns empty type if there is no appropriate target types. 11196 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth, 11197 unsigned Signed) const { 11198 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed); 11199 CanQualType QualTy = getFromTargetType(Ty); 11200 if (!QualTy && DestWidth == 128) 11201 return Signed ? Int128Ty : UnsignedInt128Ty; 11202 return QualTy; 11203 } 11204 11205 /// getRealTypeForBitwidth - 11206 /// sets floating point QualTy according to specified bitwidth. 11207 /// Returns empty type if there is no appropriate target types. 11208 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth, 11209 bool ExplicitIEEE) const { 11210 TargetInfo::RealType Ty = 11211 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitIEEE); 11212 switch (Ty) { 11213 case TargetInfo::Float: 11214 return FloatTy; 11215 case TargetInfo::Double: 11216 return DoubleTy; 11217 case TargetInfo::LongDouble: 11218 return LongDoubleTy; 11219 case TargetInfo::Float128: 11220 return Float128Ty; 11221 case TargetInfo::NoFloat: 11222 return {}; 11223 } 11224 11225 llvm_unreachable("Unhandled TargetInfo::RealType value"); 11226 } 11227 11228 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) { 11229 if (Number > 1) 11230 MangleNumbers[ND] = Number; 11231 } 11232 11233 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const { 11234 auto I = MangleNumbers.find(ND); 11235 return I != MangleNumbers.end() ? I->second : 1; 11236 } 11237 11238 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) { 11239 if (Number > 1) 11240 StaticLocalNumbers[VD] = Number; 11241 } 11242 11243 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const { 11244 auto I = StaticLocalNumbers.find(VD); 11245 return I != StaticLocalNumbers.end() ? I->second : 1; 11246 } 11247 11248 MangleNumberingContext & 11249 ASTContext::getManglingNumberContext(const DeclContext *DC) { 11250 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C. 11251 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC]; 11252 if (!MCtx) 11253 MCtx = createMangleNumberingContext(); 11254 return *MCtx; 11255 } 11256 11257 MangleNumberingContext & 11258 ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) { 11259 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C. 11260 std::unique_ptr<MangleNumberingContext> &MCtx = 11261 ExtraMangleNumberingContexts[D]; 11262 if (!MCtx) 11263 MCtx = createMangleNumberingContext(); 11264 return *MCtx; 11265 } 11266 11267 std::unique_ptr<MangleNumberingContext> 11268 ASTContext::createMangleNumberingContext() const { 11269 return ABI->createMangleNumberingContext(); 11270 } 11271 11272 const CXXConstructorDecl * 11273 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) { 11274 return ABI->getCopyConstructorForExceptionObject( 11275 cast<CXXRecordDecl>(RD->getFirstDecl())); 11276 } 11277 11278 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD, 11279 CXXConstructorDecl *CD) { 11280 return ABI->addCopyConstructorForExceptionObject( 11281 cast<CXXRecordDecl>(RD->getFirstDecl()), 11282 cast<CXXConstructorDecl>(CD->getFirstDecl())); 11283 } 11284 11285 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD, 11286 TypedefNameDecl *DD) { 11287 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD); 11288 } 11289 11290 TypedefNameDecl * 11291 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) { 11292 return ABI->getTypedefNameForUnnamedTagDecl(TD); 11293 } 11294 11295 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD, 11296 DeclaratorDecl *DD) { 11297 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD); 11298 } 11299 11300 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) { 11301 return ABI->getDeclaratorForUnnamedTagDecl(TD); 11302 } 11303 11304 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) { 11305 ParamIndices[D] = index; 11306 } 11307 11308 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const { 11309 ParameterIndexTable::const_iterator I = ParamIndices.find(D); 11310 assert(I != ParamIndices.end() && 11311 "ParmIndices lacks entry set by ParmVarDecl"); 11312 return I->second; 11313 } 11314 11315 QualType ASTContext::getStringLiteralArrayType(QualType EltTy, 11316 unsigned Length) const { 11317 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 11318 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 11319 EltTy = EltTy.withConst(); 11320 11321 EltTy = adjustStringLiteralBaseType(EltTy); 11322 11323 // Get an array type for the string, according to C99 6.4.5. This includes 11324 // the null terminator character. 11325 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr, 11326 ArrayType::Normal, /*IndexTypeQuals*/ 0); 11327 } 11328 11329 StringLiteral * 11330 ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const { 11331 StringLiteral *&Result = StringLiteralCache[Key]; 11332 if (!Result) 11333 Result = StringLiteral::Create( 11334 *this, Key, StringLiteral::Ascii, 11335 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()), 11336 SourceLocation()); 11337 return Result; 11338 } 11339 11340 MSGuidDecl * 11341 ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const { 11342 assert(MSGuidTagDecl && "building MS GUID without MS extensions?"); 11343 11344 llvm::FoldingSetNodeID ID; 11345 MSGuidDecl::Profile(ID, Parts); 11346 11347 void *InsertPos; 11348 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos)) 11349 return Existing; 11350 11351 QualType GUIDType = getMSGuidType().withConst(); 11352 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts); 11353 MSGuidDecls.InsertNode(New, InsertPos); 11354 return New; 11355 } 11356 11357 TemplateParamObjectDecl * 11358 ASTContext::getTemplateParamObjectDecl(QualType T, const APValue &V) const { 11359 assert(T->isRecordType() && "template param object of unexpected type"); 11360 11361 // C++ [temp.param]p8: 11362 // [...] a static storage duration object of type 'const T' [...] 11363 T.addConst(); 11364 11365 llvm::FoldingSetNodeID ID; 11366 TemplateParamObjectDecl::Profile(ID, T, V); 11367 11368 void *InsertPos; 11369 if (TemplateParamObjectDecl *Existing = 11370 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos)) 11371 return Existing; 11372 11373 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V); 11374 TemplateParamObjectDecls.InsertNode(New, InsertPos); 11375 return New; 11376 } 11377 11378 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const { 11379 const llvm::Triple &T = getTargetInfo().getTriple(); 11380 if (!T.isOSDarwin()) 11381 return false; 11382 11383 if (!(T.isiOS() && T.isOSVersionLT(7)) && 11384 !(T.isMacOSX() && T.isOSVersionLT(10, 9))) 11385 return false; 11386 11387 QualType AtomicTy = E->getPtr()->getType()->getPointeeType(); 11388 CharUnits sizeChars = getTypeSizeInChars(AtomicTy); 11389 uint64_t Size = sizeChars.getQuantity(); 11390 CharUnits alignChars = getTypeAlignInChars(AtomicTy); 11391 unsigned Align = alignChars.getQuantity(); 11392 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth(); 11393 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits); 11394 } 11395 11396 bool 11397 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, 11398 const ObjCMethodDecl *MethodImpl) { 11399 // No point trying to match an unavailable/deprecated mothod. 11400 if (MethodDecl->hasAttr<UnavailableAttr>() 11401 || MethodDecl->hasAttr<DeprecatedAttr>()) 11402 return false; 11403 if (MethodDecl->getObjCDeclQualifier() != 11404 MethodImpl->getObjCDeclQualifier()) 11405 return false; 11406 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType())) 11407 return false; 11408 11409 if (MethodDecl->param_size() != MethodImpl->param_size()) 11410 return false; 11411 11412 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(), 11413 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(), 11414 EF = MethodDecl->param_end(); 11415 IM != EM && IF != EF; ++IM, ++IF) { 11416 const ParmVarDecl *DeclVar = (*IF); 11417 const ParmVarDecl *ImplVar = (*IM); 11418 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier()) 11419 return false; 11420 if (!hasSameType(DeclVar->getType(), ImplVar->getType())) 11421 return false; 11422 } 11423 11424 return (MethodDecl->isVariadic() == MethodImpl->isVariadic()); 11425 } 11426 11427 uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const { 11428 LangAS AS; 11429 if (QT->getUnqualifiedDesugaredType()->isNullPtrType()) 11430 AS = LangAS::Default; 11431 else 11432 AS = QT->getPointeeType().getAddressSpace(); 11433 11434 return getTargetInfo().getNullPointerValue(AS); 11435 } 11436 11437 unsigned ASTContext::getTargetAddressSpace(LangAS AS) const { 11438 if (isTargetAddressSpace(AS)) 11439 return toTargetAddressSpace(AS); 11440 else 11441 return (*AddrSpaceMap)[(unsigned)AS]; 11442 } 11443 11444 QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const { 11445 assert(Ty->isFixedPointType()); 11446 11447 if (Ty->isSaturatedFixedPointType()) return Ty; 11448 11449 switch (Ty->castAs<BuiltinType>()->getKind()) { 11450 default: 11451 llvm_unreachable("Not a fixed point type!"); 11452 case BuiltinType::ShortAccum: 11453 return SatShortAccumTy; 11454 case BuiltinType::Accum: 11455 return SatAccumTy; 11456 case BuiltinType::LongAccum: 11457 return SatLongAccumTy; 11458 case BuiltinType::UShortAccum: 11459 return SatUnsignedShortAccumTy; 11460 case BuiltinType::UAccum: 11461 return SatUnsignedAccumTy; 11462 case BuiltinType::ULongAccum: 11463 return SatUnsignedLongAccumTy; 11464 case BuiltinType::ShortFract: 11465 return SatShortFractTy; 11466 case BuiltinType::Fract: 11467 return SatFractTy; 11468 case BuiltinType::LongFract: 11469 return SatLongFractTy; 11470 case BuiltinType::UShortFract: 11471 return SatUnsignedShortFractTy; 11472 case BuiltinType::UFract: 11473 return SatUnsignedFractTy; 11474 case BuiltinType::ULongFract: 11475 return SatUnsignedLongFractTy; 11476 } 11477 } 11478 11479 LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const { 11480 if (LangOpts.OpenCL) 11481 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS); 11482 11483 if (LangOpts.CUDA) 11484 return getTargetInfo().getCUDABuiltinAddressSpace(AS); 11485 11486 return getLangASFromTargetAS(AS); 11487 } 11488 11489 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that 11490 // doesn't include ASTContext.h 11491 template 11492 clang::LazyGenerationalUpdatePtr< 11493 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType 11494 clang::LazyGenerationalUpdatePtr< 11495 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue( 11496 const clang::ASTContext &Ctx, Decl *Value); 11497 11498 unsigned char ASTContext::getFixedPointScale(QualType Ty) const { 11499 assert(Ty->isFixedPointType()); 11500 11501 const TargetInfo &Target = getTargetInfo(); 11502 switch (Ty->castAs<BuiltinType>()->getKind()) { 11503 default: 11504 llvm_unreachable("Not a fixed point type!"); 11505 case BuiltinType::ShortAccum: 11506 case BuiltinType::SatShortAccum: 11507 return Target.getShortAccumScale(); 11508 case BuiltinType::Accum: 11509 case BuiltinType::SatAccum: 11510 return Target.getAccumScale(); 11511 case BuiltinType::LongAccum: 11512 case BuiltinType::SatLongAccum: 11513 return Target.getLongAccumScale(); 11514 case BuiltinType::UShortAccum: 11515 case BuiltinType::SatUShortAccum: 11516 return Target.getUnsignedShortAccumScale(); 11517 case BuiltinType::UAccum: 11518 case BuiltinType::SatUAccum: 11519 return Target.getUnsignedAccumScale(); 11520 case BuiltinType::ULongAccum: 11521 case BuiltinType::SatULongAccum: 11522 return Target.getUnsignedLongAccumScale(); 11523 case BuiltinType::ShortFract: 11524 case BuiltinType::SatShortFract: 11525 return Target.getShortFractScale(); 11526 case BuiltinType::Fract: 11527 case BuiltinType::SatFract: 11528 return Target.getFractScale(); 11529 case BuiltinType::LongFract: 11530 case BuiltinType::SatLongFract: 11531 return Target.getLongFractScale(); 11532 case BuiltinType::UShortFract: 11533 case BuiltinType::SatUShortFract: 11534 return Target.getUnsignedShortFractScale(); 11535 case BuiltinType::UFract: 11536 case BuiltinType::SatUFract: 11537 return Target.getUnsignedFractScale(); 11538 case BuiltinType::ULongFract: 11539 case BuiltinType::SatULongFract: 11540 return Target.getUnsignedLongFractScale(); 11541 } 11542 } 11543 11544 unsigned char ASTContext::getFixedPointIBits(QualType Ty) const { 11545 assert(Ty->isFixedPointType()); 11546 11547 const TargetInfo &Target = getTargetInfo(); 11548 switch (Ty->castAs<BuiltinType>()->getKind()) { 11549 default: 11550 llvm_unreachable("Not a fixed point type!"); 11551 case BuiltinType::ShortAccum: 11552 case BuiltinType::SatShortAccum: 11553 return Target.getShortAccumIBits(); 11554 case BuiltinType::Accum: 11555 case BuiltinType::SatAccum: 11556 return Target.getAccumIBits(); 11557 case BuiltinType::LongAccum: 11558 case BuiltinType::SatLongAccum: 11559 return Target.getLongAccumIBits(); 11560 case BuiltinType::UShortAccum: 11561 case BuiltinType::SatUShortAccum: 11562 return Target.getUnsignedShortAccumIBits(); 11563 case BuiltinType::UAccum: 11564 case BuiltinType::SatUAccum: 11565 return Target.getUnsignedAccumIBits(); 11566 case BuiltinType::ULongAccum: 11567 case BuiltinType::SatULongAccum: 11568 return Target.getUnsignedLongAccumIBits(); 11569 case BuiltinType::ShortFract: 11570 case BuiltinType::SatShortFract: 11571 case BuiltinType::Fract: 11572 case BuiltinType::SatFract: 11573 case BuiltinType::LongFract: 11574 case BuiltinType::SatLongFract: 11575 case BuiltinType::UShortFract: 11576 case BuiltinType::SatUShortFract: 11577 case BuiltinType::UFract: 11578 case BuiltinType::SatUFract: 11579 case BuiltinType::ULongFract: 11580 case BuiltinType::SatULongFract: 11581 return 0; 11582 } 11583 } 11584 11585 llvm::FixedPointSemantics 11586 ASTContext::getFixedPointSemantics(QualType Ty) const { 11587 assert((Ty->isFixedPointType() || Ty->isIntegerType()) && 11588 "Can only get the fixed point semantics for a " 11589 "fixed point or integer type."); 11590 if (Ty->isIntegerType()) 11591 return llvm::FixedPointSemantics::GetIntegerSemantics( 11592 getIntWidth(Ty), Ty->isSignedIntegerType()); 11593 11594 bool isSigned = Ty->isSignedFixedPointType(); 11595 return llvm::FixedPointSemantics( 11596 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned, 11597 Ty->isSaturatedFixedPointType(), 11598 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding()); 11599 } 11600 11601 llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const { 11602 assert(Ty->isFixedPointType()); 11603 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty)); 11604 } 11605 11606 llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const { 11607 assert(Ty->isFixedPointType()); 11608 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty)); 11609 } 11610 11611 QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const { 11612 assert(Ty->isUnsignedFixedPointType() && 11613 "Expected unsigned fixed point type"); 11614 11615 switch (Ty->castAs<BuiltinType>()->getKind()) { 11616 case BuiltinType::UShortAccum: 11617 return ShortAccumTy; 11618 case BuiltinType::UAccum: 11619 return AccumTy; 11620 case BuiltinType::ULongAccum: 11621 return LongAccumTy; 11622 case BuiltinType::SatUShortAccum: 11623 return SatShortAccumTy; 11624 case BuiltinType::SatUAccum: 11625 return SatAccumTy; 11626 case BuiltinType::SatULongAccum: 11627 return SatLongAccumTy; 11628 case BuiltinType::UShortFract: 11629 return ShortFractTy; 11630 case BuiltinType::UFract: 11631 return FractTy; 11632 case BuiltinType::ULongFract: 11633 return LongFractTy; 11634 case BuiltinType::SatUShortFract: 11635 return SatShortFractTy; 11636 case BuiltinType::SatUFract: 11637 return SatFractTy; 11638 case BuiltinType::SatULongFract: 11639 return SatLongFractTy; 11640 default: 11641 llvm_unreachable("Unexpected unsigned fixed point type"); 11642 } 11643 } 11644 11645 ParsedTargetAttr 11646 ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const { 11647 assert(TD != nullptr); 11648 ParsedTargetAttr ParsedAttr = TD->parse(); 11649 11650 ParsedAttr.Features.erase( 11651 llvm::remove_if(ParsedAttr.Features, 11652 [&](const std::string &Feat) { 11653 return !Target->isValidFeatureName( 11654 StringRef{Feat}.substr(1)); 11655 }), 11656 ParsedAttr.Features.end()); 11657 return ParsedAttr; 11658 } 11659 11660 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 11661 const FunctionDecl *FD) const { 11662 if (FD) 11663 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD)); 11664 else 11665 Target->initFeatureMap(FeatureMap, getDiagnostics(), 11666 Target->getTargetOpts().CPU, 11667 Target->getTargetOpts().Features); 11668 } 11669 11670 // Fills in the supplied string map with the set of target features for the 11671 // passed in function. 11672 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 11673 GlobalDecl GD) const { 11674 StringRef TargetCPU = Target->getTargetOpts().CPU; 11675 const FunctionDecl *FD = GD.getDecl()->getAsFunction(); 11676 if (const auto *TD = FD->getAttr<TargetAttr>()) { 11677 ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD); 11678 11679 // Make a copy of the features as passed on the command line into the 11680 // beginning of the additional features from the function to override. 11681 ParsedAttr.Features.insert( 11682 ParsedAttr.Features.begin(), 11683 Target->getTargetOpts().FeaturesAsWritten.begin(), 11684 Target->getTargetOpts().FeaturesAsWritten.end()); 11685 11686 if (ParsedAttr.Architecture != "" && 11687 Target->isValidCPUName(ParsedAttr.Architecture)) 11688 TargetCPU = ParsedAttr.Architecture; 11689 11690 // Now populate the feature map, first with the TargetCPU which is either 11691 // the default or a new one from the target attribute string. Then we'll use 11692 // the passed in features (FeaturesAsWritten) along with the new ones from 11693 // the attribute. 11694 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, 11695 ParsedAttr.Features); 11696 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) { 11697 llvm::SmallVector<StringRef, 32> FeaturesTmp; 11698 Target->getCPUSpecificCPUDispatchFeatures( 11699 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp); 11700 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end()); 11701 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features); 11702 } else { 11703 FeatureMap = Target->getTargetOpts().FeatureMap; 11704 } 11705 } 11706 11707 OMPTraitInfo &ASTContext::getNewOMPTraitInfo() { 11708 OMPTraitInfoVector.emplace_back(new OMPTraitInfo()); 11709 return *OMPTraitInfoVector.back(); 11710 } 11711 11712 const StreamingDiagnostic &clang:: 11713 operator<<(const StreamingDiagnostic &DB, 11714 const ASTContext::SectionInfo &Section) { 11715 if (Section.Decl) 11716 return DB << Section.Decl; 11717 return DB << "a prior #pragma section"; 11718 } 11719 11720 bool ASTContext::mayExternalizeStaticVar(const Decl *D) const { 11721 bool IsStaticVar = 11722 isa<VarDecl>(D) && cast<VarDecl>(D)->getStorageClass() == SC_Static; 11723 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() && 11724 !D->getAttr<CUDADeviceAttr>()->isImplicit()) || 11725 (D->hasAttr<CUDAConstantAttr>() && 11726 !D->getAttr<CUDAConstantAttr>()->isImplicit()); 11727 // CUDA/HIP: static managed variables need to be externalized since it is 11728 // a declaration in IR, therefore cannot have internal linkage. 11729 return IsStaticVar && 11730 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar); 11731 } 11732 11733 bool ASTContext::shouldExternalizeStaticVar(const Decl *D) const { 11734 return mayExternalizeStaticVar(D) && 11735 (D->hasAttr<HIPManagedAttr>() || 11736 CUDADeviceVarODRUsedByHost.count(cast<VarDecl>(D))); 11737 } 11738 11739 StringRef ASTContext::getCUIDHash() const { 11740 if (!CUIDHash.empty()) 11741 return CUIDHash; 11742 if (LangOpts.CUID.empty()) 11743 return StringRef(); 11744 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true); 11745 return CUIDHash; 11746 } 11747 11748 // Get the closest named parent, so we can order the sycl naming decls somewhere 11749 // that mangling is meaningful. 11750 static const DeclContext *GetNamedParent(const CXXRecordDecl *RD) { 11751 const DeclContext *DC = RD->getDeclContext(); 11752 11753 while (!isa<NamedDecl, TranslationUnitDecl>(DC)) 11754 DC = DC->getParent(); 11755 return DC; 11756 } 11757 11758 void ASTContext::AddSYCLKernelNamingDecl(const CXXRecordDecl *RD) { 11759 assert(getLangOpts().isSYCL() && "Only valid for SYCL programs"); 11760 RD = RD->getCanonicalDecl(); 11761 const DeclContext *DC = GetNamedParent(RD); 11762 11763 assert(RD->getLocation().isValid() && 11764 "Invalid location on kernel naming decl"); 11765 11766 (void)SYCLKernelNamingTypes[DC].insert(RD); 11767 } 11768 11769 bool ASTContext::IsSYCLKernelNamingDecl(const NamedDecl *ND) const { 11770 assert(getLangOpts().isSYCL() && "Only valid for SYCL programs"); 11771 const auto *RD = dyn_cast<CXXRecordDecl>(ND); 11772 if (!RD) 11773 return false; 11774 RD = RD->getCanonicalDecl(); 11775 const DeclContext *DC = GetNamedParent(RD); 11776 11777 auto Itr = SYCLKernelNamingTypes.find(DC); 11778 11779 if (Itr == SYCLKernelNamingTypes.end()) 11780 return false; 11781 11782 return Itr->getSecond().count(RD); 11783 } 11784 11785 // Filters the Decls list to those that share the lambda mangling with the 11786 // passed RD. 11787 void ASTContext::FilterSYCLKernelNamingDecls( 11788 const CXXRecordDecl *RD, 11789 llvm::SmallVectorImpl<const CXXRecordDecl *> &Decls) { 11790 11791 if (!SYCLKernelFilterContext) 11792 SYCLKernelFilterContext.reset( 11793 ItaniumMangleContext::create(*this, getDiagnostics())); 11794 11795 llvm::SmallString<128> LambdaSig; 11796 llvm::raw_svector_ostream Out(LambdaSig); 11797 SYCLKernelFilterContext->mangleLambdaSig(RD, Out); 11798 11799 llvm::erase_if(Decls, [this, &LambdaSig](const CXXRecordDecl *LocalRD) { 11800 llvm::SmallString<128> LocalLambdaSig; 11801 llvm::raw_svector_ostream LocalOut(LocalLambdaSig); 11802 SYCLKernelFilterContext->mangleLambdaSig(LocalRD, LocalOut); 11803 return LambdaSig != LocalLambdaSig; 11804 }); 11805 } 11806 11807 unsigned ASTContext::GetSYCLKernelNamingIndex(const NamedDecl *ND) { 11808 assert(getLangOpts().isSYCL() && "Only valid for SYCL programs"); 11809 assert(IsSYCLKernelNamingDecl(ND) && 11810 "Lambda not involved in mangling asked for a naming index?"); 11811 11812 const CXXRecordDecl *RD = cast<CXXRecordDecl>(ND)->getCanonicalDecl(); 11813 const DeclContext *DC = GetNamedParent(RD); 11814 11815 auto Itr = SYCLKernelNamingTypes.find(DC); 11816 assert(Itr != SYCLKernelNamingTypes.end() && "Not a valid DeclContext?"); 11817 11818 const llvm::SmallPtrSet<const CXXRecordDecl *, 4> &Set = Itr->getSecond(); 11819 11820 llvm::SmallVector<const CXXRecordDecl *> Decls{Set.begin(), Set.end()}; 11821 11822 FilterSYCLKernelNamingDecls(RD, Decls); 11823 11824 llvm::sort(Decls, [](const CXXRecordDecl *LHS, const CXXRecordDecl *RHS) { 11825 return LHS->getLambdaManglingNumber() < RHS->getLambdaManglingNumber(); 11826 }); 11827 11828 return llvm::find(Decls, RD) - Decls.begin(); 11829 } 11830