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/ObjCRuntime.h" 60 #include "clang/Basic/SanitizerBlacklist.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/MathExtras.h" 88 #include "llvm/Support/raw_ostream.h" 89 #include <algorithm> 90 #include <cassert> 91 #include <cstddef> 92 #include <cstdint> 93 #include <cstdlib> 94 #include <map> 95 #include <memory> 96 #include <string> 97 #include <tuple> 98 #include <utility> 99 100 using namespace clang; 101 102 enum FloatingRank { 103 BFloat16Rank, Float16Rank, HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank 104 }; 105 106 /// \returns location that is relevant when searching for Doc comments related 107 /// to \p D. 108 static SourceLocation getDeclLocForCommentSearch(const Decl *D, 109 SourceManager &SourceMgr) { 110 assert(D); 111 112 // User can not attach documentation to implicit declarations. 113 if (D->isImplicit()) 114 return {}; 115 116 // User can not attach documentation to implicit instantiations. 117 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 118 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 119 return {}; 120 } 121 122 if (const auto *VD = dyn_cast<VarDecl>(D)) { 123 if (VD->isStaticDataMember() && 124 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 125 return {}; 126 } 127 128 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) { 129 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 130 return {}; 131 } 132 133 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) { 134 TemplateSpecializationKind TSK = CTSD->getSpecializationKind(); 135 if (TSK == TSK_ImplicitInstantiation || 136 TSK == TSK_Undeclared) 137 return {}; 138 } 139 140 if (const auto *ED = dyn_cast<EnumDecl>(D)) { 141 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 142 return {}; 143 } 144 if (const auto *TD = dyn_cast<TagDecl>(D)) { 145 // When tag declaration (but not definition!) is part of the 146 // decl-specifier-seq of some other declaration, it doesn't get comment 147 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition()) 148 return {}; 149 } 150 // TODO: handle comments for function parameters properly. 151 if (isa<ParmVarDecl>(D)) 152 return {}; 153 154 // TODO: we could look up template parameter documentation in the template 155 // documentation. 156 if (isa<TemplateTypeParmDecl>(D) || 157 isa<NonTypeTemplateParmDecl>(D) || 158 isa<TemplateTemplateParmDecl>(D)) 159 return {}; 160 161 // Find declaration location. 162 // For Objective-C declarations we generally don't expect to have multiple 163 // declarators, thus use declaration starting location as the "declaration 164 // location". 165 // For all other declarations multiple declarators are used quite frequently, 166 // so we use the location of the identifier as the "declaration location". 167 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) || 168 isa<ObjCPropertyDecl>(D) || 169 isa<RedeclarableTemplateDecl>(D) || 170 isa<ClassTemplateSpecializationDecl>(D) || 171 // Allow association with Y across {} in `typedef struct X {} Y`. 172 isa<TypedefDecl>(D)) 173 return D->getBeginLoc(); 174 else { 175 const SourceLocation DeclLoc = D->getLocation(); 176 if (DeclLoc.isMacroID()) { 177 if (isa<TypedefDecl>(D)) { 178 // If location of the typedef name is in a macro, it is because being 179 // declared via a macro. Try using declaration's starting location as 180 // the "declaration location". 181 return D->getBeginLoc(); 182 } else if (const auto *TD = dyn_cast<TagDecl>(D)) { 183 // If location of the tag decl is inside a macro, but the spelling of 184 // the tag name comes from a macro argument, it looks like a special 185 // macro like NS_ENUM is being used to define the tag decl. In that 186 // case, adjust the source location to the expansion loc so that we can 187 // attach the comment to the tag decl. 188 if (SourceMgr.isMacroArgExpansion(DeclLoc) && 189 TD->isCompleteDefinition()) 190 return SourceMgr.getExpansionLoc(DeclLoc); 191 } 192 } 193 return DeclLoc; 194 } 195 196 return {}; 197 } 198 199 RawComment *ASTContext::getRawCommentForDeclNoCacheImpl( 200 const Decl *D, const SourceLocation RepresentativeLocForDecl, 201 const std::map<unsigned, RawComment *> &CommentsInTheFile) const { 202 // If the declaration doesn't map directly to a location in a file, we 203 // can't find the comment. 204 if (RepresentativeLocForDecl.isInvalid() || 205 !RepresentativeLocForDecl.isFileID()) 206 return nullptr; 207 208 // If there are no comments anywhere, we won't find anything. 209 if (CommentsInTheFile.empty()) 210 return nullptr; 211 212 // Decompose the location for the declaration and find the beginning of the 213 // file buffer. 214 const std::pair<FileID, unsigned> DeclLocDecomp = 215 SourceMgr.getDecomposedLoc(RepresentativeLocForDecl); 216 217 // Slow path. 218 auto OffsetCommentBehindDecl = 219 CommentsInTheFile.lower_bound(DeclLocDecomp.second); 220 221 // First check whether we have a trailing comment. 222 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) { 223 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second; 224 if ((CommentBehindDecl->isDocumentation() || 225 LangOpts.CommentOpts.ParseAllComments) && 226 CommentBehindDecl->isTrailingComment() && 227 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) || 228 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) { 229 230 // Check that Doxygen trailing comment comes after the declaration, starts 231 // on the same line and in the same file as the declaration. 232 if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) == 233 Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first, 234 OffsetCommentBehindDecl->first)) { 235 return CommentBehindDecl; 236 } 237 } 238 } 239 240 // The comment just after the declaration was not a trailing comment. 241 // Let's look at the previous comment. 242 if (OffsetCommentBehindDecl == CommentsInTheFile.begin()) 243 return nullptr; 244 245 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl; 246 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second; 247 248 // Check that we actually have a non-member Doxygen comment. 249 if (!(CommentBeforeDecl->isDocumentation() || 250 LangOpts.CommentOpts.ParseAllComments) || 251 CommentBeforeDecl->isTrailingComment()) 252 return nullptr; 253 254 // Decompose the end of the comment. 255 const unsigned CommentEndOffset = 256 Comments.getCommentEndOffset(CommentBeforeDecl); 257 258 // Get the corresponding buffer. 259 bool Invalid = false; 260 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first, 261 &Invalid).data(); 262 if (Invalid) 263 return nullptr; 264 265 // Extract text between the comment and declaration. 266 StringRef Text(Buffer + CommentEndOffset, 267 DeclLocDecomp.second - CommentEndOffset); 268 269 // There should be no other declarations or preprocessor directives between 270 // comment and declaration. 271 if (Text.find_first_of(";{}#@") != StringRef::npos) 272 return nullptr; 273 274 return CommentBeforeDecl; 275 } 276 277 RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const { 278 const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr); 279 280 // If the declaration doesn't map directly to a location in a file, we 281 // can't find the comment. 282 if (DeclLoc.isInvalid() || !DeclLoc.isFileID()) 283 return nullptr; 284 285 if (ExternalSource && !CommentsLoaded) { 286 ExternalSource->ReadComments(); 287 CommentsLoaded = true; 288 } 289 290 if (Comments.empty()) 291 return nullptr; 292 293 const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first; 294 const auto CommentsInThisFile = Comments.getCommentsInFile(File); 295 if (!CommentsInThisFile || CommentsInThisFile->empty()) 296 return nullptr; 297 298 return getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile); 299 } 300 301 void ASTContext::addComment(const RawComment &RC) { 302 assert(LangOpts.RetainCommentsFromSystemHeaders || 303 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin())); 304 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc); 305 } 306 307 /// If we have a 'templated' declaration for a template, adjust 'D' to 308 /// refer to the actual template. 309 /// If we have an implicit instantiation, adjust 'D' to refer to template. 310 static const Decl &adjustDeclToTemplate(const Decl &D) { 311 if (const auto *FD = dyn_cast<FunctionDecl>(&D)) { 312 // Is this function declaration part of a function template? 313 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 314 return *FTD; 315 316 // Nothing to do if function is not an implicit instantiation. 317 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) 318 return D; 319 320 // Function is an implicit instantiation of a function template? 321 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate()) 322 return *FTD; 323 324 // Function is instantiated from a member definition of a class template? 325 if (const FunctionDecl *MemberDecl = 326 FD->getInstantiatedFromMemberFunction()) 327 return *MemberDecl; 328 329 return D; 330 } 331 if (const auto *VD = dyn_cast<VarDecl>(&D)) { 332 // Static data member is instantiated from a member definition of a class 333 // template? 334 if (VD->isStaticDataMember()) 335 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember()) 336 return *MemberDecl; 337 338 return D; 339 } 340 if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) { 341 // Is this class declaration part of a class template? 342 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate()) 343 return *CTD; 344 345 // Class is an implicit instantiation of a class template or partial 346 // specialization? 347 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) { 348 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation) 349 return D; 350 llvm::PointerUnion<ClassTemplateDecl *, 351 ClassTemplatePartialSpecializationDecl *> 352 PU = CTSD->getSpecializedTemplateOrPartial(); 353 return PU.is<ClassTemplateDecl *>() 354 ? *static_cast<const Decl *>(PU.get<ClassTemplateDecl *>()) 355 : *static_cast<const Decl *>( 356 PU.get<ClassTemplatePartialSpecializationDecl *>()); 357 } 358 359 // Class is instantiated from a member definition of a class template? 360 if (const MemberSpecializationInfo *Info = 361 CRD->getMemberSpecializationInfo()) 362 return *Info->getInstantiatedFrom(); 363 364 return D; 365 } 366 if (const auto *ED = dyn_cast<EnumDecl>(&D)) { 367 // Enum is instantiated from a member definition of a class template? 368 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum()) 369 return *MemberDecl; 370 371 return D; 372 } 373 // FIXME: Adjust alias templates? 374 return D; 375 } 376 377 const RawComment *ASTContext::getRawCommentForAnyRedecl( 378 const Decl *D, 379 const Decl **OriginalDecl) const { 380 if (!D) { 381 if (OriginalDecl) 382 OriginalDecl = nullptr; 383 return nullptr; 384 } 385 386 D = &adjustDeclToTemplate(*D); 387 388 // Any comment directly attached to D? 389 { 390 auto DeclComment = DeclRawComments.find(D); 391 if (DeclComment != DeclRawComments.end()) { 392 if (OriginalDecl) 393 *OriginalDecl = D; 394 return DeclComment->second; 395 } 396 } 397 398 // Any comment attached to any redeclaration of D? 399 const Decl *CanonicalD = D->getCanonicalDecl(); 400 if (!CanonicalD) 401 return nullptr; 402 403 { 404 auto RedeclComment = RedeclChainComments.find(CanonicalD); 405 if (RedeclComment != RedeclChainComments.end()) { 406 if (OriginalDecl) 407 *OriginalDecl = RedeclComment->second; 408 auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second); 409 assert(CommentAtRedecl != DeclRawComments.end() && 410 "This decl is supposed to have comment attached."); 411 return CommentAtRedecl->second; 412 } 413 } 414 415 // Any redeclarations of D that we haven't checked for comments yet? 416 // We can't use DenseMap::iterator directly since it'd get invalid. 417 auto LastCheckedRedecl = [this, CanonicalD]() -> const Decl * { 418 auto LookupRes = CommentlessRedeclChains.find(CanonicalD); 419 if (LookupRes != CommentlessRedeclChains.end()) 420 return LookupRes->second; 421 return nullptr; 422 }(); 423 424 for (const auto Redecl : D->redecls()) { 425 assert(Redecl); 426 // Skip all redeclarations that have been checked previously. 427 if (LastCheckedRedecl) { 428 if (LastCheckedRedecl == Redecl) { 429 LastCheckedRedecl = nullptr; 430 } 431 continue; 432 } 433 const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl); 434 if (RedeclComment) { 435 cacheRawCommentForDecl(*Redecl, *RedeclComment); 436 if (OriginalDecl) 437 *OriginalDecl = Redecl; 438 return RedeclComment; 439 } 440 CommentlessRedeclChains[CanonicalD] = Redecl; 441 } 442 443 if (OriginalDecl) 444 *OriginalDecl = nullptr; 445 return nullptr; 446 } 447 448 void ASTContext::cacheRawCommentForDecl(const Decl &OriginalD, 449 const RawComment &Comment) const { 450 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments); 451 DeclRawComments.try_emplace(&OriginalD, &Comment); 452 const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl(); 453 RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD); 454 CommentlessRedeclChains.erase(CanonicalDecl); 455 } 456 457 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod, 458 SmallVectorImpl<const NamedDecl *> &Redeclared) { 459 const DeclContext *DC = ObjCMethod->getDeclContext(); 460 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) { 461 const ObjCInterfaceDecl *ID = IMD->getClassInterface(); 462 if (!ID) 463 return; 464 // Add redeclared method here. 465 for (const auto *Ext : ID->known_extensions()) { 466 if (ObjCMethodDecl *RedeclaredMethod = 467 Ext->getMethod(ObjCMethod->getSelector(), 468 ObjCMethod->isInstanceMethod())) 469 Redeclared.push_back(RedeclaredMethod); 470 } 471 } 472 } 473 474 void ASTContext::attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls, 475 const Preprocessor *PP) { 476 if (Comments.empty() || Decls.empty()) 477 return; 478 479 FileID File; 480 for (Decl *D : Decls) { 481 SourceLocation Loc = D->getLocation(); 482 if (Loc.isValid()) { 483 // See if there are any new comments that are not attached to a decl. 484 // The location doesn't have to be precise - we care only about the file. 485 File = SourceMgr.getDecomposedLoc(Loc).first; 486 break; 487 } 488 } 489 490 if (File.isInvalid()) 491 return; 492 493 auto CommentsInThisFile = Comments.getCommentsInFile(File); 494 if (!CommentsInThisFile || CommentsInThisFile->empty() || 495 CommentsInThisFile->rbegin()->second->isAttached()) 496 return; 497 498 // There is at least one comment not attached to a decl. 499 // Maybe it should be attached to one of Decls? 500 // 501 // Note that this way we pick up not only comments that precede the 502 // declaration, but also comments that *follow* the declaration -- thanks to 503 // the lookahead in the lexer: we've consumed the semicolon and looked 504 // ahead through comments. 505 506 for (const Decl *D : Decls) { 507 assert(D); 508 if (D->isInvalidDecl()) 509 continue; 510 511 D = &adjustDeclToTemplate(*D); 512 513 const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr); 514 515 if (DeclLoc.isInvalid() || !DeclLoc.isFileID()) 516 continue; 517 518 if (DeclRawComments.count(D) > 0) 519 continue; 520 521 if (RawComment *const DocComment = 522 getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile)) { 523 cacheRawCommentForDecl(*D, *DocComment); 524 comments::FullComment *FC = DocComment->parse(*this, PP, D); 525 ParsedComments[D->getCanonicalDecl()] = FC; 526 } 527 } 528 } 529 530 comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC, 531 const Decl *D) const { 532 auto *ThisDeclInfo = new (*this) comments::DeclInfo; 533 ThisDeclInfo->CommentDecl = D; 534 ThisDeclInfo->IsFilled = false; 535 ThisDeclInfo->fill(); 536 ThisDeclInfo->CommentDecl = FC->getDecl(); 537 if (!ThisDeclInfo->TemplateParameters) 538 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters; 539 comments::FullComment *CFC = 540 new (*this) comments::FullComment(FC->getBlocks(), 541 ThisDeclInfo); 542 return CFC; 543 } 544 545 comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const { 546 const RawComment *RC = getRawCommentForDeclNoCache(D); 547 return RC ? RC->parse(*this, nullptr, D) : nullptr; 548 } 549 550 comments::FullComment *ASTContext::getCommentForDecl( 551 const Decl *D, 552 const Preprocessor *PP) const { 553 if (!D || D->isInvalidDecl()) 554 return nullptr; 555 D = &adjustDeclToTemplate(*D); 556 557 const Decl *Canonical = D->getCanonicalDecl(); 558 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos = 559 ParsedComments.find(Canonical); 560 561 if (Pos != ParsedComments.end()) { 562 if (Canonical != D) { 563 comments::FullComment *FC = Pos->second; 564 comments::FullComment *CFC = cloneFullComment(FC, D); 565 return CFC; 566 } 567 return Pos->second; 568 } 569 570 const Decl *OriginalDecl = nullptr; 571 572 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl); 573 if (!RC) { 574 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) { 575 SmallVector<const NamedDecl*, 8> Overridden; 576 const auto *OMD = dyn_cast<ObjCMethodDecl>(D); 577 if (OMD && OMD->isPropertyAccessor()) 578 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl()) 579 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP)) 580 return cloneFullComment(FC, D); 581 if (OMD) 582 addRedeclaredMethods(OMD, Overridden); 583 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden); 584 for (unsigned i = 0, e = Overridden.size(); i < e; i++) 585 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP)) 586 return cloneFullComment(FC, D); 587 } 588 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) { 589 // Attach any tag type's documentation to its typedef if latter 590 // does not have one of its own. 591 QualType QT = TD->getUnderlyingType(); 592 if (const auto *TT = QT->getAs<TagType>()) 593 if (const Decl *TD = TT->getDecl()) 594 if (comments::FullComment *FC = getCommentForDecl(TD, PP)) 595 return cloneFullComment(FC, D); 596 } 597 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) { 598 while (IC->getSuperClass()) { 599 IC = IC->getSuperClass(); 600 if (comments::FullComment *FC = getCommentForDecl(IC, PP)) 601 return cloneFullComment(FC, D); 602 } 603 } 604 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) { 605 if (const ObjCInterfaceDecl *IC = CD->getClassInterface()) 606 if (comments::FullComment *FC = getCommentForDecl(IC, PP)) 607 return cloneFullComment(FC, D); 608 } 609 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) { 610 if (!(RD = RD->getDefinition())) 611 return nullptr; 612 // Check non-virtual bases. 613 for (const auto &I : RD->bases()) { 614 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public)) 615 continue; 616 QualType Ty = I.getType(); 617 if (Ty.isNull()) 618 continue; 619 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) { 620 if (!(NonVirtualBase= NonVirtualBase->getDefinition())) 621 continue; 622 623 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP)) 624 return cloneFullComment(FC, D); 625 } 626 } 627 // Check virtual bases. 628 for (const auto &I : RD->vbases()) { 629 if (I.getAccessSpecifier() != AS_public) 630 continue; 631 QualType Ty = I.getType(); 632 if (Ty.isNull()) 633 continue; 634 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) { 635 if (!(VirtualBase= VirtualBase->getDefinition())) 636 continue; 637 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP)) 638 return cloneFullComment(FC, D); 639 } 640 } 641 } 642 return nullptr; 643 } 644 645 // If the RawComment was attached to other redeclaration of this Decl, we 646 // should parse the comment in context of that other Decl. This is important 647 // because comments can contain references to parameter names which can be 648 // different across redeclarations. 649 if (D != OriginalDecl && OriginalDecl) 650 return getCommentForDecl(OriginalDecl, PP); 651 652 comments::FullComment *FC = RC->parse(*this, PP, D); 653 ParsedComments[Canonical] = FC; 654 return FC; 655 } 656 657 void 658 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID, 659 const ASTContext &C, 660 TemplateTemplateParmDecl *Parm) { 661 ID.AddInteger(Parm->getDepth()); 662 ID.AddInteger(Parm->getPosition()); 663 ID.AddBoolean(Parm->isParameterPack()); 664 665 TemplateParameterList *Params = Parm->getTemplateParameters(); 666 ID.AddInteger(Params->size()); 667 for (TemplateParameterList::const_iterator P = Params->begin(), 668 PEnd = Params->end(); 669 P != PEnd; ++P) { 670 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { 671 ID.AddInteger(0); 672 ID.AddBoolean(TTP->isParameterPack()); 673 const TypeConstraint *TC = TTP->getTypeConstraint(); 674 ID.AddBoolean(TC != nullptr); 675 if (TC) 676 TC->getImmediatelyDeclaredConstraint()->Profile(ID, C, 677 /*Canonical=*/true); 678 if (TTP->isExpandedParameterPack()) { 679 ID.AddBoolean(true); 680 ID.AddInteger(TTP->getNumExpansionParameters()); 681 } else 682 ID.AddBoolean(false); 683 continue; 684 } 685 686 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 687 ID.AddInteger(1); 688 ID.AddBoolean(NTTP->isParameterPack()); 689 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr()); 690 if (NTTP->isExpandedParameterPack()) { 691 ID.AddBoolean(true); 692 ID.AddInteger(NTTP->getNumExpansionTypes()); 693 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { 694 QualType T = NTTP->getExpansionType(I); 695 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr()); 696 } 697 } else 698 ID.AddBoolean(false); 699 continue; 700 } 701 702 auto *TTP = cast<TemplateTemplateParmDecl>(*P); 703 ID.AddInteger(2); 704 Profile(ID, C, TTP); 705 } 706 Expr *RequiresClause = Parm->getTemplateParameters()->getRequiresClause(); 707 ID.AddBoolean(RequiresClause != nullptr); 708 if (RequiresClause) 709 RequiresClause->Profile(ID, C, /*Canonical=*/true); 710 } 711 712 static Expr * 713 canonicalizeImmediatelyDeclaredConstraint(const ASTContext &C, Expr *IDC, 714 QualType ConstrainedType) { 715 // This is a bit ugly - we need to form a new immediately-declared 716 // constraint that references the new parameter; this would ideally 717 // require semantic analysis (e.g. template<C T> struct S {}; - the 718 // converted arguments of C<T> could be an argument pack if C is 719 // declared as template<typename... T> concept C = ...). 720 // We don't have semantic analysis here so we dig deep into the 721 // ready-made constraint expr and change the thing manually. 722 ConceptSpecializationExpr *CSE; 723 if (const auto *Fold = dyn_cast<CXXFoldExpr>(IDC)) 724 CSE = cast<ConceptSpecializationExpr>(Fold->getLHS()); 725 else 726 CSE = cast<ConceptSpecializationExpr>(IDC); 727 ArrayRef<TemplateArgument> OldConverted = CSE->getTemplateArguments(); 728 SmallVector<TemplateArgument, 3> NewConverted; 729 NewConverted.reserve(OldConverted.size()); 730 if (OldConverted.front().getKind() == TemplateArgument::Pack) { 731 // The case: 732 // template<typename... T> concept C = true; 733 // template<C<int> T> struct S; -> constraint is C<{T, int}> 734 NewConverted.push_back(ConstrainedType); 735 for (auto &Arg : OldConverted.front().pack_elements().drop_front(1)) 736 NewConverted.push_back(Arg); 737 TemplateArgument NewPack(NewConverted); 738 739 NewConverted.clear(); 740 NewConverted.push_back(NewPack); 741 assert(OldConverted.size() == 1 && 742 "Template parameter pack should be the last parameter"); 743 } else { 744 assert(OldConverted.front().getKind() == TemplateArgument::Type && 745 "Unexpected first argument kind for immediately-declared " 746 "constraint"); 747 NewConverted.push_back(ConstrainedType); 748 for (auto &Arg : OldConverted.drop_front(1)) 749 NewConverted.push_back(Arg); 750 } 751 Expr *NewIDC = ConceptSpecializationExpr::Create( 752 C, CSE->getNamedConcept(), NewConverted, nullptr, 753 CSE->isInstantiationDependent(), CSE->containsUnexpandedParameterPack()); 754 755 if (auto *OrigFold = dyn_cast<CXXFoldExpr>(IDC)) 756 NewIDC = new (C) CXXFoldExpr( 757 OrigFold->getType(), /*Callee*/nullptr, SourceLocation(), NewIDC, 758 BinaryOperatorKind::BO_LAnd, SourceLocation(), /*RHS=*/nullptr, 759 SourceLocation(), /*NumExpansions=*/None); 760 return NewIDC; 761 } 762 763 TemplateTemplateParmDecl * 764 ASTContext::getCanonicalTemplateTemplateParmDecl( 765 TemplateTemplateParmDecl *TTP) const { 766 // Check if we already have a canonical template template parameter. 767 llvm::FoldingSetNodeID ID; 768 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP); 769 void *InsertPos = nullptr; 770 CanonicalTemplateTemplateParm *Canonical 771 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 772 if (Canonical) 773 return Canonical->getParam(); 774 775 // Build a canonical template parameter list. 776 TemplateParameterList *Params = TTP->getTemplateParameters(); 777 SmallVector<NamedDecl *, 4> CanonParams; 778 CanonParams.reserve(Params->size()); 779 for (TemplateParameterList::const_iterator P = Params->begin(), 780 PEnd = Params->end(); 781 P != PEnd; ++P) { 782 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { 783 TemplateTypeParmDecl *NewTTP = TemplateTypeParmDecl::Create(*this, 784 getTranslationUnitDecl(), SourceLocation(), SourceLocation(), 785 TTP->getDepth(), TTP->getIndex(), nullptr, false, 786 TTP->isParameterPack(), TTP->hasTypeConstraint(), 787 TTP->isExpandedParameterPack() ? 788 llvm::Optional<unsigned>(TTP->getNumExpansionParameters()) : None); 789 if (const auto *TC = TTP->getTypeConstraint()) { 790 QualType ParamAsArgument(NewTTP->getTypeForDecl(), 0); 791 Expr *NewIDC = canonicalizeImmediatelyDeclaredConstraint( 792 *this, TC->getImmediatelyDeclaredConstraint(), 793 ParamAsArgument); 794 TemplateArgumentListInfo CanonArgsAsWritten; 795 if (auto *Args = TC->getTemplateArgsAsWritten()) 796 for (const auto &ArgLoc : Args->arguments()) 797 CanonArgsAsWritten.addArgument( 798 TemplateArgumentLoc(ArgLoc.getArgument(), 799 TemplateArgumentLocInfo())); 800 NewTTP->setTypeConstraint( 801 NestedNameSpecifierLoc(), 802 DeclarationNameInfo(TC->getNamedConcept()->getDeclName(), 803 SourceLocation()), /*FoundDecl=*/nullptr, 804 // Actually canonicalizing a TemplateArgumentLoc is difficult so we 805 // simply omit the ArgsAsWritten 806 TC->getNamedConcept(), /*ArgsAsWritten=*/nullptr, NewIDC); 807 } 808 CanonParams.push_back(NewTTP); 809 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 810 QualType T = getCanonicalType(NTTP->getType()); 811 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); 812 NonTypeTemplateParmDecl *Param; 813 if (NTTP->isExpandedParameterPack()) { 814 SmallVector<QualType, 2> ExpandedTypes; 815 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos; 816 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { 817 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I))); 818 ExpandedTInfos.push_back( 819 getTrivialTypeSourceInfo(ExpandedTypes.back())); 820 } 821 822 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 823 SourceLocation(), 824 SourceLocation(), 825 NTTP->getDepth(), 826 NTTP->getPosition(), nullptr, 827 T, 828 TInfo, 829 ExpandedTypes, 830 ExpandedTInfos); 831 } else { 832 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 833 SourceLocation(), 834 SourceLocation(), 835 NTTP->getDepth(), 836 NTTP->getPosition(), nullptr, 837 T, 838 NTTP->isParameterPack(), 839 TInfo); 840 } 841 if (AutoType *AT = T->getContainedAutoType()) { 842 if (AT->isConstrained()) { 843 Param->setPlaceholderTypeConstraint( 844 canonicalizeImmediatelyDeclaredConstraint( 845 *this, NTTP->getPlaceholderTypeConstraint(), T)); 846 } 847 } 848 CanonParams.push_back(Param); 849 850 } else 851 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl( 852 cast<TemplateTemplateParmDecl>(*P))); 853 } 854 855 Expr *CanonRequiresClause = nullptr; 856 if (Expr *RequiresClause = TTP->getTemplateParameters()->getRequiresClause()) 857 CanonRequiresClause = RequiresClause; 858 859 TemplateTemplateParmDecl *CanonTTP 860 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 861 SourceLocation(), TTP->getDepth(), 862 TTP->getPosition(), 863 TTP->isParameterPack(), 864 nullptr, 865 TemplateParameterList::Create(*this, SourceLocation(), 866 SourceLocation(), 867 CanonParams, 868 SourceLocation(), 869 CanonRequiresClause)); 870 871 // Get the new insert position for the node we care about. 872 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 873 assert(!Canonical && "Shouldn't be in the map!"); 874 (void)Canonical; 875 876 // Create the canonical template template parameter entry. 877 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP); 878 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos); 879 return CanonTTP; 880 } 881 882 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) { 883 if (!LangOpts.CPlusPlus) return nullptr; 884 885 switch (T.getCXXABI().getKind()) { 886 case TargetCXXABI::AppleARM64: 887 case TargetCXXABI::Fuchsia: 888 case TargetCXXABI::GenericARM: // Same as Itanium at this level 889 case TargetCXXABI::iOS: 890 case TargetCXXABI::WatchOS: 891 case TargetCXXABI::GenericAArch64: 892 case TargetCXXABI::GenericMIPS: 893 case TargetCXXABI::GenericItanium: 894 case TargetCXXABI::WebAssembly: 895 case TargetCXXABI::XL: 896 return CreateItaniumCXXABI(*this); 897 case TargetCXXABI::Microsoft: 898 return CreateMicrosoftCXXABI(*this); 899 } 900 llvm_unreachable("Invalid CXXABI type!"); 901 } 902 903 interp::Context &ASTContext::getInterpContext() { 904 if (!InterpContext) { 905 InterpContext.reset(new interp::Context(*this)); 906 } 907 return *InterpContext.get(); 908 } 909 910 ParentMapContext &ASTContext::getParentMapContext() { 911 if (!ParentMapCtx) 912 ParentMapCtx.reset(new ParentMapContext(*this)); 913 return *ParentMapCtx.get(); 914 } 915 916 static const LangASMap *getAddressSpaceMap(const TargetInfo &T, 917 const LangOptions &LOpts) { 918 if (LOpts.FakeAddressSpaceMap) { 919 // The fake address space map must have a distinct entry for each 920 // language-specific address space. 921 static const unsigned FakeAddrSpaceMap[] = { 922 0, // Default 923 1, // opencl_global 924 3, // opencl_local 925 2, // opencl_constant 926 0, // opencl_private 927 4, // opencl_generic 928 5, // opencl_global_device 929 6, // opencl_global_host 930 7, // cuda_device 931 8, // cuda_constant 932 9, // cuda_shared 933 10, // ptr32_sptr 934 11, // ptr32_uptr 935 12 // ptr64 936 }; 937 return &FakeAddrSpaceMap; 938 } else { 939 return &T.getAddressSpaceMap(); 940 } 941 } 942 943 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI, 944 const LangOptions &LangOpts) { 945 switch (LangOpts.getAddressSpaceMapMangling()) { 946 case LangOptions::ASMM_Target: 947 return TI.useAddressSpaceMapMangling(); 948 case LangOptions::ASMM_On: 949 return true; 950 case LangOptions::ASMM_Off: 951 return false; 952 } 953 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything."); 954 } 955 956 ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM, 957 IdentifierTable &idents, SelectorTable &sels, 958 Builtin::Context &builtins) 959 : ConstantArrayTypes(this_()), FunctionProtoTypes(this_()), 960 TemplateSpecializationTypes(this_()), 961 DependentTemplateSpecializationTypes(this_()), AutoTypes(this_()), 962 SubstTemplateTemplateParmPacks(this_()), 963 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts), 964 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)), 965 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles, 966 LangOpts.XRayNeverInstrumentFiles, 967 LangOpts.XRayAttrListFiles, SM)), 968 PrintingPolicy(LOpts), Idents(idents), Selectors(sels), 969 BuiltinInfo(builtins), DeclarationNames(*this), Comments(SM), 970 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), 971 CompCategories(this_()), LastSDM(nullptr, 0) { 972 TUDecl = TranslationUnitDecl::Create(*this); 973 TraversalScope = {TUDecl}; 974 } 975 976 ASTContext::~ASTContext() { 977 // Release the DenseMaps associated with DeclContext objects. 978 // FIXME: Is this the ideal solution? 979 ReleaseDeclContextMaps(); 980 981 // Call all of the deallocation functions on all of their targets. 982 for (auto &Pair : Deallocations) 983 (Pair.first)(Pair.second); 984 985 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed 986 // because they can contain DenseMaps. 987 for (llvm::DenseMap<const ObjCContainerDecl*, 988 const ASTRecordLayout*>::iterator 989 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) 990 // Increment in loop to prevent using deallocated memory. 991 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second)) 992 R->Destroy(*this); 993 994 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator 995 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) { 996 // Increment in loop to prevent using deallocated memory. 997 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second)) 998 R->Destroy(*this); 999 } 1000 1001 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(), 1002 AEnd = DeclAttrs.end(); 1003 A != AEnd; ++A) 1004 A->second->~AttrVec(); 1005 1006 for (const auto &Value : ModuleInitializers) 1007 Value.second->~PerModuleInitializers(); 1008 } 1009 1010 void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) { 1011 TraversalScope = TopLevelDecls; 1012 getParentMapContext().clear(); 1013 } 1014 1015 void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const { 1016 Deallocations.push_back({Callback, Data}); 1017 } 1018 1019 void 1020 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) { 1021 ExternalSource = std::move(Source); 1022 } 1023 1024 void ASTContext::PrintStats() const { 1025 llvm::errs() << "\n*** AST Context Stats:\n"; 1026 llvm::errs() << " " << Types.size() << " types total.\n"; 1027 1028 unsigned counts[] = { 1029 #define TYPE(Name, Parent) 0, 1030 #define ABSTRACT_TYPE(Name, Parent) 1031 #include "clang/AST/TypeNodes.inc" 1032 0 // Extra 1033 }; 1034 1035 for (unsigned i = 0, e = Types.size(); i != e; ++i) { 1036 Type *T = Types[i]; 1037 counts[(unsigned)T->getTypeClass()]++; 1038 } 1039 1040 unsigned Idx = 0; 1041 unsigned TotalBytes = 0; 1042 #define TYPE(Name, Parent) \ 1043 if (counts[Idx]) \ 1044 llvm::errs() << " " << counts[Idx] << " " << #Name \ 1045 << " types, " << sizeof(Name##Type) << " each " \ 1046 << "(" << counts[Idx] * sizeof(Name##Type) \ 1047 << " bytes)\n"; \ 1048 TotalBytes += counts[Idx] * sizeof(Name##Type); \ 1049 ++Idx; 1050 #define ABSTRACT_TYPE(Name, Parent) 1051 #include "clang/AST/TypeNodes.inc" 1052 1053 llvm::errs() << "Total bytes = " << TotalBytes << "\n"; 1054 1055 // Implicit special member functions. 1056 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/" 1057 << NumImplicitDefaultConstructors 1058 << " implicit default constructors created\n"; 1059 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/" 1060 << NumImplicitCopyConstructors 1061 << " implicit copy constructors created\n"; 1062 if (getLangOpts().CPlusPlus) 1063 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/" 1064 << NumImplicitMoveConstructors 1065 << " implicit move constructors created\n"; 1066 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/" 1067 << NumImplicitCopyAssignmentOperators 1068 << " implicit copy assignment operators created\n"; 1069 if (getLangOpts().CPlusPlus) 1070 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/" 1071 << NumImplicitMoveAssignmentOperators 1072 << " implicit move assignment operators created\n"; 1073 llvm::errs() << NumImplicitDestructorsDeclared << "/" 1074 << NumImplicitDestructors 1075 << " implicit destructors created\n"; 1076 1077 if (ExternalSource) { 1078 llvm::errs() << "\n"; 1079 ExternalSource->PrintStats(); 1080 } 1081 1082 BumpAlloc.PrintStats(); 1083 } 1084 1085 void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M, 1086 bool NotifyListeners) { 1087 if (NotifyListeners) 1088 if (auto *Listener = getASTMutationListener()) 1089 Listener->RedefinedHiddenDefinition(ND, M); 1090 1091 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M); 1092 } 1093 1094 void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) { 1095 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl())); 1096 if (It == MergedDefModules.end()) 1097 return; 1098 1099 auto &Merged = It->second; 1100 llvm::DenseSet<Module*> Found; 1101 for (Module *&M : Merged) 1102 if (!Found.insert(M).second) 1103 M = nullptr; 1104 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end()); 1105 } 1106 1107 ArrayRef<Module *> 1108 ASTContext::getModulesWithMergedDefinition(const NamedDecl *Def) { 1109 auto MergedIt = 1110 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl())); 1111 if (MergedIt == MergedDefModules.end()) 1112 return None; 1113 return MergedIt->second; 1114 } 1115 1116 void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) { 1117 if (LazyInitializers.empty()) 1118 return; 1119 1120 auto *Source = Ctx.getExternalSource(); 1121 assert(Source && "lazy initializers but no external source"); 1122 1123 auto LazyInits = std::move(LazyInitializers); 1124 LazyInitializers.clear(); 1125 1126 for (auto ID : LazyInits) 1127 Initializers.push_back(Source->GetExternalDecl(ID)); 1128 1129 assert(LazyInitializers.empty() && 1130 "GetExternalDecl for lazy module initializer added more inits"); 1131 } 1132 1133 void ASTContext::addModuleInitializer(Module *M, Decl *D) { 1134 // One special case: if we add a module initializer that imports another 1135 // module, and that module's only initializer is an ImportDecl, simplify. 1136 if (const auto *ID = dyn_cast<ImportDecl>(D)) { 1137 auto It = ModuleInitializers.find(ID->getImportedModule()); 1138 1139 // Maybe the ImportDecl does nothing at all. (Common case.) 1140 if (It == ModuleInitializers.end()) 1141 return; 1142 1143 // Maybe the ImportDecl only imports another ImportDecl. 1144 auto &Imported = *It->second; 1145 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) { 1146 Imported.resolve(*this); 1147 auto *OnlyDecl = Imported.Initializers.front(); 1148 if (isa<ImportDecl>(OnlyDecl)) 1149 D = OnlyDecl; 1150 } 1151 } 1152 1153 auto *&Inits = ModuleInitializers[M]; 1154 if (!Inits) 1155 Inits = new (*this) PerModuleInitializers; 1156 Inits->Initializers.push_back(D); 1157 } 1158 1159 void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) { 1160 auto *&Inits = ModuleInitializers[M]; 1161 if (!Inits) 1162 Inits = new (*this) PerModuleInitializers; 1163 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(), 1164 IDs.begin(), IDs.end()); 1165 } 1166 1167 ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) { 1168 auto It = ModuleInitializers.find(M); 1169 if (It == ModuleInitializers.end()) 1170 return None; 1171 1172 auto *Inits = It->second; 1173 Inits->resolve(*this); 1174 return Inits->Initializers; 1175 } 1176 1177 ExternCContextDecl *ASTContext::getExternCContextDecl() const { 1178 if (!ExternCContext) 1179 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl()); 1180 1181 return ExternCContext; 1182 } 1183 1184 BuiltinTemplateDecl * 1185 ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK, 1186 const IdentifierInfo *II) const { 1187 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK); 1188 BuiltinTemplate->setImplicit(); 1189 TUDecl->addDecl(BuiltinTemplate); 1190 1191 return BuiltinTemplate; 1192 } 1193 1194 BuiltinTemplateDecl * 1195 ASTContext::getMakeIntegerSeqDecl() const { 1196 if (!MakeIntegerSeqDecl) 1197 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq, 1198 getMakeIntegerSeqName()); 1199 return MakeIntegerSeqDecl; 1200 } 1201 1202 BuiltinTemplateDecl * 1203 ASTContext::getTypePackElementDecl() const { 1204 if (!TypePackElementDecl) 1205 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element, 1206 getTypePackElementName()); 1207 return TypePackElementDecl; 1208 } 1209 1210 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name, 1211 RecordDecl::TagKind TK) const { 1212 SourceLocation Loc; 1213 RecordDecl *NewDecl; 1214 if (getLangOpts().CPlusPlus) 1215 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, 1216 Loc, &Idents.get(Name)); 1217 else 1218 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc, 1219 &Idents.get(Name)); 1220 NewDecl->setImplicit(); 1221 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit( 1222 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default)); 1223 return NewDecl; 1224 } 1225 1226 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T, 1227 StringRef Name) const { 1228 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); 1229 TypedefDecl *NewDecl = TypedefDecl::Create( 1230 const_cast<ASTContext &>(*this), getTranslationUnitDecl(), 1231 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo); 1232 NewDecl->setImplicit(); 1233 return NewDecl; 1234 } 1235 1236 TypedefDecl *ASTContext::getInt128Decl() const { 1237 if (!Int128Decl) 1238 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t"); 1239 return Int128Decl; 1240 } 1241 1242 TypedefDecl *ASTContext::getUInt128Decl() const { 1243 if (!UInt128Decl) 1244 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t"); 1245 return UInt128Decl; 1246 } 1247 1248 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) { 1249 auto *Ty = new (*this, TypeAlignment) BuiltinType(K); 1250 R = CanQualType::CreateUnsafe(QualType(Ty, 0)); 1251 Types.push_back(Ty); 1252 } 1253 1254 void ASTContext::InitBuiltinTypes(const TargetInfo &Target, 1255 const TargetInfo *AuxTarget) { 1256 assert((!this->Target || this->Target == &Target) && 1257 "Incorrect target reinitialization"); 1258 assert(VoidTy.isNull() && "Context reinitialized?"); 1259 1260 this->Target = &Target; 1261 this->AuxTarget = AuxTarget; 1262 1263 ABI.reset(createCXXABI(Target)); 1264 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts); 1265 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts); 1266 1267 // C99 6.2.5p19. 1268 InitBuiltinType(VoidTy, BuiltinType::Void); 1269 1270 // C99 6.2.5p2. 1271 InitBuiltinType(BoolTy, BuiltinType::Bool); 1272 // C99 6.2.5p3. 1273 if (LangOpts.CharIsSigned) 1274 InitBuiltinType(CharTy, BuiltinType::Char_S); 1275 else 1276 InitBuiltinType(CharTy, BuiltinType::Char_U); 1277 // C99 6.2.5p4. 1278 InitBuiltinType(SignedCharTy, BuiltinType::SChar); 1279 InitBuiltinType(ShortTy, BuiltinType::Short); 1280 InitBuiltinType(IntTy, BuiltinType::Int); 1281 InitBuiltinType(LongTy, BuiltinType::Long); 1282 InitBuiltinType(LongLongTy, BuiltinType::LongLong); 1283 1284 // C99 6.2.5p6. 1285 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar); 1286 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort); 1287 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt); 1288 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong); 1289 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong); 1290 1291 // C99 6.2.5p10. 1292 InitBuiltinType(FloatTy, BuiltinType::Float); 1293 InitBuiltinType(DoubleTy, BuiltinType::Double); 1294 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble); 1295 1296 // GNU extension, __float128 for IEEE quadruple precision 1297 InitBuiltinType(Float128Ty, BuiltinType::Float128); 1298 1299 // C11 extension ISO/IEC TS 18661-3 1300 InitBuiltinType(Float16Ty, BuiltinType::Float16); 1301 1302 // ISO/IEC JTC1 SC22 WG14 N1169 Extension 1303 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum); 1304 InitBuiltinType(AccumTy, BuiltinType::Accum); 1305 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum); 1306 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum); 1307 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum); 1308 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum); 1309 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract); 1310 InitBuiltinType(FractTy, BuiltinType::Fract); 1311 InitBuiltinType(LongFractTy, BuiltinType::LongFract); 1312 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract); 1313 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract); 1314 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract); 1315 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum); 1316 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum); 1317 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum); 1318 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum); 1319 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum); 1320 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum); 1321 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract); 1322 InitBuiltinType(SatFractTy, BuiltinType::SatFract); 1323 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract); 1324 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract); 1325 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract); 1326 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract); 1327 1328 // GNU extension, 128-bit integers. 1329 InitBuiltinType(Int128Ty, BuiltinType::Int128); 1330 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128); 1331 1332 // C++ 3.9.1p5 1333 if (TargetInfo::isTypeSigned(Target.getWCharType())) 1334 InitBuiltinType(WCharTy, BuiltinType::WChar_S); 1335 else // -fshort-wchar makes wchar_t be unsigned. 1336 InitBuiltinType(WCharTy, BuiltinType::WChar_U); 1337 if (LangOpts.CPlusPlus && LangOpts.WChar) 1338 WideCharTy = WCharTy; 1339 else { 1340 // C99 (or C++ using -fno-wchar). 1341 WideCharTy = getFromTargetType(Target.getWCharType()); 1342 } 1343 1344 WIntTy = getFromTargetType(Target.getWIntType()); 1345 1346 // C++20 (proposed) 1347 InitBuiltinType(Char8Ty, BuiltinType::Char8); 1348 1349 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 1350 InitBuiltinType(Char16Ty, BuiltinType::Char16); 1351 else // C99 1352 Char16Ty = getFromTargetType(Target.getChar16Type()); 1353 1354 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 1355 InitBuiltinType(Char32Ty, BuiltinType::Char32); 1356 else // C99 1357 Char32Ty = getFromTargetType(Target.getChar32Type()); 1358 1359 // Placeholder type for type-dependent expressions whose type is 1360 // completely unknown. No code should ever check a type against 1361 // DependentTy and users should never see it; however, it is here to 1362 // help diagnose failures to properly check for type-dependent 1363 // expressions. 1364 InitBuiltinType(DependentTy, BuiltinType::Dependent); 1365 1366 // Placeholder type for functions. 1367 InitBuiltinType(OverloadTy, BuiltinType::Overload); 1368 1369 // Placeholder type for bound members. 1370 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember); 1371 1372 // Placeholder type for pseudo-objects. 1373 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject); 1374 1375 // "any" type; useful for debugger-like clients. 1376 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny); 1377 1378 // Placeholder type for unbridged ARC casts. 1379 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast); 1380 1381 // Placeholder type for builtin functions. 1382 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn); 1383 1384 // Placeholder type for OMP array sections. 1385 if (LangOpts.OpenMP) { 1386 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection); 1387 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping); 1388 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator); 1389 } 1390 if (LangOpts.MatrixTypes) 1391 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx); 1392 1393 // C99 6.2.5p11. 1394 FloatComplexTy = getComplexType(FloatTy); 1395 DoubleComplexTy = getComplexType(DoubleTy); 1396 LongDoubleComplexTy = getComplexType(LongDoubleTy); 1397 Float128ComplexTy = getComplexType(Float128Ty); 1398 1399 // Builtin types for 'id', 'Class', and 'SEL'. 1400 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId); 1401 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass); 1402 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel); 1403 1404 if (LangOpts.OpenCL) { 1405 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 1406 InitBuiltinType(SingletonId, BuiltinType::Id); 1407 #include "clang/Basic/OpenCLImageTypes.def" 1408 1409 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler); 1410 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent); 1411 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent); 1412 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue); 1413 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID); 1414 1415 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 1416 InitBuiltinType(Id##Ty, BuiltinType::Id); 1417 #include "clang/Basic/OpenCLExtensionTypes.def" 1418 } 1419 1420 if (Target.hasAArch64SVETypes()) { 1421 #define SVE_TYPE(Name, Id, SingletonId) \ 1422 InitBuiltinType(SingletonId, BuiltinType::Id); 1423 #include "clang/Basic/AArch64SVEACLETypes.def" 1424 } 1425 1426 if (Target.getTriple().isPPC64() && 1427 Target.hasFeature("paired-vector-memops")) { 1428 if (Target.hasFeature("mma")) { 1429 #define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \ 1430 InitBuiltinType(Id##Ty, BuiltinType::Id); 1431 #include "clang/Basic/PPCTypes.def" 1432 } 1433 #define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \ 1434 InitBuiltinType(Id##Ty, BuiltinType::Id); 1435 #include "clang/Basic/PPCTypes.def" 1436 } 1437 1438 // Builtin type for __objc_yes and __objc_no 1439 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ? 1440 SignedCharTy : BoolTy); 1441 1442 ObjCConstantStringType = QualType(); 1443 1444 ObjCSuperType = QualType(); 1445 1446 // void * type 1447 if (LangOpts.OpenCLVersion >= 200) { 1448 auto Q = VoidTy.getQualifiers(); 1449 Q.setAddressSpace(LangAS::opencl_generic); 1450 VoidPtrTy = getPointerType(getCanonicalType( 1451 getQualifiedType(VoidTy.getUnqualifiedType(), Q))); 1452 } else { 1453 VoidPtrTy = getPointerType(VoidTy); 1454 } 1455 1456 // nullptr type (C++0x 2.14.7) 1457 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr); 1458 1459 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16 1460 InitBuiltinType(HalfTy, BuiltinType::Half); 1461 1462 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16); 1463 1464 // Builtin type used to help define __builtin_va_list. 1465 VaListTagDecl = nullptr; 1466 1467 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls. 1468 if (LangOpts.MicrosoftExt || LangOpts.Borland) { 1469 MSGuidTagDecl = buildImplicitRecord("_GUID"); 1470 TUDecl->addDecl(MSGuidTagDecl); 1471 } 1472 } 1473 1474 DiagnosticsEngine &ASTContext::getDiagnostics() const { 1475 return SourceMgr.getDiagnostics(); 1476 } 1477 1478 AttrVec& ASTContext::getDeclAttrs(const Decl *D) { 1479 AttrVec *&Result = DeclAttrs[D]; 1480 if (!Result) { 1481 void *Mem = Allocate(sizeof(AttrVec)); 1482 Result = new (Mem) AttrVec; 1483 } 1484 1485 return *Result; 1486 } 1487 1488 /// Erase the attributes corresponding to the given declaration. 1489 void ASTContext::eraseDeclAttrs(const Decl *D) { 1490 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D); 1491 if (Pos != DeclAttrs.end()) { 1492 Pos->second->~AttrVec(); 1493 DeclAttrs.erase(Pos); 1494 } 1495 } 1496 1497 // FIXME: Remove ? 1498 MemberSpecializationInfo * 1499 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) { 1500 assert(Var->isStaticDataMember() && "Not a static data member"); 1501 return getTemplateOrSpecializationInfo(Var) 1502 .dyn_cast<MemberSpecializationInfo *>(); 1503 } 1504 1505 ASTContext::TemplateOrSpecializationInfo 1506 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) { 1507 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos = 1508 TemplateOrInstantiation.find(Var); 1509 if (Pos == TemplateOrInstantiation.end()) 1510 return {}; 1511 1512 return Pos->second; 1513 } 1514 1515 void 1516 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, 1517 TemplateSpecializationKind TSK, 1518 SourceLocation PointOfInstantiation) { 1519 assert(Inst->isStaticDataMember() && "Not a static data member"); 1520 assert(Tmpl->isStaticDataMember() && "Not a static data member"); 1521 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo( 1522 Tmpl, TSK, PointOfInstantiation)); 1523 } 1524 1525 void 1526 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst, 1527 TemplateOrSpecializationInfo TSI) { 1528 assert(!TemplateOrInstantiation[Inst] && 1529 "Already noted what the variable was instantiated from"); 1530 TemplateOrInstantiation[Inst] = TSI; 1531 } 1532 1533 NamedDecl * 1534 ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) { 1535 auto Pos = InstantiatedFromUsingDecl.find(UUD); 1536 if (Pos == InstantiatedFromUsingDecl.end()) 1537 return nullptr; 1538 1539 return Pos->second; 1540 } 1541 1542 void 1543 ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) { 1544 assert((isa<UsingDecl>(Pattern) || 1545 isa<UnresolvedUsingValueDecl>(Pattern) || 1546 isa<UnresolvedUsingTypenameDecl>(Pattern)) && 1547 "pattern decl is not a using decl"); 1548 assert((isa<UsingDecl>(Inst) || 1549 isa<UnresolvedUsingValueDecl>(Inst) || 1550 isa<UnresolvedUsingTypenameDecl>(Inst)) && 1551 "instantiation did not produce a using decl"); 1552 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists"); 1553 InstantiatedFromUsingDecl[Inst] = Pattern; 1554 } 1555 1556 UsingShadowDecl * 1557 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) { 1558 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos 1559 = InstantiatedFromUsingShadowDecl.find(Inst); 1560 if (Pos == InstantiatedFromUsingShadowDecl.end()) 1561 return nullptr; 1562 1563 return Pos->second; 1564 } 1565 1566 void 1567 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, 1568 UsingShadowDecl *Pattern) { 1569 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists"); 1570 InstantiatedFromUsingShadowDecl[Inst] = Pattern; 1571 } 1572 1573 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) { 1574 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos 1575 = InstantiatedFromUnnamedFieldDecl.find(Field); 1576 if (Pos == InstantiatedFromUnnamedFieldDecl.end()) 1577 return nullptr; 1578 1579 return Pos->second; 1580 } 1581 1582 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, 1583 FieldDecl *Tmpl) { 1584 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed"); 1585 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed"); 1586 assert(!InstantiatedFromUnnamedFieldDecl[Inst] && 1587 "Already noted what unnamed field was instantiated from"); 1588 1589 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl; 1590 } 1591 1592 ASTContext::overridden_cxx_method_iterator 1593 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const { 1594 return overridden_methods(Method).begin(); 1595 } 1596 1597 ASTContext::overridden_cxx_method_iterator 1598 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const { 1599 return overridden_methods(Method).end(); 1600 } 1601 1602 unsigned 1603 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const { 1604 auto Range = overridden_methods(Method); 1605 return Range.end() - Range.begin(); 1606 } 1607 1608 ASTContext::overridden_method_range 1609 ASTContext::overridden_methods(const CXXMethodDecl *Method) const { 1610 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos = 1611 OverriddenMethods.find(Method->getCanonicalDecl()); 1612 if (Pos == OverriddenMethods.end()) 1613 return overridden_method_range(nullptr, nullptr); 1614 return overridden_method_range(Pos->second.begin(), Pos->second.end()); 1615 } 1616 1617 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method, 1618 const CXXMethodDecl *Overridden) { 1619 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl()); 1620 OverriddenMethods[Method].push_back(Overridden); 1621 } 1622 1623 void ASTContext::getOverriddenMethods( 1624 const NamedDecl *D, 1625 SmallVectorImpl<const NamedDecl *> &Overridden) const { 1626 assert(D); 1627 1628 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) { 1629 Overridden.append(overridden_methods_begin(CXXMethod), 1630 overridden_methods_end(CXXMethod)); 1631 return; 1632 } 1633 1634 const auto *Method = dyn_cast<ObjCMethodDecl>(D); 1635 if (!Method) 1636 return; 1637 1638 SmallVector<const ObjCMethodDecl *, 8> OverDecls; 1639 Method->getOverriddenMethods(OverDecls); 1640 Overridden.append(OverDecls.begin(), OverDecls.end()); 1641 } 1642 1643 void ASTContext::addedLocalImportDecl(ImportDecl *Import) { 1644 assert(!Import->getNextLocalImport() && 1645 "Import declaration already in the chain"); 1646 assert(!Import->isFromASTFile() && "Non-local import declaration"); 1647 if (!FirstLocalImport) { 1648 FirstLocalImport = Import; 1649 LastLocalImport = Import; 1650 return; 1651 } 1652 1653 LastLocalImport->setNextLocalImport(Import); 1654 LastLocalImport = Import; 1655 } 1656 1657 //===----------------------------------------------------------------------===// 1658 // Type Sizing and Analysis 1659 //===----------------------------------------------------------------------===// 1660 1661 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified 1662 /// scalar floating point type. 1663 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const { 1664 switch (T->castAs<BuiltinType>()->getKind()) { 1665 default: 1666 llvm_unreachable("Not a floating point type!"); 1667 case BuiltinType::BFloat16: 1668 return Target->getBFloat16Format(); 1669 case BuiltinType::Float16: 1670 case BuiltinType::Half: 1671 return Target->getHalfFormat(); 1672 case BuiltinType::Float: return Target->getFloatFormat(); 1673 case BuiltinType::Double: return Target->getDoubleFormat(); 1674 case BuiltinType::LongDouble: 1675 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) 1676 return AuxTarget->getLongDoubleFormat(); 1677 return Target->getLongDoubleFormat(); 1678 case BuiltinType::Float128: 1679 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) 1680 return AuxTarget->getFloat128Format(); 1681 return Target->getFloat128Format(); 1682 } 1683 } 1684 1685 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const { 1686 unsigned Align = Target->getCharWidth(); 1687 1688 bool UseAlignAttrOnly = false; 1689 if (unsigned AlignFromAttr = D->getMaxAlignment()) { 1690 Align = AlignFromAttr; 1691 1692 // __attribute__((aligned)) can increase or decrease alignment 1693 // *except* on a struct or struct member, where it only increases 1694 // alignment unless 'packed' is also specified. 1695 // 1696 // It is an error for alignas to decrease alignment, so we can 1697 // ignore that possibility; Sema should diagnose it. 1698 if (isa<FieldDecl>(D)) { 1699 UseAlignAttrOnly = D->hasAttr<PackedAttr>() || 1700 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 1701 } else { 1702 UseAlignAttrOnly = true; 1703 } 1704 } 1705 else if (isa<FieldDecl>(D)) 1706 UseAlignAttrOnly = 1707 D->hasAttr<PackedAttr>() || 1708 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 1709 1710 // If we're using the align attribute only, just ignore everything 1711 // else about the declaration and its type. 1712 if (UseAlignAttrOnly) { 1713 // do nothing 1714 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) { 1715 QualType T = VD->getType(); 1716 if (const auto *RT = T->getAs<ReferenceType>()) { 1717 if (ForAlignof) 1718 T = RT->getPointeeType(); 1719 else 1720 T = getPointerType(RT->getPointeeType()); 1721 } 1722 QualType BaseT = getBaseElementType(T); 1723 if (T->isFunctionType()) 1724 Align = getTypeInfoImpl(T.getTypePtr()).Align; 1725 else if (!BaseT->isIncompleteType()) { 1726 // Adjust alignments of declarations with array type by the 1727 // large-array alignment on the target. 1728 if (const ArrayType *arrayType = getAsArrayType(T)) { 1729 unsigned MinWidth = Target->getLargeArrayMinWidth(); 1730 if (!ForAlignof && MinWidth) { 1731 if (isa<VariableArrayType>(arrayType)) 1732 Align = std::max(Align, Target->getLargeArrayAlign()); 1733 else if (isa<ConstantArrayType>(arrayType) && 1734 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType))) 1735 Align = std::max(Align, Target->getLargeArrayAlign()); 1736 } 1737 } 1738 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr())); 1739 if (BaseT.getQualifiers().hasUnaligned()) 1740 Align = Target->getCharWidth(); 1741 if (const auto *VD = dyn_cast<VarDecl>(D)) { 1742 if (VD->hasGlobalStorage() && !ForAlignof) { 1743 uint64_t TypeSize = getTypeSize(T.getTypePtr()); 1744 Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize)); 1745 } 1746 } 1747 } 1748 1749 // Fields can be subject to extra alignment constraints, like if 1750 // the field is packed, the struct is packed, or the struct has a 1751 // a max-field-alignment constraint (#pragma pack). So calculate 1752 // the actual alignment of the field within the struct, and then 1753 // (as we're expected to) constrain that by the alignment of the type. 1754 if (const auto *Field = dyn_cast<FieldDecl>(VD)) { 1755 const RecordDecl *Parent = Field->getParent(); 1756 // We can only produce a sensible answer if the record is valid. 1757 if (!Parent->isInvalidDecl()) { 1758 const ASTRecordLayout &Layout = getASTRecordLayout(Parent); 1759 1760 // Start with the record's overall alignment. 1761 unsigned FieldAlign = toBits(Layout.getAlignment()); 1762 1763 // Use the GCD of that and the offset within the record. 1764 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex()); 1765 if (Offset > 0) { 1766 // Alignment is always a power of 2, so the GCD will be a power of 2, 1767 // which means we get to do this crazy thing instead of Euclid's. 1768 uint64_t LowBitOfOffset = Offset & (~Offset + 1); 1769 if (LowBitOfOffset < FieldAlign) 1770 FieldAlign = static_cast<unsigned>(LowBitOfOffset); 1771 } 1772 1773 Align = std::min(Align, FieldAlign); 1774 } 1775 } 1776 } 1777 1778 return toCharUnitsFromBits(Align); 1779 } 1780 1781 CharUnits ASTContext::getExnObjectAlignment() const { 1782 return toCharUnitsFromBits(Target->getExnObjectAlignment()); 1783 } 1784 1785 // getTypeInfoDataSizeInChars - Return the size of a type, in 1786 // chars. If the type is a record, its data size is returned. This is 1787 // the size of the memcpy that's performed when assigning this type 1788 // using a trivial copy/move assignment operator. 1789 TypeInfoChars ASTContext::getTypeInfoDataSizeInChars(QualType T) const { 1790 TypeInfoChars Info = getTypeInfoInChars(T); 1791 1792 // In C++, objects can sometimes be allocated into the tail padding 1793 // of a base-class subobject. We decide whether that's possible 1794 // during class layout, so here we can just trust the layout results. 1795 if (getLangOpts().CPlusPlus) { 1796 if (const auto *RT = T->getAs<RecordType>()) { 1797 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl()); 1798 Info.Width = layout.getDataSize(); 1799 } 1800 } 1801 1802 return Info; 1803 } 1804 1805 /// getConstantArrayInfoInChars - Performing the computation in CharUnits 1806 /// instead of in bits prevents overflowing the uint64_t for some large arrays. 1807 TypeInfoChars 1808 static getConstantArrayInfoInChars(const ASTContext &Context, 1809 const ConstantArrayType *CAT) { 1810 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType()); 1811 uint64_t Size = CAT->getSize().getZExtValue(); 1812 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <= 1813 (uint64_t)(-1)/Size) && 1814 "Overflow in array type char size evaluation"); 1815 uint64_t Width = EltInfo.Width.getQuantity() * Size; 1816 unsigned Align = EltInfo.Align.getQuantity(); 1817 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() || 1818 Context.getTargetInfo().getPointerWidth(0) == 64) 1819 Width = llvm::alignTo(Width, Align); 1820 return TypeInfoChars(CharUnits::fromQuantity(Width), 1821 CharUnits::fromQuantity(Align), 1822 EltInfo.AlignIsRequired); 1823 } 1824 1825 TypeInfoChars ASTContext::getTypeInfoInChars(const Type *T) const { 1826 if (const auto *CAT = dyn_cast<ConstantArrayType>(T)) 1827 return getConstantArrayInfoInChars(*this, CAT); 1828 TypeInfo Info = getTypeInfo(T); 1829 return TypeInfoChars(toCharUnitsFromBits(Info.Width), 1830 toCharUnitsFromBits(Info.Align), 1831 Info.AlignIsRequired); 1832 } 1833 1834 TypeInfoChars ASTContext::getTypeInfoInChars(QualType T) const { 1835 return getTypeInfoInChars(T.getTypePtr()); 1836 } 1837 1838 bool ASTContext::isAlignmentRequired(const Type *T) const { 1839 return getTypeInfo(T).AlignIsRequired; 1840 } 1841 1842 bool ASTContext::isAlignmentRequired(QualType T) const { 1843 return isAlignmentRequired(T.getTypePtr()); 1844 } 1845 1846 unsigned ASTContext::getTypeAlignIfKnown(QualType T, 1847 bool NeedsPreferredAlignment) const { 1848 // An alignment on a typedef overrides anything else. 1849 if (const auto *TT = T->getAs<TypedefType>()) 1850 if (unsigned Align = TT->getDecl()->getMaxAlignment()) 1851 return Align; 1852 1853 // If we have an (array of) complete type, we're done. 1854 T = getBaseElementType(T); 1855 if (!T->isIncompleteType()) 1856 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T); 1857 1858 // If we had an array type, its element type might be a typedef 1859 // type with an alignment attribute. 1860 if (const auto *TT = T->getAs<TypedefType>()) 1861 if (unsigned Align = TT->getDecl()->getMaxAlignment()) 1862 return Align; 1863 1864 // Otherwise, see if the declaration of the type had an attribute. 1865 if (const auto *TT = T->getAs<TagType>()) 1866 return TT->getDecl()->getMaxAlignment(); 1867 1868 return 0; 1869 } 1870 1871 TypeInfo ASTContext::getTypeInfo(const Type *T) const { 1872 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T); 1873 if (I != MemoizedTypeInfo.end()) 1874 return I->second; 1875 1876 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup. 1877 TypeInfo TI = getTypeInfoImpl(T); 1878 MemoizedTypeInfo[T] = TI; 1879 return TI; 1880 } 1881 1882 /// getTypeInfoImpl - Return the size of the specified type, in bits. This 1883 /// method does not work on incomplete types. 1884 /// 1885 /// FIXME: Pointers into different addr spaces could have different sizes and 1886 /// alignment requirements: getPointerInfo should take an AddrSpace, this 1887 /// should take a QualType, &c. 1888 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const { 1889 uint64_t Width = 0; 1890 unsigned Align = 8; 1891 bool AlignIsRequired = false; 1892 unsigned AS = 0; 1893 switch (T->getTypeClass()) { 1894 #define TYPE(Class, Base) 1895 #define ABSTRACT_TYPE(Class, Base) 1896 #define NON_CANONICAL_TYPE(Class, Base) 1897 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 1898 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \ 1899 case Type::Class: \ 1900 assert(!T->isDependentType() && "should not see dependent types here"); \ 1901 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr()); 1902 #include "clang/AST/TypeNodes.inc" 1903 llvm_unreachable("Should not see dependent types"); 1904 1905 case Type::FunctionNoProto: 1906 case Type::FunctionProto: 1907 // GCC extension: alignof(function) = 32 bits 1908 Width = 0; 1909 Align = 32; 1910 break; 1911 1912 case Type::IncompleteArray: 1913 case Type::VariableArray: 1914 case Type::ConstantArray: { 1915 // Model non-constant sized arrays as size zero, but track the alignment. 1916 uint64_t Size = 0; 1917 if (const auto *CAT = dyn_cast<ConstantArrayType>(T)) 1918 Size = CAT->getSize().getZExtValue(); 1919 1920 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType()); 1921 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) && 1922 "Overflow in array type bit size evaluation"); 1923 Width = EltInfo.Width * Size; 1924 Align = EltInfo.Align; 1925 AlignIsRequired = EltInfo.AlignIsRequired; 1926 if (!getTargetInfo().getCXXABI().isMicrosoft() || 1927 getTargetInfo().getPointerWidth(0) == 64) 1928 Width = llvm::alignTo(Width, Align); 1929 break; 1930 } 1931 1932 case Type::ExtVector: 1933 case Type::Vector: { 1934 const auto *VT = cast<VectorType>(T); 1935 TypeInfo EltInfo = getTypeInfo(VT->getElementType()); 1936 Width = EltInfo.Width * VT->getNumElements(); 1937 Align = Width; 1938 // If the alignment is not a power of 2, round up to the next power of 2. 1939 // This happens for non-power-of-2 length vectors. 1940 if (Align & (Align-1)) { 1941 Align = llvm::NextPowerOf2(Align); 1942 Width = llvm::alignTo(Width, Align); 1943 } 1944 // Adjust the alignment based on the target max. 1945 uint64_t TargetVectorAlign = Target->getMaxVectorAlign(); 1946 if (TargetVectorAlign && TargetVectorAlign < Align) 1947 Align = TargetVectorAlign; 1948 if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) 1949 // Adjust the alignment for fixed-length SVE vectors. This is important 1950 // for non-power-of-2 vector lengths. 1951 Align = 128; 1952 else if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 1953 // Adjust the alignment for fixed-length SVE predicates. 1954 Align = 16; 1955 break; 1956 } 1957 1958 case Type::ConstantMatrix: { 1959 const auto *MT = cast<ConstantMatrixType>(T); 1960 TypeInfo ElementInfo = getTypeInfo(MT->getElementType()); 1961 // The internal layout of a matrix value is implementation defined. 1962 // Initially be ABI compatible with arrays with respect to alignment and 1963 // size. 1964 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns(); 1965 Align = ElementInfo.Align; 1966 break; 1967 } 1968 1969 case Type::Builtin: 1970 switch (cast<BuiltinType>(T)->getKind()) { 1971 default: llvm_unreachable("Unknown builtin type!"); 1972 case BuiltinType::Void: 1973 // GCC extension: alignof(void) = 8 bits. 1974 Width = 0; 1975 Align = 8; 1976 break; 1977 case BuiltinType::Bool: 1978 Width = Target->getBoolWidth(); 1979 Align = Target->getBoolAlign(); 1980 break; 1981 case BuiltinType::Char_S: 1982 case BuiltinType::Char_U: 1983 case BuiltinType::UChar: 1984 case BuiltinType::SChar: 1985 case BuiltinType::Char8: 1986 Width = Target->getCharWidth(); 1987 Align = Target->getCharAlign(); 1988 break; 1989 case BuiltinType::WChar_S: 1990 case BuiltinType::WChar_U: 1991 Width = Target->getWCharWidth(); 1992 Align = Target->getWCharAlign(); 1993 break; 1994 case BuiltinType::Char16: 1995 Width = Target->getChar16Width(); 1996 Align = Target->getChar16Align(); 1997 break; 1998 case BuiltinType::Char32: 1999 Width = Target->getChar32Width(); 2000 Align = Target->getChar32Align(); 2001 break; 2002 case BuiltinType::UShort: 2003 case BuiltinType::Short: 2004 Width = Target->getShortWidth(); 2005 Align = Target->getShortAlign(); 2006 break; 2007 case BuiltinType::UInt: 2008 case BuiltinType::Int: 2009 Width = Target->getIntWidth(); 2010 Align = Target->getIntAlign(); 2011 break; 2012 case BuiltinType::ULong: 2013 case BuiltinType::Long: 2014 Width = Target->getLongWidth(); 2015 Align = Target->getLongAlign(); 2016 break; 2017 case BuiltinType::ULongLong: 2018 case BuiltinType::LongLong: 2019 Width = Target->getLongLongWidth(); 2020 Align = Target->getLongLongAlign(); 2021 break; 2022 case BuiltinType::Int128: 2023 case BuiltinType::UInt128: 2024 Width = 128; 2025 Align = 128; // int128_t is 128-bit aligned on all targets. 2026 break; 2027 case BuiltinType::ShortAccum: 2028 case BuiltinType::UShortAccum: 2029 case BuiltinType::SatShortAccum: 2030 case BuiltinType::SatUShortAccum: 2031 Width = Target->getShortAccumWidth(); 2032 Align = Target->getShortAccumAlign(); 2033 break; 2034 case BuiltinType::Accum: 2035 case BuiltinType::UAccum: 2036 case BuiltinType::SatAccum: 2037 case BuiltinType::SatUAccum: 2038 Width = Target->getAccumWidth(); 2039 Align = Target->getAccumAlign(); 2040 break; 2041 case BuiltinType::LongAccum: 2042 case BuiltinType::ULongAccum: 2043 case BuiltinType::SatLongAccum: 2044 case BuiltinType::SatULongAccum: 2045 Width = Target->getLongAccumWidth(); 2046 Align = Target->getLongAccumAlign(); 2047 break; 2048 case BuiltinType::ShortFract: 2049 case BuiltinType::UShortFract: 2050 case BuiltinType::SatShortFract: 2051 case BuiltinType::SatUShortFract: 2052 Width = Target->getShortFractWidth(); 2053 Align = Target->getShortFractAlign(); 2054 break; 2055 case BuiltinType::Fract: 2056 case BuiltinType::UFract: 2057 case BuiltinType::SatFract: 2058 case BuiltinType::SatUFract: 2059 Width = Target->getFractWidth(); 2060 Align = Target->getFractAlign(); 2061 break; 2062 case BuiltinType::LongFract: 2063 case BuiltinType::ULongFract: 2064 case BuiltinType::SatLongFract: 2065 case BuiltinType::SatULongFract: 2066 Width = Target->getLongFractWidth(); 2067 Align = Target->getLongFractAlign(); 2068 break; 2069 case BuiltinType::BFloat16: 2070 Width = Target->getBFloat16Width(); 2071 Align = Target->getBFloat16Align(); 2072 break; 2073 case BuiltinType::Float16: 2074 case BuiltinType::Half: 2075 if (Target->hasFloat16Type() || !getLangOpts().OpenMP || 2076 !getLangOpts().OpenMPIsDevice) { 2077 Width = Target->getHalfWidth(); 2078 Align = Target->getHalfAlign(); 2079 } else { 2080 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 2081 "Expected OpenMP device compilation."); 2082 Width = AuxTarget->getHalfWidth(); 2083 Align = AuxTarget->getHalfAlign(); 2084 } 2085 break; 2086 case BuiltinType::Float: 2087 Width = Target->getFloatWidth(); 2088 Align = Target->getFloatAlign(); 2089 break; 2090 case BuiltinType::Double: 2091 Width = Target->getDoubleWidth(); 2092 Align = Target->getDoubleAlign(); 2093 break; 2094 case BuiltinType::LongDouble: 2095 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 2096 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() || 2097 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) { 2098 Width = AuxTarget->getLongDoubleWidth(); 2099 Align = AuxTarget->getLongDoubleAlign(); 2100 } else { 2101 Width = Target->getLongDoubleWidth(); 2102 Align = Target->getLongDoubleAlign(); 2103 } 2104 break; 2105 case BuiltinType::Float128: 2106 if (Target->hasFloat128Type() || !getLangOpts().OpenMP || 2107 !getLangOpts().OpenMPIsDevice) { 2108 Width = Target->getFloat128Width(); 2109 Align = Target->getFloat128Align(); 2110 } else { 2111 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 2112 "Expected OpenMP device compilation."); 2113 Width = AuxTarget->getFloat128Width(); 2114 Align = AuxTarget->getFloat128Align(); 2115 } 2116 break; 2117 case BuiltinType::NullPtr: 2118 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t) 2119 Align = Target->getPointerAlign(0); // == sizeof(void*) 2120 break; 2121 case BuiltinType::ObjCId: 2122 case BuiltinType::ObjCClass: 2123 case BuiltinType::ObjCSel: 2124 Width = Target->getPointerWidth(0); 2125 Align = Target->getPointerAlign(0); 2126 break; 2127 case BuiltinType::OCLSampler: 2128 case BuiltinType::OCLEvent: 2129 case BuiltinType::OCLClkEvent: 2130 case BuiltinType::OCLQueue: 2131 case BuiltinType::OCLReserveID: 2132 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 2133 case BuiltinType::Id: 2134 #include "clang/Basic/OpenCLImageTypes.def" 2135 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 2136 case BuiltinType::Id: 2137 #include "clang/Basic/OpenCLExtensionTypes.def" 2138 AS = getTargetAddressSpace( 2139 Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T))); 2140 Width = Target->getPointerWidth(AS); 2141 Align = Target->getPointerAlign(AS); 2142 break; 2143 // The SVE types are effectively target-specific. The length of an 2144 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple 2145 // of 128 bits. There is one predicate bit for each vector byte, so the 2146 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits. 2147 // 2148 // Because the length is only known at runtime, we use a dummy value 2149 // of 0 for the static length. The alignment values are those defined 2150 // by the Procedure Call Standard for the Arm Architecture. 2151 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \ 2152 IsSigned, IsFP, IsBF) \ 2153 case BuiltinType::Id: \ 2154 Width = 0; \ 2155 Align = 128; \ 2156 break; 2157 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \ 2158 case BuiltinType::Id: \ 2159 Width = 0; \ 2160 Align = 16; \ 2161 break; 2162 #include "clang/Basic/AArch64SVEACLETypes.def" 2163 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 2164 case BuiltinType::Id: \ 2165 Width = Size; \ 2166 Align = Size; \ 2167 break; 2168 #include "clang/Basic/PPCTypes.def" 2169 } 2170 break; 2171 case Type::ObjCObjectPointer: 2172 Width = Target->getPointerWidth(0); 2173 Align = Target->getPointerAlign(0); 2174 break; 2175 case Type::BlockPointer: 2176 AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType()); 2177 Width = Target->getPointerWidth(AS); 2178 Align = Target->getPointerAlign(AS); 2179 break; 2180 case Type::LValueReference: 2181 case Type::RValueReference: 2182 // alignof and sizeof should never enter this code path here, so we go 2183 // the pointer route. 2184 AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType()); 2185 Width = Target->getPointerWidth(AS); 2186 Align = Target->getPointerAlign(AS); 2187 break; 2188 case Type::Pointer: 2189 AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType()); 2190 Width = Target->getPointerWidth(AS); 2191 Align = Target->getPointerAlign(AS); 2192 break; 2193 case Type::MemberPointer: { 2194 const auto *MPT = cast<MemberPointerType>(T); 2195 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT); 2196 Width = MPI.Width; 2197 Align = MPI.Align; 2198 break; 2199 } 2200 case Type::Complex: { 2201 // Complex types have the same alignment as their elements, but twice the 2202 // size. 2203 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType()); 2204 Width = EltInfo.Width * 2; 2205 Align = EltInfo.Align; 2206 break; 2207 } 2208 case Type::ObjCObject: 2209 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr()); 2210 case Type::Adjusted: 2211 case Type::Decayed: 2212 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr()); 2213 case Type::ObjCInterface: { 2214 const auto *ObjCI = cast<ObjCInterfaceType>(T); 2215 if (ObjCI->getDecl()->isInvalidDecl()) { 2216 Width = 8; 2217 Align = 8; 2218 break; 2219 } 2220 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 2221 Width = toBits(Layout.getSize()); 2222 Align = toBits(Layout.getAlignment()); 2223 break; 2224 } 2225 case Type::ExtInt: { 2226 const auto *EIT = cast<ExtIntType>(T); 2227 Align = 2228 std::min(static_cast<unsigned>(std::max( 2229 getCharWidth(), llvm::PowerOf2Ceil(EIT->getNumBits()))), 2230 Target->getLongLongAlign()); 2231 Width = llvm::alignTo(EIT->getNumBits(), Align); 2232 break; 2233 } 2234 case Type::Record: 2235 case Type::Enum: { 2236 const auto *TT = cast<TagType>(T); 2237 2238 if (TT->getDecl()->isInvalidDecl()) { 2239 Width = 8; 2240 Align = 8; 2241 break; 2242 } 2243 2244 if (const auto *ET = dyn_cast<EnumType>(TT)) { 2245 const EnumDecl *ED = ET->getDecl(); 2246 TypeInfo Info = 2247 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType()); 2248 if (unsigned AttrAlign = ED->getMaxAlignment()) { 2249 Info.Align = AttrAlign; 2250 Info.AlignIsRequired = true; 2251 } 2252 return Info; 2253 } 2254 2255 const auto *RT = cast<RecordType>(TT); 2256 const RecordDecl *RD = RT->getDecl(); 2257 const ASTRecordLayout &Layout = getASTRecordLayout(RD); 2258 Width = toBits(Layout.getSize()); 2259 Align = toBits(Layout.getAlignment()); 2260 AlignIsRequired = RD->hasAttr<AlignedAttr>(); 2261 break; 2262 } 2263 2264 case Type::SubstTemplateTypeParm: 2265 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)-> 2266 getReplacementType().getTypePtr()); 2267 2268 case Type::Auto: 2269 case Type::DeducedTemplateSpecialization: { 2270 const auto *A = cast<DeducedType>(T); 2271 assert(!A->getDeducedType().isNull() && 2272 "cannot request the size of an undeduced or dependent auto type"); 2273 return getTypeInfo(A->getDeducedType().getTypePtr()); 2274 } 2275 2276 case Type::Paren: 2277 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr()); 2278 2279 case Type::MacroQualified: 2280 return getTypeInfo( 2281 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr()); 2282 2283 case Type::ObjCTypeParam: 2284 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr()); 2285 2286 case Type::Typedef: { 2287 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl(); 2288 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr()); 2289 // If the typedef has an aligned attribute on it, it overrides any computed 2290 // alignment we have. This violates the GCC documentation (which says that 2291 // attribute(aligned) can only round up) but matches its implementation. 2292 if (unsigned AttrAlign = Typedef->getMaxAlignment()) { 2293 Align = AttrAlign; 2294 AlignIsRequired = true; 2295 } else { 2296 Align = Info.Align; 2297 AlignIsRequired = Info.AlignIsRequired; 2298 } 2299 Width = Info.Width; 2300 break; 2301 } 2302 2303 case Type::Elaborated: 2304 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr()); 2305 2306 case Type::Attributed: 2307 return getTypeInfo( 2308 cast<AttributedType>(T)->getEquivalentType().getTypePtr()); 2309 2310 case Type::Atomic: { 2311 // Start with the base type information. 2312 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType()); 2313 Width = Info.Width; 2314 Align = Info.Align; 2315 2316 if (!Width) { 2317 // An otherwise zero-sized type should still generate an 2318 // atomic operation. 2319 Width = Target->getCharWidth(); 2320 assert(Align); 2321 } else if (Width <= Target->getMaxAtomicPromoteWidth()) { 2322 // If the size of the type doesn't exceed the platform's max 2323 // atomic promotion width, make the size and alignment more 2324 // favorable to atomic operations: 2325 2326 // Round the size up to a power of 2. 2327 if (!llvm::isPowerOf2_64(Width)) 2328 Width = llvm::NextPowerOf2(Width); 2329 2330 // Set the alignment equal to the size. 2331 Align = static_cast<unsigned>(Width); 2332 } 2333 } 2334 break; 2335 2336 case Type::Pipe: 2337 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global)); 2338 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global)); 2339 break; 2340 } 2341 2342 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2"); 2343 return TypeInfo(Width, Align, AlignIsRequired); 2344 } 2345 2346 unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const { 2347 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T); 2348 if (I != MemoizedUnadjustedAlign.end()) 2349 return I->second; 2350 2351 unsigned UnadjustedAlign; 2352 if (const auto *RT = T->getAs<RecordType>()) { 2353 const RecordDecl *RD = RT->getDecl(); 2354 const ASTRecordLayout &Layout = getASTRecordLayout(RD); 2355 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment()); 2356 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) { 2357 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 2358 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment()); 2359 } else { 2360 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType()); 2361 } 2362 2363 MemoizedUnadjustedAlign[T] = UnadjustedAlign; 2364 return UnadjustedAlign; 2365 } 2366 2367 unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const { 2368 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign(); 2369 return SimdAlign; 2370 } 2371 2372 /// toCharUnitsFromBits - Convert a size in bits to a size in characters. 2373 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const { 2374 return CharUnits::fromQuantity(BitSize / getCharWidth()); 2375 } 2376 2377 /// toBits - Convert a size in characters to a size in characters. 2378 int64_t ASTContext::toBits(CharUnits CharSize) const { 2379 return CharSize.getQuantity() * getCharWidth(); 2380 } 2381 2382 /// getTypeSizeInChars - Return the size of the specified type, in characters. 2383 /// This method does not work on incomplete types. 2384 CharUnits ASTContext::getTypeSizeInChars(QualType T) const { 2385 return getTypeInfoInChars(T).Width; 2386 } 2387 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const { 2388 return getTypeInfoInChars(T).Width; 2389 } 2390 2391 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in 2392 /// characters. This method does not work on incomplete types. 2393 CharUnits ASTContext::getTypeAlignInChars(QualType T) const { 2394 return toCharUnitsFromBits(getTypeAlign(T)); 2395 } 2396 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const { 2397 return toCharUnitsFromBits(getTypeAlign(T)); 2398 } 2399 2400 /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a 2401 /// type, in characters, before alignment adustments. This method does 2402 /// not work on incomplete types. 2403 CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const { 2404 return toCharUnitsFromBits(getTypeUnadjustedAlign(T)); 2405 } 2406 CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const { 2407 return toCharUnitsFromBits(getTypeUnadjustedAlign(T)); 2408 } 2409 2410 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified 2411 /// type for the current target in bits. This can be different than the ABI 2412 /// alignment in cases where it is beneficial for performance or backwards 2413 /// compatibility preserving to overalign a data type. (Note: despite the name, 2414 /// the preferred alignment is ABI-impacting, and not an optimization.) 2415 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const { 2416 TypeInfo TI = getTypeInfo(T); 2417 unsigned ABIAlign = TI.Align; 2418 2419 T = T->getBaseElementTypeUnsafe(); 2420 2421 // The preferred alignment of member pointers is that of a pointer. 2422 if (T->isMemberPointerType()) 2423 return getPreferredTypeAlign(getPointerDiffType().getTypePtr()); 2424 2425 if (!Target->allowsLargerPreferedTypeAlignment()) 2426 return ABIAlign; 2427 2428 if (const auto *RT = T->getAs<RecordType>()) { 2429 if (TI.AlignIsRequired || RT->getDecl()->isInvalidDecl()) 2430 return ABIAlign; 2431 2432 unsigned PreferredAlign = static_cast<unsigned>( 2433 toBits(getASTRecordLayout(RT->getDecl()).PreferredAlignment)); 2434 assert(PreferredAlign >= ABIAlign && 2435 "PreferredAlign should be at least as large as ABIAlign."); 2436 return PreferredAlign; 2437 } 2438 2439 // Double (and, for targets supporting AIX `power` alignment, long double) and 2440 // long long should be naturally aligned (despite requiring less alignment) if 2441 // possible. 2442 if (const auto *CT = T->getAs<ComplexType>()) 2443 T = CT->getElementType().getTypePtr(); 2444 if (const auto *ET = T->getAs<EnumType>()) 2445 T = ET->getDecl()->getIntegerType().getTypePtr(); 2446 if (T->isSpecificBuiltinType(BuiltinType::Double) || 2447 T->isSpecificBuiltinType(BuiltinType::LongLong) || 2448 T->isSpecificBuiltinType(BuiltinType::ULongLong) || 2449 (T->isSpecificBuiltinType(BuiltinType::LongDouble) && 2450 Target->defaultsToAIXPowerAlignment())) 2451 // Don't increase the alignment if an alignment attribute was specified on a 2452 // typedef declaration. 2453 if (!TI.AlignIsRequired) 2454 return std::max(ABIAlign, (unsigned)getTypeSize(T)); 2455 2456 return ABIAlign; 2457 } 2458 2459 /// getTargetDefaultAlignForAttributeAligned - Return the default alignment 2460 /// for __attribute__((aligned)) on this target, to be used if no alignment 2461 /// value is specified. 2462 unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const { 2463 return getTargetInfo().getDefaultAlignForAttributeAligned(); 2464 } 2465 2466 /// getAlignOfGlobalVar - Return the alignment in bits that should be given 2467 /// to a global variable of the specified type. 2468 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const { 2469 uint64_t TypeSize = getTypeSize(T.getTypePtr()); 2470 return std::max(getPreferredTypeAlign(T), 2471 getTargetInfo().getMinGlobalAlign(TypeSize)); 2472 } 2473 2474 /// getAlignOfGlobalVarInChars - Return the alignment in characters that 2475 /// should be given to a global variable of the specified type. 2476 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const { 2477 return toCharUnitsFromBits(getAlignOfGlobalVar(T)); 2478 } 2479 2480 CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const { 2481 CharUnits Offset = CharUnits::Zero(); 2482 const ASTRecordLayout *Layout = &getASTRecordLayout(RD); 2483 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) { 2484 Offset += Layout->getBaseClassOffset(Base); 2485 Layout = &getASTRecordLayout(Base); 2486 } 2487 return Offset; 2488 } 2489 2490 CharUnits ASTContext::getMemberPointerPathAdjustment(const APValue &MP) const { 2491 const ValueDecl *MPD = MP.getMemberPointerDecl(); 2492 CharUnits ThisAdjustment = CharUnits::Zero(); 2493 ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath(); 2494 bool DerivedMember = MP.isMemberPointerToDerivedMember(); 2495 const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext()); 2496 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 2497 const CXXRecordDecl *Base = RD; 2498 const CXXRecordDecl *Derived = Path[I]; 2499 if (DerivedMember) 2500 std::swap(Base, Derived); 2501 ThisAdjustment += getASTRecordLayout(Derived).getBaseClassOffset(Base); 2502 RD = Path[I]; 2503 } 2504 if (DerivedMember) 2505 ThisAdjustment = -ThisAdjustment; 2506 return ThisAdjustment; 2507 } 2508 2509 /// DeepCollectObjCIvars - 2510 /// This routine first collects all declared, but not synthesized, ivars in 2511 /// super class and then collects all ivars, including those synthesized for 2512 /// current class. This routine is used for implementation of current class 2513 /// when all ivars, declared and synthesized are known. 2514 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, 2515 bool leafClass, 2516 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const { 2517 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass()) 2518 DeepCollectObjCIvars(SuperClass, false, Ivars); 2519 if (!leafClass) { 2520 for (const auto *I : OI->ivars()) 2521 Ivars.push_back(I); 2522 } else { 2523 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI); 2524 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv; 2525 Iv= Iv->getNextIvar()) 2526 Ivars.push_back(Iv); 2527 } 2528 } 2529 2530 /// CollectInheritedProtocols - Collect all protocols in current class and 2531 /// those inherited by it. 2532 void ASTContext::CollectInheritedProtocols(const Decl *CDecl, 2533 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) { 2534 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) { 2535 // We can use protocol_iterator here instead of 2536 // all_referenced_protocol_iterator since we are walking all categories. 2537 for (auto *Proto : OI->all_referenced_protocols()) { 2538 CollectInheritedProtocols(Proto, Protocols); 2539 } 2540 2541 // Categories of this Interface. 2542 for (const auto *Cat : OI->visible_categories()) 2543 CollectInheritedProtocols(Cat, Protocols); 2544 2545 if (ObjCInterfaceDecl *SD = OI->getSuperClass()) 2546 while (SD) { 2547 CollectInheritedProtocols(SD, Protocols); 2548 SD = SD->getSuperClass(); 2549 } 2550 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) { 2551 for (auto *Proto : OC->protocols()) { 2552 CollectInheritedProtocols(Proto, Protocols); 2553 } 2554 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) { 2555 // Insert the protocol. 2556 if (!Protocols.insert( 2557 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second) 2558 return; 2559 2560 for (auto *Proto : OP->protocols()) 2561 CollectInheritedProtocols(Proto, Protocols); 2562 } 2563 } 2564 2565 static bool unionHasUniqueObjectRepresentations(const ASTContext &Context, 2566 const RecordDecl *RD) { 2567 assert(RD->isUnion() && "Must be union type"); 2568 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl()); 2569 2570 for (const auto *Field : RD->fields()) { 2571 if (!Context.hasUniqueObjectRepresentations(Field->getType())) 2572 return false; 2573 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType()); 2574 if (FieldSize != UnionSize) 2575 return false; 2576 } 2577 return !RD->field_empty(); 2578 } 2579 2580 static bool isStructEmpty(QualType Ty) { 2581 const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl(); 2582 2583 if (!RD->field_empty()) 2584 return false; 2585 2586 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) 2587 return ClassDecl->isEmpty(); 2588 2589 return true; 2590 } 2591 2592 static llvm::Optional<int64_t> 2593 structHasUniqueObjectRepresentations(const ASTContext &Context, 2594 const RecordDecl *RD) { 2595 assert(!RD->isUnion() && "Must be struct/class type"); 2596 const auto &Layout = Context.getASTRecordLayout(RD); 2597 2598 int64_t CurOffsetInBits = 0; 2599 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) { 2600 if (ClassDecl->isDynamicClass()) 2601 return llvm::None; 2602 2603 SmallVector<std::pair<QualType, int64_t>, 4> Bases; 2604 for (const auto &Base : ClassDecl->bases()) { 2605 // Empty types can be inherited from, and non-empty types can potentially 2606 // have tail padding, so just make sure there isn't an error. 2607 if (!isStructEmpty(Base.getType())) { 2608 llvm::Optional<int64_t> Size = structHasUniqueObjectRepresentations( 2609 Context, Base.getType()->castAs<RecordType>()->getDecl()); 2610 if (!Size) 2611 return llvm::None; 2612 Bases.emplace_back(Base.getType(), Size.getValue()); 2613 } 2614 } 2615 2616 llvm::sort(Bases, [&](const std::pair<QualType, int64_t> &L, 2617 const std::pair<QualType, int64_t> &R) { 2618 return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) < 2619 Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl()); 2620 }); 2621 2622 for (const auto &Base : Bases) { 2623 int64_t BaseOffset = Context.toBits( 2624 Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl())); 2625 int64_t BaseSize = Base.second; 2626 if (BaseOffset != CurOffsetInBits) 2627 return llvm::None; 2628 CurOffsetInBits = BaseOffset + BaseSize; 2629 } 2630 } 2631 2632 for (const auto *Field : RD->fields()) { 2633 if (!Field->getType()->isReferenceType() && 2634 !Context.hasUniqueObjectRepresentations(Field->getType())) 2635 return llvm::None; 2636 2637 int64_t FieldSizeInBits = 2638 Context.toBits(Context.getTypeSizeInChars(Field->getType())); 2639 if (Field->isBitField()) { 2640 int64_t BitfieldSize = Field->getBitWidthValue(Context); 2641 2642 if (BitfieldSize > FieldSizeInBits) 2643 return llvm::None; 2644 FieldSizeInBits = BitfieldSize; 2645 } 2646 2647 int64_t FieldOffsetInBits = Context.getFieldOffset(Field); 2648 2649 if (FieldOffsetInBits != CurOffsetInBits) 2650 return llvm::None; 2651 2652 CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits; 2653 } 2654 2655 return CurOffsetInBits; 2656 } 2657 2658 bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const { 2659 // C++17 [meta.unary.prop]: 2660 // The predicate condition for a template specialization 2661 // has_unique_object_representations<T> shall be 2662 // satisfied if and only if: 2663 // (9.1) - T is trivially copyable, and 2664 // (9.2) - any two objects of type T with the same value have the same 2665 // object representation, where two objects 2666 // of array or non-union class type are considered to have the same value 2667 // if their respective sequences of 2668 // direct subobjects have the same values, and two objects of union type 2669 // are considered to have the same 2670 // value if they have the same active member and the corresponding members 2671 // have the same value. 2672 // The set of scalar types for which this condition holds is 2673 // implementation-defined. [ Note: If a type has padding 2674 // bits, the condition does not hold; otherwise, the condition holds true 2675 // for unsigned integral types. -- end note ] 2676 assert(!Ty.isNull() && "Null QualType sent to unique object rep check"); 2677 2678 // Arrays are unique only if their element type is unique. 2679 if (Ty->isArrayType()) 2680 return hasUniqueObjectRepresentations(getBaseElementType(Ty)); 2681 2682 // (9.1) - T is trivially copyable... 2683 if (!Ty.isTriviallyCopyableType(*this)) 2684 return false; 2685 2686 // All integrals and enums are unique. 2687 if (Ty->isIntegralOrEnumerationType()) 2688 return true; 2689 2690 // All other pointers are unique. 2691 if (Ty->isPointerType()) 2692 return true; 2693 2694 if (Ty->isMemberPointerType()) { 2695 const auto *MPT = Ty->getAs<MemberPointerType>(); 2696 return !ABI->getMemberPointerInfo(MPT).HasPadding; 2697 } 2698 2699 if (Ty->isRecordType()) { 2700 const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl(); 2701 2702 if (Record->isInvalidDecl()) 2703 return false; 2704 2705 if (Record->isUnion()) 2706 return unionHasUniqueObjectRepresentations(*this, Record); 2707 2708 Optional<int64_t> StructSize = 2709 structHasUniqueObjectRepresentations(*this, Record); 2710 2711 return StructSize && 2712 StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty)); 2713 } 2714 2715 // FIXME: More cases to handle here (list by rsmith): 2716 // vectors (careful about, eg, vector of 3 foo) 2717 // _Complex int and friends 2718 // _Atomic T 2719 // Obj-C block pointers 2720 // Obj-C object pointers 2721 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t, 2722 // clk_event_t, queue_t, reserve_id_t) 2723 // There're also Obj-C class types and the Obj-C selector type, but I think it 2724 // makes sense for those to return false here. 2725 2726 return false; 2727 } 2728 2729 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const { 2730 unsigned count = 0; 2731 // Count ivars declared in class extension. 2732 for (const auto *Ext : OI->known_extensions()) 2733 count += Ext->ivar_size(); 2734 2735 // Count ivar defined in this class's implementation. This 2736 // includes synthesized ivars. 2737 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) 2738 count += ImplDecl->ivar_size(); 2739 2740 return count; 2741 } 2742 2743 bool ASTContext::isSentinelNullExpr(const Expr *E) { 2744 if (!E) 2745 return false; 2746 2747 // nullptr_t is always treated as null. 2748 if (E->getType()->isNullPtrType()) return true; 2749 2750 if (E->getType()->isAnyPointerType() && 2751 E->IgnoreParenCasts()->isNullPointerConstant(*this, 2752 Expr::NPC_ValueDependentIsNull)) 2753 return true; 2754 2755 // Unfortunately, __null has type 'int'. 2756 if (isa<GNUNullExpr>(E)) return true; 2757 2758 return false; 2759 } 2760 2761 /// Get the implementation of ObjCInterfaceDecl, or nullptr if none 2762 /// exists. 2763 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) { 2764 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 2765 I = ObjCImpls.find(D); 2766 if (I != ObjCImpls.end()) 2767 return cast<ObjCImplementationDecl>(I->second); 2768 return nullptr; 2769 } 2770 2771 /// Get the implementation of ObjCCategoryDecl, or nullptr if none 2772 /// exists. 2773 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) { 2774 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 2775 I = ObjCImpls.find(D); 2776 if (I != ObjCImpls.end()) 2777 return cast<ObjCCategoryImplDecl>(I->second); 2778 return nullptr; 2779 } 2780 2781 /// Set the implementation of ObjCInterfaceDecl. 2782 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD, 2783 ObjCImplementationDecl *ImplD) { 2784 assert(IFaceD && ImplD && "Passed null params"); 2785 ObjCImpls[IFaceD] = ImplD; 2786 } 2787 2788 /// Set the implementation of ObjCCategoryDecl. 2789 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD, 2790 ObjCCategoryImplDecl *ImplD) { 2791 assert(CatD && ImplD && "Passed null params"); 2792 ObjCImpls[CatD] = ImplD; 2793 } 2794 2795 const ObjCMethodDecl * 2796 ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const { 2797 return ObjCMethodRedecls.lookup(MD); 2798 } 2799 2800 void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD, 2801 const ObjCMethodDecl *Redecl) { 2802 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration"); 2803 ObjCMethodRedecls[MD] = Redecl; 2804 } 2805 2806 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface( 2807 const NamedDecl *ND) const { 2808 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext())) 2809 return ID; 2810 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext())) 2811 return CD->getClassInterface(); 2812 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext())) 2813 return IMD->getClassInterface(); 2814 2815 return nullptr; 2816 } 2817 2818 /// Get the copy initialization expression of VarDecl, or nullptr if 2819 /// none exists. 2820 BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const { 2821 assert(VD && "Passed null params"); 2822 assert(VD->hasAttr<BlocksAttr>() && 2823 "getBlockVarCopyInits - not __block var"); 2824 auto I = BlockVarCopyInits.find(VD); 2825 if (I != BlockVarCopyInits.end()) 2826 return I->second; 2827 return {nullptr, false}; 2828 } 2829 2830 /// Set the copy initialization expression of a block var decl. 2831 void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr, 2832 bool CanThrow) { 2833 assert(VD && CopyExpr && "Passed null params"); 2834 assert(VD->hasAttr<BlocksAttr>() && 2835 "setBlockVarCopyInits - not __block var"); 2836 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow); 2837 } 2838 2839 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T, 2840 unsigned DataSize) const { 2841 if (!DataSize) 2842 DataSize = TypeLoc::getFullDataSizeForType(T); 2843 else 2844 assert(DataSize == TypeLoc::getFullDataSizeForType(T) && 2845 "incorrect data size provided to CreateTypeSourceInfo!"); 2846 2847 auto *TInfo = 2848 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8); 2849 new (TInfo) TypeSourceInfo(T); 2850 return TInfo; 2851 } 2852 2853 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T, 2854 SourceLocation L) const { 2855 TypeSourceInfo *DI = CreateTypeSourceInfo(T); 2856 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L); 2857 return DI; 2858 } 2859 2860 const ASTRecordLayout & 2861 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const { 2862 return getObjCLayout(D, nullptr); 2863 } 2864 2865 const ASTRecordLayout & 2866 ASTContext::getASTObjCImplementationLayout( 2867 const ObjCImplementationDecl *D) const { 2868 return getObjCLayout(D->getClassInterface(), D); 2869 } 2870 2871 //===----------------------------------------------------------------------===// 2872 // Type creation/memoization methods 2873 //===----------------------------------------------------------------------===// 2874 2875 QualType 2876 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const { 2877 unsigned fastQuals = quals.getFastQualifiers(); 2878 quals.removeFastQualifiers(); 2879 2880 // Check if we've already instantiated this type. 2881 llvm::FoldingSetNodeID ID; 2882 ExtQuals::Profile(ID, baseType, quals); 2883 void *insertPos = nullptr; 2884 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) { 2885 assert(eq->getQualifiers() == quals); 2886 return QualType(eq, fastQuals); 2887 } 2888 2889 // If the base type is not canonical, make the appropriate canonical type. 2890 QualType canon; 2891 if (!baseType->isCanonicalUnqualified()) { 2892 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split(); 2893 canonSplit.Quals.addConsistentQualifiers(quals); 2894 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals); 2895 2896 // Re-find the insert position. 2897 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos); 2898 } 2899 2900 auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals); 2901 ExtQualNodes.InsertNode(eq, insertPos); 2902 return QualType(eq, fastQuals); 2903 } 2904 2905 QualType ASTContext::getAddrSpaceQualType(QualType T, 2906 LangAS AddressSpace) const { 2907 QualType CanT = getCanonicalType(T); 2908 if (CanT.getAddressSpace() == AddressSpace) 2909 return T; 2910 2911 // If we are composing extended qualifiers together, merge together 2912 // into one ExtQuals node. 2913 QualifierCollector Quals; 2914 const Type *TypeNode = Quals.strip(T); 2915 2916 // If this type already has an address space specified, it cannot get 2917 // another one. 2918 assert(!Quals.hasAddressSpace() && 2919 "Type cannot be in multiple addr spaces!"); 2920 Quals.addAddressSpace(AddressSpace); 2921 2922 return getExtQualType(TypeNode, Quals); 2923 } 2924 2925 QualType ASTContext::removeAddrSpaceQualType(QualType T) const { 2926 // If the type is not qualified with an address space, just return it 2927 // immediately. 2928 if (!T.hasAddressSpace()) 2929 return T; 2930 2931 // If we are composing extended qualifiers together, merge together 2932 // into one ExtQuals node. 2933 QualifierCollector Quals; 2934 const Type *TypeNode; 2935 2936 while (T.hasAddressSpace()) { 2937 TypeNode = Quals.strip(T); 2938 2939 // If the type no longer has an address space after stripping qualifiers, 2940 // jump out. 2941 if (!QualType(TypeNode, 0).hasAddressSpace()) 2942 break; 2943 2944 // There might be sugar in the way. Strip it and try again. 2945 T = T.getSingleStepDesugaredType(*this); 2946 } 2947 2948 Quals.removeAddressSpace(); 2949 2950 // Removal of the address space can mean there are no longer any 2951 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts) 2952 // or required. 2953 if (Quals.hasNonFastQualifiers()) 2954 return getExtQualType(TypeNode, Quals); 2955 else 2956 return QualType(TypeNode, Quals.getFastQualifiers()); 2957 } 2958 2959 QualType ASTContext::getObjCGCQualType(QualType T, 2960 Qualifiers::GC GCAttr) const { 2961 QualType CanT = getCanonicalType(T); 2962 if (CanT.getObjCGCAttr() == GCAttr) 2963 return T; 2964 2965 if (const auto *ptr = T->getAs<PointerType>()) { 2966 QualType Pointee = ptr->getPointeeType(); 2967 if (Pointee->isAnyPointerType()) { 2968 QualType ResultType = getObjCGCQualType(Pointee, GCAttr); 2969 return getPointerType(ResultType); 2970 } 2971 } 2972 2973 // If we are composing extended qualifiers together, merge together 2974 // into one ExtQuals node. 2975 QualifierCollector Quals; 2976 const Type *TypeNode = Quals.strip(T); 2977 2978 // If this type already has an ObjCGC specified, it cannot get 2979 // another one. 2980 assert(!Quals.hasObjCGCAttr() && 2981 "Type cannot have multiple ObjCGCs!"); 2982 Quals.addObjCGCAttr(GCAttr); 2983 2984 return getExtQualType(TypeNode, Quals); 2985 } 2986 2987 QualType ASTContext::removePtrSizeAddrSpace(QualType T) const { 2988 if (const PointerType *Ptr = T->getAs<PointerType>()) { 2989 QualType Pointee = Ptr->getPointeeType(); 2990 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) { 2991 return getPointerType(removeAddrSpaceQualType(Pointee)); 2992 } 2993 } 2994 return T; 2995 } 2996 2997 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T, 2998 FunctionType::ExtInfo Info) { 2999 if (T->getExtInfo() == Info) 3000 return T; 3001 3002 QualType Result; 3003 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) { 3004 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info); 3005 } else { 3006 const auto *FPT = cast<FunctionProtoType>(T); 3007 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 3008 EPI.ExtInfo = Info; 3009 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI); 3010 } 3011 3012 return cast<FunctionType>(Result.getTypePtr()); 3013 } 3014 3015 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD, 3016 QualType ResultType) { 3017 FD = FD->getMostRecentDecl(); 3018 while (true) { 3019 const auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 3020 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 3021 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI)); 3022 if (FunctionDecl *Next = FD->getPreviousDecl()) 3023 FD = Next; 3024 else 3025 break; 3026 } 3027 if (ASTMutationListener *L = getASTMutationListener()) 3028 L->DeducedReturnType(FD, ResultType); 3029 } 3030 3031 /// Get a function type and produce the equivalent function type with the 3032 /// specified exception specification. Type sugar that can be present on a 3033 /// declaration of a function with an exception specification is permitted 3034 /// and preserved. Other type sugar (for instance, typedefs) is not. 3035 QualType ASTContext::getFunctionTypeWithExceptionSpec( 3036 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) { 3037 // Might have some parens. 3038 if (const auto *PT = dyn_cast<ParenType>(Orig)) 3039 return getParenType( 3040 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI)); 3041 3042 // Might be wrapped in a macro qualified type. 3043 if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig)) 3044 return getMacroQualifiedType( 3045 getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI), 3046 MQT->getMacroIdentifier()); 3047 3048 // Might have a calling-convention attribute. 3049 if (const auto *AT = dyn_cast<AttributedType>(Orig)) 3050 return getAttributedType( 3051 AT->getAttrKind(), 3052 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI), 3053 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI)); 3054 3055 // Anything else must be a function type. Rebuild it with the new exception 3056 // specification. 3057 const auto *Proto = Orig->castAs<FunctionProtoType>(); 3058 return getFunctionType( 3059 Proto->getReturnType(), Proto->getParamTypes(), 3060 Proto->getExtProtoInfo().withExceptionSpec(ESI)); 3061 } 3062 3063 bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T, 3064 QualType U) { 3065 return hasSameType(T, U) || 3066 (getLangOpts().CPlusPlus17 && 3067 hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None), 3068 getFunctionTypeWithExceptionSpec(U, EST_None))); 3069 } 3070 3071 QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) { 3072 if (const auto *Proto = T->getAs<FunctionProtoType>()) { 3073 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType()); 3074 SmallVector<QualType, 16> Args(Proto->param_types()); 3075 for (unsigned i = 0, n = Args.size(); i != n; ++i) 3076 Args[i] = removePtrSizeAddrSpace(Args[i]); 3077 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo()); 3078 } 3079 3080 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) { 3081 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType()); 3082 return getFunctionNoProtoType(RetTy, Proto->getExtInfo()); 3083 } 3084 3085 return T; 3086 } 3087 3088 bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) { 3089 return hasSameType(T, U) || 3090 hasSameType(getFunctionTypeWithoutPtrSizes(T), 3091 getFunctionTypeWithoutPtrSizes(U)); 3092 } 3093 3094 void ASTContext::adjustExceptionSpec( 3095 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, 3096 bool AsWritten) { 3097 // Update the type. 3098 QualType Updated = 3099 getFunctionTypeWithExceptionSpec(FD->getType(), ESI); 3100 FD->setType(Updated); 3101 3102 if (!AsWritten) 3103 return; 3104 3105 // Update the type in the type source information too. 3106 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) { 3107 // If the type and the type-as-written differ, we may need to update 3108 // the type-as-written too. 3109 if (TSInfo->getType() != FD->getType()) 3110 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI); 3111 3112 // FIXME: When we get proper type location information for exceptions, 3113 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch 3114 // up the TypeSourceInfo; 3115 assert(TypeLoc::getFullDataSizeForType(Updated) == 3116 TypeLoc::getFullDataSizeForType(TSInfo->getType()) && 3117 "TypeLoc size mismatch from updating exception specification"); 3118 TSInfo->overrideType(Updated); 3119 } 3120 } 3121 3122 /// getComplexType - Return the uniqued reference to the type for a complex 3123 /// number with the specified element type. 3124 QualType ASTContext::getComplexType(QualType T) const { 3125 // Unique pointers, to guarantee there is only one pointer of a particular 3126 // structure. 3127 llvm::FoldingSetNodeID ID; 3128 ComplexType::Profile(ID, T); 3129 3130 void *InsertPos = nullptr; 3131 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos)) 3132 return QualType(CT, 0); 3133 3134 // If the pointee type isn't canonical, this won't be a canonical type either, 3135 // so fill in the canonical type field. 3136 QualType Canonical; 3137 if (!T.isCanonical()) { 3138 Canonical = getComplexType(getCanonicalType(T)); 3139 3140 // Get the new insert position for the node we care about. 3141 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos); 3142 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3143 } 3144 auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical); 3145 Types.push_back(New); 3146 ComplexTypes.InsertNode(New, InsertPos); 3147 return QualType(New, 0); 3148 } 3149 3150 /// getPointerType - Return the uniqued reference to the type for a pointer to 3151 /// the specified type. 3152 QualType ASTContext::getPointerType(QualType T) const { 3153 // Unique pointers, to guarantee there is only one pointer of a particular 3154 // structure. 3155 llvm::FoldingSetNodeID ID; 3156 PointerType::Profile(ID, T); 3157 3158 void *InsertPos = nullptr; 3159 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3160 return QualType(PT, 0); 3161 3162 // If the pointee type isn't canonical, this won't be a canonical type either, 3163 // so fill in the canonical type field. 3164 QualType Canonical; 3165 if (!T.isCanonical()) { 3166 Canonical = getPointerType(getCanonicalType(T)); 3167 3168 // Get the new insert position for the node we care about. 3169 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3170 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3171 } 3172 auto *New = new (*this, TypeAlignment) PointerType(T, Canonical); 3173 Types.push_back(New); 3174 PointerTypes.InsertNode(New, InsertPos); 3175 return QualType(New, 0); 3176 } 3177 3178 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const { 3179 llvm::FoldingSetNodeID ID; 3180 AdjustedType::Profile(ID, Orig, New); 3181 void *InsertPos = nullptr; 3182 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3183 if (AT) 3184 return QualType(AT, 0); 3185 3186 QualType Canonical = getCanonicalType(New); 3187 3188 // Get the new insert position for the node we care about. 3189 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3190 assert(!AT && "Shouldn't be in the map!"); 3191 3192 AT = new (*this, TypeAlignment) 3193 AdjustedType(Type::Adjusted, Orig, New, Canonical); 3194 Types.push_back(AT); 3195 AdjustedTypes.InsertNode(AT, InsertPos); 3196 return QualType(AT, 0); 3197 } 3198 3199 QualType ASTContext::getDecayedType(QualType T) const { 3200 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay"); 3201 3202 QualType Decayed; 3203 3204 // C99 6.7.5.3p7: 3205 // A declaration of a parameter as "array of type" shall be 3206 // adjusted to "qualified pointer to type", where the type 3207 // qualifiers (if any) are those specified within the [ and ] of 3208 // the array type derivation. 3209 if (T->isArrayType()) 3210 Decayed = getArrayDecayedType(T); 3211 3212 // C99 6.7.5.3p8: 3213 // A declaration of a parameter as "function returning type" 3214 // shall be adjusted to "pointer to function returning type", as 3215 // in 6.3.2.1. 3216 if (T->isFunctionType()) 3217 Decayed = getPointerType(T); 3218 3219 llvm::FoldingSetNodeID ID; 3220 AdjustedType::Profile(ID, T, Decayed); 3221 void *InsertPos = nullptr; 3222 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3223 if (AT) 3224 return QualType(AT, 0); 3225 3226 QualType Canonical = getCanonicalType(Decayed); 3227 3228 // Get the new insert position for the node we care about. 3229 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3230 assert(!AT && "Shouldn't be in the map!"); 3231 3232 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical); 3233 Types.push_back(AT); 3234 AdjustedTypes.InsertNode(AT, InsertPos); 3235 return QualType(AT, 0); 3236 } 3237 3238 /// getBlockPointerType - Return the uniqued reference to the type for 3239 /// a pointer to the specified block. 3240 QualType ASTContext::getBlockPointerType(QualType T) const { 3241 assert(T->isFunctionType() && "block of function types only"); 3242 // Unique pointers, to guarantee there is only one block of a particular 3243 // structure. 3244 llvm::FoldingSetNodeID ID; 3245 BlockPointerType::Profile(ID, T); 3246 3247 void *InsertPos = nullptr; 3248 if (BlockPointerType *PT = 3249 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3250 return QualType(PT, 0); 3251 3252 // If the block pointee type isn't canonical, this won't be a canonical 3253 // type either so fill in the canonical type field. 3254 QualType Canonical; 3255 if (!T.isCanonical()) { 3256 Canonical = getBlockPointerType(getCanonicalType(T)); 3257 3258 // Get the new insert position for the node we care about. 3259 BlockPointerType *NewIP = 3260 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3261 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3262 } 3263 auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical); 3264 Types.push_back(New); 3265 BlockPointerTypes.InsertNode(New, InsertPos); 3266 return QualType(New, 0); 3267 } 3268 3269 /// getLValueReferenceType - Return the uniqued reference to the type for an 3270 /// lvalue reference to the specified type. 3271 QualType 3272 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const { 3273 assert(getCanonicalType(T) != OverloadTy && 3274 "Unresolved overloaded function type"); 3275 3276 // Unique pointers, to guarantee there is only one pointer of a particular 3277 // structure. 3278 llvm::FoldingSetNodeID ID; 3279 ReferenceType::Profile(ID, T, SpelledAsLValue); 3280 3281 void *InsertPos = nullptr; 3282 if (LValueReferenceType *RT = 3283 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 3284 return QualType(RT, 0); 3285 3286 const auto *InnerRef = T->getAs<ReferenceType>(); 3287 3288 // If the referencee type isn't canonical, this won't be a canonical type 3289 // either, so fill in the canonical type field. 3290 QualType Canonical; 3291 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) { 3292 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 3293 Canonical = getLValueReferenceType(getCanonicalType(PointeeType)); 3294 3295 // Get the new insert position for the node we care about. 3296 LValueReferenceType *NewIP = 3297 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 3298 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3299 } 3300 3301 auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical, 3302 SpelledAsLValue); 3303 Types.push_back(New); 3304 LValueReferenceTypes.InsertNode(New, InsertPos); 3305 3306 return QualType(New, 0); 3307 } 3308 3309 /// getRValueReferenceType - Return the uniqued reference to the type for an 3310 /// rvalue reference to the specified type. 3311 QualType ASTContext::getRValueReferenceType(QualType T) const { 3312 // Unique pointers, to guarantee there is only one pointer of a particular 3313 // structure. 3314 llvm::FoldingSetNodeID ID; 3315 ReferenceType::Profile(ID, T, false); 3316 3317 void *InsertPos = nullptr; 3318 if (RValueReferenceType *RT = 3319 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 3320 return QualType(RT, 0); 3321 3322 const auto *InnerRef = T->getAs<ReferenceType>(); 3323 3324 // If the referencee type isn't canonical, this won't be a canonical type 3325 // either, so fill in the canonical type field. 3326 QualType Canonical; 3327 if (InnerRef || !T.isCanonical()) { 3328 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 3329 Canonical = getRValueReferenceType(getCanonicalType(PointeeType)); 3330 3331 // Get the new insert position for the node we care about. 3332 RValueReferenceType *NewIP = 3333 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 3334 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3335 } 3336 3337 auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical); 3338 Types.push_back(New); 3339 RValueReferenceTypes.InsertNode(New, InsertPos); 3340 return QualType(New, 0); 3341 } 3342 3343 /// getMemberPointerType - Return the uniqued reference to the type for a 3344 /// member pointer to the specified type, in the specified class. 3345 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const { 3346 // Unique pointers, to guarantee there is only one pointer of a particular 3347 // structure. 3348 llvm::FoldingSetNodeID ID; 3349 MemberPointerType::Profile(ID, T, Cls); 3350 3351 void *InsertPos = nullptr; 3352 if (MemberPointerType *PT = 3353 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3354 return QualType(PT, 0); 3355 3356 // If the pointee or class type isn't canonical, this won't be a canonical 3357 // type either, so fill in the canonical type field. 3358 QualType Canonical; 3359 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) { 3360 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls)); 3361 3362 // Get the new insert position for the node we care about. 3363 MemberPointerType *NewIP = 3364 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3365 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3366 } 3367 auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical); 3368 Types.push_back(New); 3369 MemberPointerTypes.InsertNode(New, InsertPos); 3370 return QualType(New, 0); 3371 } 3372 3373 /// getConstantArrayType - Return the unique reference to the type for an 3374 /// array of the specified element type. 3375 QualType ASTContext::getConstantArrayType(QualType EltTy, 3376 const llvm::APInt &ArySizeIn, 3377 const Expr *SizeExpr, 3378 ArrayType::ArraySizeModifier ASM, 3379 unsigned IndexTypeQuals) const { 3380 assert((EltTy->isDependentType() || 3381 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) && 3382 "Constant array of VLAs is illegal!"); 3383 3384 // We only need the size as part of the type if it's instantiation-dependent. 3385 if (SizeExpr && !SizeExpr->isInstantiationDependent()) 3386 SizeExpr = nullptr; 3387 3388 // Convert the array size into a canonical width matching the pointer size for 3389 // the target. 3390 llvm::APInt ArySize(ArySizeIn); 3391 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth()); 3392 3393 llvm::FoldingSetNodeID ID; 3394 ConstantArrayType::Profile(ID, *this, EltTy, ArySize, SizeExpr, ASM, 3395 IndexTypeQuals); 3396 3397 void *InsertPos = nullptr; 3398 if (ConstantArrayType *ATP = 3399 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 3400 return QualType(ATP, 0); 3401 3402 // If the element type isn't canonical or has qualifiers, or the array bound 3403 // is instantiation-dependent, this won't be a canonical type either, so fill 3404 // in the canonical type field. 3405 QualType Canon; 3406 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) { 3407 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 3408 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr, 3409 ASM, IndexTypeQuals); 3410 Canon = getQualifiedType(Canon, canonSplit.Quals); 3411 3412 // Get the new insert position for the node we care about. 3413 ConstantArrayType *NewIP = 3414 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 3415 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3416 } 3417 3418 void *Mem = Allocate( 3419 ConstantArrayType::totalSizeToAlloc<const Expr *>(SizeExpr ? 1 : 0), 3420 TypeAlignment); 3421 auto *New = new (Mem) 3422 ConstantArrayType(EltTy, Canon, ArySize, SizeExpr, ASM, IndexTypeQuals); 3423 ConstantArrayTypes.InsertNode(New, InsertPos); 3424 Types.push_back(New); 3425 return QualType(New, 0); 3426 } 3427 3428 /// getVariableArrayDecayedType - Turns the given type, which may be 3429 /// variably-modified, into the corresponding type with all the known 3430 /// sizes replaced with [*]. 3431 QualType ASTContext::getVariableArrayDecayedType(QualType type) const { 3432 // Vastly most common case. 3433 if (!type->isVariablyModifiedType()) return type; 3434 3435 QualType result; 3436 3437 SplitQualType split = type.getSplitDesugaredType(); 3438 const Type *ty = split.Ty; 3439 switch (ty->getTypeClass()) { 3440 #define TYPE(Class, Base) 3441 #define ABSTRACT_TYPE(Class, Base) 3442 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 3443 #include "clang/AST/TypeNodes.inc" 3444 llvm_unreachable("didn't desugar past all non-canonical types?"); 3445 3446 // These types should never be variably-modified. 3447 case Type::Builtin: 3448 case Type::Complex: 3449 case Type::Vector: 3450 case Type::DependentVector: 3451 case Type::ExtVector: 3452 case Type::DependentSizedExtVector: 3453 case Type::ConstantMatrix: 3454 case Type::DependentSizedMatrix: 3455 case Type::DependentAddressSpace: 3456 case Type::ObjCObject: 3457 case Type::ObjCInterface: 3458 case Type::ObjCObjectPointer: 3459 case Type::Record: 3460 case Type::Enum: 3461 case Type::UnresolvedUsing: 3462 case Type::TypeOfExpr: 3463 case Type::TypeOf: 3464 case Type::Decltype: 3465 case Type::UnaryTransform: 3466 case Type::DependentName: 3467 case Type::InjectedClassName: 3468 case Type::TemplateSpecialization: 3469 case Type::DependentTemplateSpecialization: 3470 case Type::TemplateTypeParm: 3471 case Type::SubstTemplateTypeParmPack: 3472 case Type::Auto: 3473 case Type::DeducedTemplateSpecialization: 3474 case Type::PackExpansion: 3475 case Type::ExtInt: 3476 case Type::DependentExtInt: 3477 llvm_unreachable("type should never be variably-modified"); 3478 3479 // These types can be variably-modified but should never need to 3480 // further decay. 3481 case Type::FunctionNoProto: 3482 case Type::FunctionProto: 3483 case Type::BlockPointer: 3484 case Type::MemberPointer: 3485 case Type::Pipe: 3486 return type; 3487 3488 // These types can be variably-modified. All these modifications 3489 // preserve structure except as noted by comments. 3490 // TODO: if we ever care about optimizing VLAs, there are no-op 3491 // optimizations available here. 3492 case Type::Pointer: 3493 result = getPointerType(getVariableArrayDecayedType( 3494 cast<PointerType>(ty)->getPointeeType())); 3495 break; 3496 3497 case Type::LValueReference: { 3498 const auto *lv = cast<LValueReferenceType>(ty); 3499 result = getLValueReferenceType( 3500 getVariableArrayDecayedType(lv->getPointeeType()), 3501 lv->isSpelledAsLValue()); 3502 break; 3503 } 3504 3505 case Type::RValueReference: { 3506 const auto *lv = cast<RValueReferenceType>(ty); 3507 result = getRValueReferenceType( 3508 getVariableArrayDecayedType(lv->getPointeeType())); 3509 break; 3510 } 3511 3512 case Type::Atomic: { 3513 const auto *at = cast<AtomicType>(ty); 3514 result = getAtomicType(getVariableArrayDecayedType(at->getValueType())); 3515 break; 3516 } 3517 3518 case Type::ConstantArray: { 3519 const auto *cat = cast<ConstantArrayType>(ty); 3520 result = getConstantArrayType( 3521 getVariableArrayDecayedType(cat->getElementType()), 3522 cat->getSize(), 3523 cat->getSizeExpr(), 3524 cat->getSizeModifier(), 3525 cat->getIndexTypeCVRQualifiers()); 3526 break; 3527 } 3528 3529 case Type::DependentSizedArray: { 3530 const auto *dat = cast<DependentSizedArrayType>(ty); 3531 result = getDependentSizedArrayType( 3532 getVariableArrayDecayedType(dat->getElementType()), 3533 dat->getSizeExpr(), 3534 dat->getSizeModifier(), 3535 dat->getIndexTypeCVRQualifiers(), 3536 dat->getBracketsRange()); 3537 break; 3538 } 3539 3540 // Turn incomplete types into [*] types. 3541 case Type::IncompleteArray: { 3542 const auto *iat = cast<IncompleteArrayType>(ty); 3543 result = getVariableArrayType( 3544 getVariableArrayDecayedType(iat->getElementType()), 3545 /*size*/ nullptr, 3546 ArrayType::Normal, 3547 iat->getIndexTypeCVRQualifiers(), 3548 SourceRange()); 3549 break; 3550 } 3551 3552 // Turn VLA types into [*] types. 3553 case Type::VariableArray: { 3554 const auto *vat = cast<VariableArrayType>(ty); 3555 result = getVariableArrayType( 3556 getVariableArrayDecayedType(vat->getElementType()), 3557 /*size*/ nullptr, 3558 ArrayType::Star, 3559 vat->getIndexTypeCVRQualifiers(), 3560 vat->getBracketsRange()); 3561 break; 3562 } 3563 } 3564 3565 // Apply the top-level qualifiers from the original. 3566 return getQualifiedType(result, split.Quals); 3567 } 3568 3569 /// getVariableArrayType - Returns a non-unique reference to the type for a 3570 /// variable array of the specified element type. 3571 QualType ASTContext::getVariableArrayType(QualType EltTy, 3572 Expr *NumElts, 3573 ArrayType::ArraySizeModifier ASM, 3574 unsigned IndexTypeQuals, 3575 SourceRange Brackets) const { 3576 // Since we don't unique expressions, it isn't possible to unique VLA's 3577 // that have an expression provided for their size. 3578 QualType Canon; 3579 3580 // Be sure to pull qualifiers off the element type. 3581 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) { 3582 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 3583 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM, 3584 IndexTypeQuals, Brackets); 3585 Canon = getQualifiedType(Canon, canonSplit.Quals); 3586 } 3587 3588 auto *New = new (*this, TypeAlignment) 3589 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets); 3590 3591 VariableArrayTypes.push_back(New); 3592 Types.push_back(New); 3593 return QualType(New, 0); 3594 } 3595 3596 /// getDependentSizedArrayType - Returns a non-unique reference to 3597 /// the type for a dependently-sized array of the specified element 3598 /// type. 3599 QualType ASTContext::getDependentSizedArrayType(QualType elementType, 3600 Expr *numElements, 3601 ArrayType::ArraySizeModifier ASM, 3602 unsigned elementTypeQuals, 3603 SourceRange brackets) const { 3604 assert((!numElements || numElements->isTypeDependent() || 3605 numElements->isValueDependent()) && 3606 "Size must be type- or value-dependent!"); 3607 3608 // Dependently-sized array types that do not have a specified number 3609 // of elements will have their sizes deduced from a dependent 3610 // initializer. We do no canonicalization here at all, which is okay 3611 // because they can't be used in most locations. 3612 if (!numElements) { 3613 auto *newType 3614 = new (*this, TypeAlignment) 3615 DependentSizedArrayType(*this, elementType, QualType(), 3616 numElements, ASM, elementTypeQuals, 3617 brackets); 3618 Types.push_back(newType); 3619 return QualType(newType, 0); 3620 } 3621 3622 // Otherwise, we actually build a new type every time, but we 3623 // also build a canonical type. 3624 3625 SplitQualType canonElementType = getCanonicalType(elementType).split(); 3626 3627 void *insertPos = nullptr; 3628 llvm::FoldingSetNodeID ID; 3629 DependentSizedArrayType::Profile(ID, *this, 3630 QualType(canonElementType.Ty, 0), 3631 ASM, elementTypeQuals, numElements); 3632 3633 // Look for an existing type with these properties. 3634 DependentSizedArrayType *canonTy = 3635 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos); 3636 3637 // If we don't have one, build one. 3638 if (!canonTy) { 3639 canonTy = new (*this, TypeAlignment) 3640 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0), 3641 QualType(), numElements, ASM, elementTypeQuals, 3642 brackets); 3643 DependentSizedArrayTypes.InsertNode(canonTy, insertPos); 3644 Types.push_back(canonTy); 3645 } 3646 3647 // Apply qualifiers from the element type to the array. 3648 QualType canon = getQualifiedType(QualType(canonTy,0), 3649 canonElementType.Quals); 3650 3651 // If we didn't need extra canonicalization for the element type or the size 3652 // expression, then just use that as our result. 3653 if (QualType(canonElementType.Ty, 0) == elementType && 3654 canonTy->getSizeExpr() == numElements) 3655 return canon; 3656 3657 // Otherwise, we need to build a type which follows the spelling 3658 // of the element type. 3659 auto *sugaredType 3660 = new (*this, TypeAlignment) 3661 DependentSizedArrayType(*this, elementType, canon, numElements, 3662 ASM, elementTypeQuals, brackets); 3663 Types.push_back(sugaredType); 3664 return QualType(sugaredType, 0); 3665 } 3666 3667 QualType ASTContext::getIncompleteArrayType(QualType elementType, 3668 ArrayType::ArraySizeModifier ASM, 3669 unsigned elementTypeQuals) const { 3670 llvm::FoldingSetNodeID ID; 3671 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals); 3672 3673 void *insertPos = nullptr; 3674 if (IncompleteArrayType *iat = 3675 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos)) 3676 return QualType(iat, 0); 3677 3678 // If the element type isn't canonical, this won't be a canonical type 3679 // either, so fill in the canonical type field. We also have to pull 3680 // qualifiers off the element type. 3681 QualType canon; 3682 3683 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) { 3684 SplitQualType canonSplit = getCanonicalType(elementType).split(); 3685 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0), 3686 ASM, elementTypeQuals); 3687 canon = getQualifiedType(canon, canonSplit.Quals); 3688 3689 // Get the new insert position for the node we care about. 3690 IncompleteArrayType *existing = 3691 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos); 3692 assert(!existing && "Shouldn't be in the map!"); (void) existing; 3693 } 3694 3695 auto *newType = new (*this, TypeAlignment) 3696 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals); 3697 3698 IncompleteArrayTypes.InsertNode(newType, insertPos); 3699 Types.push_back(newType); 3700 return QualType(newType, 0); 3701 } 3702 3703 ASTContext::BuiltinVectorTypeInfo 3704 ASTContext::getBuiltinVectorTypeInfo(const BuiltinType *Ty) const { 3705 #define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \ 3706 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \ 3707 NUMVECTORS}; 3708 3709 #define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \ 3710 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS}; 3711 3712 switch (Ty->getKind()) { 3713 default: 3714 llvm_unreachable("Unsupported builtin vector type"); 3715 case BuiltinType::SveInt8: 3716 return SVE_INT_ELTTY(8, 16, true, 1); 3717 case BuiltinType::SveUint8: 3718 return SVE_INT_ELTTY(8, 16, false, 1); 3719 case BuiltinType::SveInt8x2: 3720 return SVE_INT_ELTTY(8, 16, true, 2); 3721 case BuiltinType::SveUint8x2: 3722 return SVE_INT_ELTTY(8, 16, false, 2); 3723 case BuiltinType::SveInt8x3: 3724 return SVE_INT_ELTTY(8, 16, true, 3); 3725 case BuiltinType::SveUint8x3: 3726 return SVE_INT_ELTTY(8, 16, false, 3); 3727 case BuiltinType::SveInt8x4: 3728 return SVE_INT_ELTTY(8, 16, true, 4); 3729 case BuiltinType::SveUint8x4: 3730 return SVE_INT_ELTTY(8, 16, false, 4); 3731 case BuiltinType::SveInt16: 3732 return SVE_INT_ELTTY(16, 8, true, 1); 3733 case BuiltinType::SveUint16: 3734 return SVE_INT_ELTTY(16, 8, false, 1); 3735 case BuiltinType::SveInt16x2: 3736 return SVE_INT_ELTTY(16, 8, true, 2); 3737 case BuiltinType::SveUint16x2: 3738 return SVE_INT_ELTTY(16, 8, false, 2); 3739 case BuiltinType::SveInt16x3: 3740 return SVE_INT_ELTTY(16, 8, true, 3); 3741 case BuiltinType::SveUint16x3: 3742 return SVE_INT_ELTTY(16, 8, false, 3); 3743 case BuiltinType::SveInt16x4: 3744 return SVE_INT_ELTTY(16, 8, true, 4); 3745 case BuiltinType::SveUint16x4: 3746 return SVE_INT_ELTTY(16, 8, false, 4); 3747 case BuiltinType::SveInt32: 3748 return SVE_INT_ELTTY(32, 4, true, 1); 3749 case BuiltinType::SveUint32: 3750 return SVE_INT_ELTTY(32, 4, false, 1); 3751 case BuiltinType::SveInt32x2: 3752 return SVE_INT_ELTTY(32, 4, true, 2); 3753 case BuiltinType::SveUint32x2: 3754 return SVE_INT_ELTTY(32, 4, false, 2); 3755 case BuiltinType::SveInt32x3: 3756 return SVE_INT_ELTTY(32, 4, true, 3); 3757 case BuiltinType::SveUint32x3: 3758 return SVE_INT_ELTTY(32, 4, false, 3); 3759 case BuiltinType::SveInt32x4: 3760 return SVE_INT_ELTTY(32, 4, true, 4); 3761 case BuiltinType::SveUint32x4: 3762 return SVE_INT_ELTTY(32, 4, false, 4); 3763 case BuiltinType::SveInt64: 3764 return SVE_INT_ELTTY(64, 2, true, 1); 3765 case BuiltinType::SveUint64: 3766 return SVE_INT_ELTTY(64, 2, false, 1); 3767 case BuiltinType::SveInt64x2: 3768 return SVE_INT_ELTTY(64, 2, true, 2); 3769 case BuiltinType::SveUint64x2: 3770 return SVE_INT_ELTTY(64, 2, false, 2); 3771 case BuiltinType::SveInt64x3: 3772 return SVE_INT_ELTTY(64, 2, true, 3); 3773 case BuiltinType::SveUint64x3: 3774 return SVE_INT_ELTTY(64, 2, false, 3); 3775 case BuiltinType::SveInt64x4: 3776 return SVE_INT_ELTTY(64, 2, true, 4); 3777 case BuiltinType::SveUint64x4: 3778 return SVE_INT_ELTTY(64, 2, false, 4); 3779 case BuiltinType::SveBool: 3780 return SVE_ELTTY(BoolTy, 16, 1); 3781 case BuiltinType::SveFloat16: 3782 return SVE_ELTTY(HalfTy, 8, 1); 3783 case BuiltinType::SveFloat16x2: 3784 return SVE_ELTTY(HalfTy, 8, 2); 3785 case BuiltinType::SveFloat16x3: 3786 return SVE_ELTTY(HalfTy, 8, 3); 3787 case BuiltinType::SveFloat16x4: 3788 return SVE_ELTTY(HalfTy, 8, 4); 3789 case BuiltinType::SveFloat32: 3790 return SVE_ELTTY(FloatTy, 4, 1); 3791 case BuiltinType::SveFloat32x2: 3792 return SVE_ELTTY(FloatTy, 4, 2); 3793 case BuiltinType::SveFloat32x3: 3794 return SVE_ELTTY(FloatTy, 4, 3); 3795 case BuiltinType::SveFloat32x4: 3796 return SVE_ELTTY(FloatTy, 4, 4); 3797 case BuiltinType::SveFloat64: 3798 return SVE_ELTTY(DoubleTy, 2, 1); 3799 case BuiltinType::SveFloat64x2: 3800 return SVE_ELTTY(DoubleTy, 2, 2); 3801 case BuiltinType::SveFloat64x3: 3802 return SVE_ELTTY(DoubleTy, 2, 3); 3803 case BuiltinType::SveFloat64x4: 3804 return SVE_ELTTY(DoubleTy, 2, 4); 3805 case BuiltinType::SveBFloat16: 3806 return SVE_ELTTY(BFloat16Ty, 8, 1); 3807 case BuiltinType::SveBFloat16x2: 3808 return SVE_ELTTY(BFloat16Ty, 8, 2); 3809 case BuiltinType::SveBFloat16x3: 3810 return SVE_ELTTY(BFloat16Ty, 8, 3); 3811 case BuiltinType::SveBFloat16x4: 3812 return SVE_ELTTY(BFloat16Ty, 8, 4); 3813 } 3814 } 3815 3816 /// getScalableVectorType - Return the unique reference to a scalable vector 3817 /// type of the specified element type and size. VectorType must be a built-in 3818 /// type. 3819 QualType ASTContext::getScalableVectorType(QualType EltTy, 3820 unsigned NumElts) const { 3821 if (Target->hasAArch64SVETypes()) { 3822 uint64_t EltTySize = getTypeSize(EltTy); 3823 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \ 3824 IsSigned, IsFP, IsBF) \ 3825 if (!EltTy->isBooleanType() && \ 3826 ((EltTy->hasIntegerRepresentation() && \ 3827 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \ 3828 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \ 3829 IsFP && !IsBF) || \ 3830 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \ 3831 IsBF && !IsFP)) && \ 3832 EltTySize == ElBits && NumElts == NumEls) { \ 3833 return SingletonId; \ 3834 } 3835 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \ 3836 if (EltTy->isBooleanType() && NumElts == NumEls) \ 3837 return SingletonId; 3838 #include "clang/Basic/AArch64SVEACLETypes.def" 3839 } 3840 return QualType(); 3841 } 3842 3843 /// getVectorType - Return the unique reference to a vector type of 3844 /// the specified element type and size. VectorType must be a built-in type. 3845 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts, 3846 VectorType::VectorKind VecKind) const { 3847 assert(vecType->isBuiltinType()); 3848 3849 // Check if we've already instantiated a vector of this type. 3850 llvm::FoldingSetNodeID ID; 3851 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind); 3852 3853 void *InsertPos = nullptr; 3854 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 3855 return QualType(VTP, 0); 3856 3857 // If the element type isn't canonical, this won't be a canonical type either, 3858 // so fill in the canonical type field. 3859 QualType Canonical; 3860 if (!vecType.isCanonical()) { 3861 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind); 3862 3863 // Get the new insert position for the node we care about. 3864 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3865 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3866 } 3867 auto *New = new (*this, TypeAlignment) 3868 VectorType(vecType, NumElts, Canonical, VecKind); 3869 VectorTypes.InsertNode(New, InsertPos); 3870 Types.push_back(New); 3871 return QualType(New, 0); 3872 } 3873 3874 QualType 3875 ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr, 3876 SourceLocation AttrLoc, 3877 VectorType::VectorKind VecKind) const { 3878 llvm::FoldingSetNodeID ID; 3879 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr, 3880 VecKind); 3881 void *InsertPos = nullptr; 3882 DependentVectorType *Canon = 3883 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3884 DependentVectorType *New; 3885 3886 if (Canon) { 3887 New = new (*this, TypeAlignment) DependentVectorType( 3888 *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind); 3889 } else { 3890 QualType CanonVecTy = getCanonicalType(VecType); 3891 if (CanonVecTy == VecType) { 3892 New = new (*this, TypeAlignment) DependentVectorType( 3893 *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind); 3894 3895 DependentVectorType *CanonCheck = 3896 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3897 assert(!CanonCheck && 3898 "Dependent-sized vector_size canonical type broken"); 3899 (void)CanonCheck; 3900 DependentVectorTypes.InsertNode(New, InsertPos); 3901 } else { 3902 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr, 3903 SourceLocation(), VecKind); 3904 New = new (*this, TypeAlignment) DependentVectorType( 3905 *this, VecType, CanonTy, SizeExpr, AttrLoc, VecKind); 3906 } 3907 } 3908 3909 Types.push_back(New); 3910 return QualType(New, 0); 3911 } 3912 3913 /// getExtVectorType - Return the unique reference to an extended vector type of 3914 /// the specified element type and size. VectorType must be a built-in type. 3915 QualType 3916 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const { 3917 assert(vecType->isBuiltinType() || vecType->isDependentType()); 3918 3919 // Check if we've already instantiated a vector of this type. 3920 llvm::FoldingSetNodeID ID; 3921 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, 3922 VectorType::GenericVector); 3923 void *InsertPos = nullptr; 3924 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 3925 return QualType(VTP, 0); 3926 3927 // If the element type isn't canonical, this won't be a canonical type either, 3928 // so fill in the canonical type field. 3929 QualType Canonical; 3930 if (!vecType.isCanonical()) { 3931 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts); 3932 3933 // Get the new insert position for the node we care about. 3934 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3935 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3936 } 3937 auto *New = new (*this, TypeAlignment) 3938 ExtVectorType(vecType, NumElts, Canonical); 3939 VectorTypes.InsertNode(New, InsertPos); 3940 Types.push_back(New); 3941 return QualType(New, 0); 3942 } 3943 3944 QualType 3945 ASTContext::getDependentSizedExtVectorType(QualType vecType, 3946 Expr *SizeExpr, 3947 SourceLocation AttrLoc) const { 3948 llvm::FoldingSetNodeID ID; 3949 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType), 3950 SizeExpr); 3951 3952 void *InsertPos = nullptr; 3953 DependentSizedExtVectorType *Canon 3954 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3955 DependentSizedExtVectorType *New; 3956 if (Canon) { 3957 // We already have a canonical version of this array type; use it as 3958 // the canonical type for a newly-built type. 3959 New = new (*this, TypeAlignment) 3960 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0), 3961 SizeExpr, AttrLoc); 3962 } else { 3963 QualType CanonVecTy = getCanonicalType(vecType); 3964 if (CanonVecTy == vecType) { 3965 New = new (*this, TypeAlignment) 3966 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr, 3967 AttrLoc); 3968 3969 DependentSizedExtVectorType *CanonCheck 3970 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3971 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken"); 3972 (void)CanonCheck; 3973 DependentSizedExtVectorTypes.InsertNode(New, InsertPos); 3974 } else { 3975 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr, 3976 SourceLocation()); 3977 New = new (*this, TypeAlignment) DependentSizedExtVectorType( 3978 *this, vecType, CanonExtTy, SizeExpr, AttrLoc); 3979 } 3980 } 3981 3982 Types.push_back(New); 3983 return QualType(New, 0); 3984 } 3985 3986 QualType ASTContext::getConstantMatrixType(QualType ElementTy, unsigned NumRows, 3987 unsigned NumColumns) const { 3988 llvm::FoldingSetNodeID ID; 3989 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns, 3990 Type::ConstantMatrix); 3991 3992 assert(MatrixType::isValidElementType(ElementTy) && 3993 "need a valid element type"); 3994 assert(ConstantMatrixType::isDimensionValid(NumRows) && 3995 ConstantMatrixType::isDimensionValid(NumColumns) && 3996 "need valid matrix dimensions"); 3997 void *InsertPos = nullptr; 3998 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos)) 3999 return QualType(MTP, 0); 4000 4001 QualType Canonical; 4002 if (!ElementTy.isCanonical()) { 4003 Canonical = 4004 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns); 4005 4006 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos); 4007 assert(!NewIP && "Matrix type shouldn't already exist in the map"); 4008 (void)NewIP; 4009 } 4010 4011 auto *New = new (*this, TypeAlignment) 4012 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical); 4013 MatrixTypes.InsertNode(New, InsertPos); 4014 Types.push_back(New); 4015 return QualType(New, 0); 4016 } 4017 4018 QualType ASTContext::getDependentSizedMatrixType(QualType ElementTy, 4019 Expr *RowExpr, 4020 Expr *ColumnExpr, 4021 SourceLocation AttrLoc) const { 4022 QualType CanonElementTy = getCanonicalType(ElementTy); 4023 llvm::FoldingSetNodeID ID; 4024 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr, 4025 ColumnExpr); 4026 4027 void *InsertPos = nullptr; 4028 DependentSizedMatrixType *Canon = 4029 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos); 4030 4031 if (!Canon) { 4032 Canon = new (*this, TypeAlignment) DependentSizedMatrixType( 4033 *this, CanonElementTy, QualType(), RowExpr, ColumnExpr, AttrLoc); 4034 #ifndef NDEBUG 4035 DependentSizedMatrixType *CanonCheck = 4036 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos); 4037 assert(!CanonCheck && "Dependent-sized matrix canonical type broken"); 4038 #endif 4039 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos); 4040 Types.push_back(Canon); 4041 } 4042 4043 // Already have a canonical version of the matrix type 4044 // 4045 // If it exactly matches the requested type, use it directly. 4046 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr && 4047 Canon->getRowExpr() == ColumnExpr) 4048 return QualType(Canon, 0); 4049 4050 // Use Canon as the canonical type for newly-built type. 4051 DependentSizedMatrixType *New = new (*this, TypeAlignment) 4052 DependentSizedMatrixType(*this, ElementTy, QualType(Canon, 0), RowExpr, 4053 ColumnExpr, AttrLoc); 4054 Types.push_back(New); 4055 return QualType(New, 0); 4056 } 4057 4058 QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType, 4059 Expr *AddrSpaceExpr, 4060 SourceLocation AttrLoc) const { 4061 assert(AddrSpaceExpr->isInstantiationDependent()); 4062 4063 QualType canonPointeeType = getCanonicalType(PointeeType); 4064 4065 void *insertPos = nullptr; 4066 llvm::FoldingSetNodeID ID; 4067 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType, 4068 AddrSpaceExpr); 4069 4070 DependentAddressSpaceType *canonTy = 4071 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos); 4072 4073 if (!canonTy) { 4074 canonTy = new (*this, TypeAlignment) 4075 DependentAddressSpaceType(*this, canonPointeeType, 4076 QualType(), AddrSpaceExpr, AttrLoc); 4077 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos); 4078 Types.push_back(canonTy); 4079 } 4080 4081 if (canonPointeeType == PointeeType && 4082 canonTy->getAddrSpaceExpr() == AddrSpaceExpr) 4083 return QualType(canonTy, 0); 4084 4085 auto *sugaredType 4086 = new (*this, TypeAlignment) 4087 DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0), 4088 AddrSpaceExpr, AttrLoc); 4089 Types.push_back(sugaredType); 4090 return QualType(sugaredType, 0); 4091 } 4092 4093 /// Determine whether \p T is canonical as the result type of a function. 4094 static bool isCanonicalResultType(QualType T) { 4095 return T.isCanonical() && 4096 (T.getObjCLifetime() == Qualifiers::OCL_None || 4097 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone); 4098 } 4099 4100 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'. 4101 QualType 4102 ASTContext::getFunctionNoProtoType(QualType ResultTy, 4103 const FunctionType::ExtInfo &Info) const { 4104 // Unique functions, to guarantee there is only one function of a particular 4105 // structure. 4106 llvm::FoldingSetNodeID ID; 4107 FunctionNoProtoType::Profile(ID, ResultTy, Info); 4108 4109 void *InsertPos = nullptr; 4110 if (FunctionNoProtoType *FT = 4111 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 4112 return QualType(FT, 0); 4113 4114 QualType Canonical; 4115 if (!isCanonicalResultType(ResultTy)) { 4116 Canonical = 4117 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info); 4118 4119 // Get the new insert position for the node we care about. 4120 FunctionNoProtoType *NewIP = 4121 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 4122 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4123 } 4124 4125 auto *New = new (*this, TypeAlignment) 4126 FunctionNoProtoType(ResultTy, Canonical, Info); 4127 Types.push_back(New); 4128 FunctionNoProtoTypes.InsertNode(New, InsertPos); 4129 return QualType(New, 0); 4130 } 4131 4132 CanQualType 4133 ASTContext::getCanonicalFunctionResultType(QualType ResultType) const { 4134 CanQualType CanResultType = getCanonicalType(ResultType); 4135 4136 // Canonical result types do not have ARC lifetime qualifiers. 4137 if (CanResultType.getQualifiers().hasObjCLifetime()) { 4138 Qualifiers Qs = CanResultType.getQualifiers(); 4139 Qs.removeObjCLifetime(); 4140 return CanQualType::CreateUnsafe( 4141 getQualifiedType(CanResultType.getUnqualifiedType(), Qs)); 4142 } 4143 4144 return CanResultType; 4145 } 4146 4147 static bool isCanonicalExceptionSpecification( 4148 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) { 4149 if (ESI.Type == EST_None) 4150 return true; 4151 if (!NoexceptInType) 4152 return false; 4153 4154 // C++17 onwards: exception specification is part of the type, as a simple 4155 // boolean "can this function type throw". 4156 if (ESI.Type == EST_BasicNoexcept) 4157 return true; 4158 4159 // A noexcept(expr) specification is (possibly) canonical if expr is 4160 // value-dependent. 4161 if (ESI.Type == EST_DependentNoexcept) 4162 return true; 4163 4164 // A dynamic exception specification is canonical if it only contains pack 4165 // expansions (so we can't tell whether it's non-throwing) and all its 4166 // contained types are canonical. 4167 if (ESI.Type == EST_Dynamic) { 4168 bool AnyPackExpansions = false; 4169 for (QualType ET : ESI.Exceptions) { 4170 if (!ET.isCanonical()) 4171 return false; 4172 if (ET->getAs<PackExpansionType>()) 4173 AnyPackExpansions = true; 4174 } 4175 return AnyPackExpansions; 4176 } 4177 4178 return false; 4179 } 4180 4181 QualType ASTContext::getFunctionTypeInternal( 4182 QualType ResultTy, ArrayRef<QualType> ArgArray, 4183 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const { 4184 size_t NumArgs = ArgArray.size(); 4185 4186 // Unique functions, to guarantee there is only one function of a particular 4187 // structure. 4188 llvm::FoldingSetNodeID ID; 4189 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI, 4190 *this, true); 4191 4192 QualType Canonical; 4193 bool Unique = false; 4194 4195 void *InsertPos = nullptr; 4196 if (FunctionProtoType *FPT = 4197 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) { 4198 QualType Existing = QualType(FPT, 0); 4199 4200 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse 4201 // it so long as our exception specification doesn't contain a dependent 4202 // noexcept expression, or we're just looking for a canonical type. 4203 // Otherwise, we're going to need to create a type 4204 // sugar node to hold the concrete expression. 4205 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) || 4206 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr()) 4207 return Existing; 4208 4209 // We need a new type sugar node for this one, to hold the new noexcept 4210 // expression. We do no canonicalization here, but that's OK since we don't 4211 // expect to see the same noexcept expression much more than once. 4212 Canonical = getCanonicalType(Existing); 4213 Unique = true; 4214 } 4215 4216 bool NoexceptInType = getLangOpts().CPlusPlus17; 4217 bool IsCanonicalExceptionSpec = 4218 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType); 4219 4220 // Determine whether the type being created is already canonical or not. 4221 bool isCanonical = !Unique && IsCanonicalExceptionSpec && 4222 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn; 4223 for (unsigned i = 0; i != NumArgs && isCanonical; ++i) 4224 if (!ArgArray[i].isCanonicalAsParam()) 4225 isCanonical = false; 4226 4227 if (OnlyWantCanonical) 4228 assert(isCanonical && 4229 "given non-canonical parameters constructing canonical type"); 4230 4231 // If this type isn't canonical, get the canonical version of it if we don't 4232 // already have it. The exception spec is only partially part of the 4233 // canonical type, and only in C++17 onwards. 4234 if (!isCanonical && Canonical.isNull()) { 4235 SmallVector<QualType, 16> CanonicalArgs; 4236 CanonicalArgs.reserve(NumArgs); 4237 for (unsigned i = 0; i != NumArgs; ++i) 4238 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i])); 4239 4240 llvm::SmallVector<QualType, 8> ExceptionTypeStorage; 4241 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI; 4242 CanonicalEPI.HasTrailingReturn = false; 4243 4244 if (IsCanonicalExceptionSpec) { 4245 // Exception spec is already OK. 4246 } else if (NoexceptInType) { 4247 switch (EPI.ExceptionSpec.Type) { 4248 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated: 4249 // We don't know yet. It shouldn't matter what we pick here; no-one 4250 // should ever look at this. 4251 LLVM_FALLTHROUGH; 4252 case EST_None: case EST_MSAny: case EST_NoexceptFalse: 4253 CanonicalEPI.ExceptionSpec.Type = EST_None; 4254 break; 4255 4256 // A dynamic exception specification is almost always "not noexcept", 4257 // with the exception that a pack expansion might expand to no types. 4258 case EST_Dynamic: { 4259 bool AnyPacks = false; 4260 for (QualType ET : EPI.ExceptionSpec.Exceptions) { 4261 if (ET->getAs<PackExpansionType>()) 4262 AnyPacks = true; 4263 ExceptionTypeStorage.push_back(getCanonicalType(ET)); 4264 } 4265 if (!AnyPacks) 4266 CanonicalEPI.ExceptionSpec.Type = EST_None; 4267 else { 4268 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic; 4269 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage; 4270 } 4271 break; 4272 } 4273 4274 case EST_DynamicNone: 4275 case EST_BasicNoexcept: 4276 case EST_NoexceptTrue: 4277 case EST_NoThrow: 4278 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept; 4279 break; 4280 4281 case EST_DependentNoexcept: 4282 llvm_unreachable("dependent noexcept is already canonical"); 4283 } 4284 } else { 4285 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo(); 4286 } 4287 4288 // Adjust the canonical function result type. 4289 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy); 4290 Canonical = 4291 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true); 4292 4293 // Get the new insert position for the node we care about. 4294 FunctionProtoType *NewIP = 4295 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 4296 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4297 } 4298 4299 // Compute the needed size to hold this FunctionProtoType and the 4300 // various trailing objects. 4301 auto ESH = FunctionProtoType::getExceptionSpecSize( 4302 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size()); 4303 size_t Size = FunctionProtoType::totalSizeToAlloc< 4304 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields, 4305 FunctionType::ExceptionType, Expr *, FunctionDecl *, 4306 FunctionProtoType::ExtParameterInfo, Qualifiers>( 4307 NumArgs, EPI.Variadic, 4308 FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type), 4309 ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr, 4310 EPI.ExtParameterInfos ? NumArgs : 0, 4311 EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0); 4312 4313 auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment); 4314 FunctionProtoType::ExtProtoInfo newEPI = EPI; 4315 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI); 4316 Types.push_back(FTP); 4317 if (!Unique) 4318 FunctionProtoTypes.InsertNode(FTP, InsertPos); 4319 return QualType(FTP, 0); 4320 } 4321 4322 QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const { 4323 llvm::FoldingSetNodeID ID; 4324 PipeType::Profile(ID, T, ReadOnly); 4325 4326 void *InsertPos = nullptr; 4327 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos)) 4328 return QualType(PT, 0); 4329 4330 // If the pipe element type isn't canonical, this won't be a canonical type 4331 // either, so fill in the canonical type field. 4332 QualType Canonical; 4333 if (!T.isCanonical()) { 4334 Canonical = getPipeType(getCanonicalType(T), ReadOnly); 4335 4336 // Get the new insert position for the node we care about. 4337 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos); 4338 assert(!NewIP && "Shouldn't be in the map!"); 4339 (void)NewIP; 4340 } 4341 auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly); 4342 Types.push_back(New); 4343 PipeTypes.InsertNode(New, InsertPos); 4344 return QualType(New, 0); 4345 } 4346 4347 QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const { 4348 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 4349 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant) 4350 : Ty; 4351 } 4352 4353 QualType ASTContext::getReadPipeType(QualType T) const { 4354 return getPipeType(T, true); 4355 } 4356 4357 QualType ASTContext::getWritePipeType(QualType T) const { 4358 return getPipeType(T, false); 4359 } 4360 4361 QualType ASTContext::getExtIntType(bool IsUnsigned, unsigned NumBits) const { 4362 llvm::FoldingSetNodeID ID; 4363 ExtIntType::Profile(ID, IsUnsigned, NumBits); 4364 4365 void *InsertPos = nullptr; 4366 if (ExtIntType *EIT = ExtIntTypes.FindNodeOrInsertPos(ID, InsertPos)) 4367 return QualType(EIT, 0); 4368 4369 auto *New = new (*this, TypeAlignment) ExtIntType(IsUnsigned, NumBits); 4370 ExtIntTypes.InsertNode(New, InsertPos); 4371 Types.push_back(New); 4372 return QualType(New, 0); 4373 } 4374 4375 QualType ASTContext::getDependentExtIntType(bool IsUnsigned, 4376 Expr *NumBitsExpr) const { 4377 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent"); 4378 llvm::FoldingSetNodeID ID; 4379 DependentExtIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr); 4380 4381 void *InsertPos = nullptr; 4382 if (DependentExtIntType *Existing = 4383 DependentExtIntTypes.FindNodeOrInsertPos(ID, InsertPos)) 4384 return QualType(Existing, 0); 4385 4386 auto *New = new (*this, TypeAlignment) 4387 DependentExtIntType(*this, IsUnsigned, NumBitsExpr); 4388 DependentExtIntTypes.InsertNode(New, InsertPos); 4389 4390 Types.push_back(New); 4391 return QualType(New, 0); 4392 } 4393 4394 #ifndef NDEBUG 4395 static bool NeedsInjectedClassNameType(const RecordDecl *D) { 4396 if (!isa<CXXRecordDecl>(D)) return false; 4397 const auto *RD = cast<CXXRecordDecl>(D); 4398 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) 4399 return true; 4400 if (RD->getDescribedClassTemplate() && 4401 !isa<ClassTemplateSpecializationDecl>(RD)) 4402 return true; 4403 return false; 4404 } 4405 #endif 4406 4407 /// getInjectedClassNameType - Return the unique reference to the 4408 /// injected class name type for the specified templated declaration. 4409 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl, 4410 QualType TST) const { 4411 assert(NeedsInjectedClassNameType(Decl)); 4412 if (Decl->TypeForDecl) { 4413 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 4414 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) { 4415 assert(PrevDecl->TypeForDecl && "previous declaration has no type"); 4416 Decl->TypeForDecl = PrevDecl->TypeForDecl; 4417 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 4418 } else { 4419 Type *newType = 4420 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST); 4421 Decl->TypeForDecl = newType; 4422 Types.push_back(newType); 4423 } 4424 return QualType(Decl->TypeForDecl, 0); 4425 } 4426 4427 /// getTypeDeclType - Return the unique reference to the type for the 4428 /// specified type declaration. 4429 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const { 4430 assert(Decl && "Passed null for Decl param"); 4431 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case"); 4432 4433 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl)) 4434 return getTypedefType(Typedef); 4435 4436 assert(!isa<TemplateTypeParmDecl>(Decl) && 4437 "Template type parameter types are always available."); 4438 4439 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) { 4440 assert(Record->isFirstDecl() && "struct/union has previous declaration"); 4441 assert(!NeedsInjectedClassNameType(Record)); 4442 return getRecordType(Record); 4443 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) { 4444 assert(Enum->isFirstDecl() && "enum has previous declaration"); 4445 return getEnumType(Enum); 4446 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) { 4447 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using); 4448 Decl->TypeForDecl = newType; 4449 Types.push_back(newType); 4450 } else 4451 llvm_unreachable("TypeDecl without a type?"); 4452 4453 return QualType(Decl->TypeForDecl, 0); 4454 } 4455 4456 /// getTypedefType - Return the unique reference to the type for the 4457 /// specified typedef name decl. 4458 QualType ASTContext::getTypedefType(const TypedefNameDecl *Decl, 4459 QualType Underlying) const { 4460 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 4461 4462 if (Underlying.isNull()) 4463 Underlying = Decl->getUnderlyingType(); 4464 QualType Canonical = getCanonicalType(Underlying); 4465 auto *newType = new (*this, TypeAlignment) 4466 TypedefType(Type::Typedef, Decl, Underlying, Canonical); 4467 Decl->TypeForDecl = newType; 4468 Types.push_back(newType); 4469 return QualType(newType, 0); 4470 } 4471 4472 QualType ASTContext::getRecordType(const RecordDecl *Decl) const { 4473 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 4474 4475 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl()) 4476 if (PrevDecl->TypeForDecl) 4477 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 4478 4479 auto *newType = new (*this, TypeAlignment) RecordType(Decl); 4480 Decl->TypeForDecl = newType; 4481 Types.push_back(newType); 4482 return QualType(newType, 0); 4483 } 4484 4485 QualType ASTContext::getEnumType(const EnumDecl *Decl) const { 4486 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 4487 4488 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl()) 4489 if (PrevDecl->TypeForDecl) 4490 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 4491 4492 auto *newType = new (*this, TypeAlignment) EnumType(Decl); 4493 Decl->TypeForDecl = newType; 4494 Types.push_back(newType); 4495 return QualType(newType, 0); 4496 } 4497 4498 QualType ASTContext::getAttributedType(attr::Kind attrKind, 4499 QualType modifiedType, 4500 QualType equivalentType) { 4501 llvm::FoldingSetNodeID id; 4502 AttributedType::Profile(id, attrKind, modifiedType, equivalentType); 4503 4504 void *insertPos = nullptr; 4505 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos); 4506 if (type) return QualType(type, 0); 4507 4508 QualType canon = getCanonicalType(equivalentType); 4509 type = new (*this, TypeAlignment) 4510 AttributedType(canon, attrKind, modifiedType, equivalentType); 4511 4512 Types.push_back(type); 4513 AttributedTypes.InsertNode(type, insertPos); 4514 4515 return QualType(type, 0); 4516 } 4517 4518 /// Retrieve a substitution-result type. 4519 QualType 4520 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm, 4521 QualType Replacement) const { 4522 assert(Replacement.isCanonical() 4523 && "replacement types must always be canonical"); 4524 4525 llvm::FoldingSetNodeID ID; 4526 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement); 4527 void *InsertPos = nullptr; 4528 SubstTemplateTypeParmType *SubstParm 4529 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 4530 4531 if (!SubstParm) { 4532 SubstParm = new (*this, TypeAlignment) 4533 SubstTemplateTypeParmType(Parm, Replacement); 4534 Types.push_back(SubstParm); 4535 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos); 4536 } 4537 4538 return QualType(SubstParm, 0); 4539 } 4540 4541 /// Retrieve a 4542 QualType ASTContext::getSubstTemplateTypeParmPackType( 4543 const TemplateTypeParmType *Parm, 4544 const TemplateArgument &ArgPack) { 4545 #ifndef NDEBUG 4546 for (const auto &P : ArgPack.pack_elements()) { 4547 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type"); 4548 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type"); 4549 } 4550 #endif 4551 4552 llvm::FoldingSetNodeID ID; 4553 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack); 4554 void *InsertPos = nullptr; 4555 if (SubstTemplateTypeParmPackType *SubstParm 4556 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos)) 4557 return QualType(SubstParm, 0); 4558 4559 QualType Canon; 4560 if (!Parm->isCanonicalUnqualified()) { 4561 Canon = getCanonicalType(QualType(Parm, 0)); 4562 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon), 4563 ArgPack); 4564 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos); 4565 } 4566 4567 auto *SubstParm 4568 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon, 4569 ArgPack); 4570 Types.push_back(SubstParm); 4571 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos); 4572 return QualType(SubstParm, 0); 4573 } 4574 4575 /// Retrieve the template type parameter type for a template 4576 /// parameter or parameter pack with the given depth, index, and (optionally) 4577 /// name. 4578 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index, 4579 bool ParameterPack, 4580 TemplateTypeParmDecl *TTPDecl) const { 4581 llvm::FoldingSetNodeID ID; 4582 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl); 4583 void *InsertPos = nullptr; 4584 TemplateTypeParmType *TypeParm 4585 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 4586 4587 if (TypeParm) 4588 return QualType(TypeParm, 0); 4589 4590 if (TTPDecl) { 4591 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack); 4592 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon); 4593 4594 TemplateTypeParmType *TypeCheck 4595 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 4596 assert(!TypeCheck && "Template type parameter canonical type broken"); 4597 (void)TypeCheck; 4598 } else 4599 TypeParm = new (*this, TypeAlignment) 4600 TemplateTypeParmType(Depth, Index, ParameterPack); 4601 4602 Types.push_back(TypeParm); 4603 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos); 4604 4605 return QualType(TypeParm, 0); 4606 } 4607 4608 TypeSourceInfo * 4609 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name, 4610 SourceLocation NameLoc, 4611 const TemplateArgumentListInfo &Args, 4612 QualType Underlying) const { 4613 assert(!Name.getAsDependentTemplateName() && 4614 "No dependent template names here!"); 4615 QualType TST = getTemplateSpecializationType(Name, Args, Underlying); 4616 4617 TypeSourceInfo *DI = CreateTypeSourceInfo(TST); 4618 TemplateSpecializationTypeLoc TL = 4619 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>(); 4620 TL.setTemplateKeywordLoc(SourceLocation()); 4621 TL.setTemplateNameLoc(NameLoc); 4622 TL.setLAngleLoc(Args.getLAngleLoc()); 4623 TL.setRAngleLoc(Args.getRAngleLoc()); 4624 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 4625 TL.setArgLocInfo(i, Args[i].getLocInfo()); 4626 return DI; 4627 } 4628 4629 QualType 4630 ASTContext::getTemplateSpecializationType(TemplateName Template, 4631 const TemplateArgumentListInfo &Args, 4632 QualType Underlying) const { 4633 assert(!Template.getAsDependentTemplateName() && 4634 "No dependent template names here!"); 4635 4636 SmallVector<TemplateArgument, 4> ArgVec; 4637 ArgVec.reserve(Args.size()); 4638 for (const TemplateArgumentLoc &Arg : Args.arguments()) 4639 ArgVec.push_back(Arg.getArgument()); 4640 4641 return getTemplateSpecializationType(Template, ArgVec, Underlying); 4642 } 4643 4644 #ifndef NDEBUG 4645 static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) { 4646 for (const TemplateArgument &Arg : Args) 4647 if (Arg.isPackExpansion()) 4648 return true; 4649 4650 return true; 4651 } 4652 #endif 4653 4654 QualType 4655 ASTContext::getTemplateSpecializationType(TemplateName Template, 4656 ArrayRef<TemplateArgument> Args, 4657 QualType Underlying) const { 4658 assert(!Template.getAsDependentTemplateName() && 4659 "No dependent template names here!"); 4660 // Look through qualified template names. 4661 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 4662 Template = TemplateName(QTN->getTemplateDecl()); 4663 4664 bool IsTypeAlias = 4665 Template.getAsTemplateDecl() && 4666 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl()); 4667 QualType CanonType; 4668 if (!Underlying.isNull()) 4669 CanonType = getCanonicalType(Underlying); 4670 else { 4671 // We can get here with an alias template when the specialization contains 4672 // a pack expansion that does not match up with a parameter pack. 4673 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) && 4674 "Caller must compute aliased type"); 4675 IsTypeAlias = false; 4676 CanonType = getCanonicalTemplateSpecializationType(Template, Args); 4677 } 4678 4679 // Allocate the (non-canonical) template specialization type, but don't 4680 // try to unique it: these types typically have location information that 4681 // we don't unique and don't want to lose. 4682 void *Mem = Allocate(sizeof(TemplateSpecializationType) + 4683 sizeof(TemplateArgument) * Args.size() + 4684 (IsTypeAlias? sizeof(QualType) : 0), 4685 TypeAlignment); 4686 auto *Spec 4687 = new (Mem) TemplateSpecializationType(Template, Args, CanonType, 4688 IsTypeAlias ? Underlying : QualType()); 4689 4690 Types.push_back(Spec); 4691 return QualType(Spec, 0); 4692 } 4693 4694 QualType ASTContext::getCanonicalTemplateSpecializationType( 4695 TemplateName Template, ArrayRef<TemplateArgument> Args) const { 4696 assert(!Template.getAsDependentTemplateName() && 4697 "No dependent template names here!"); 4698 4699 // Look through qualified template names. 4700 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 4701 Template = TemplateName(QTN->getTemplateDecl()); 4702 4703 // Build the canonical template specialization type. 4704 TemplateName CanonTemplate = getCanonicalTemplateName(Template); 4705 SmallVector<TemplateArgument, 4> CanonArgs; 4706 unsigned NumArgs = Args.size(); 4707 CanonArgs.reserve(NumArgs); 4708 for (const TemplateArgument &Arg : Args) 4709 CanonArgs.push_back(getCanonicalTemplateArgument(Arg)); 4710 4711 // Determine whether this canonical template specialization type already 4712 // exists. 4713 llvm::FoldingSetNodeID ID; 4714 TemplateSpecializationType::Profile(ID, CanonTemplate, 4715 CanonArgs, *this); 4716 4717 void *InsertPos = nullptr; 4718 TemplateSpecializationType *Spec 4719 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 4720 4721 if (!Spec) { 4722 // Allocate a new canonical template specialization type. 4723 void *Mem = Allocate((sizeof(TemplateSpecializationType) + 4724 sizeof(TemplateArgument) * NumArgs), 4725 TypeAlignment); 4726 Spec = new (Mem) TemplateSpecializationType(CanonTemplate, 4727 CanonArgs, 4728 QualType(), QualType()); 4729 Types.push_back(Spec); 4730 TemplateSpecializationTypes.InsertNode(Spec, InsertPos); 4731 } 4732 4733 assert(Spec->isDependentType() && 4734 "Non-dependent template-id type must have a canonical type"); 4735 return QualType(Spec, 0); 4736 } 4737 4738 QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword, 4739 NestedNameSpecifier *NNS, 4740 QualType NamedType, 4741 TagDecl *OwnedTagDecl) const { 4742 llvm::FoldingSetNodeID ID; 4743 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl); 4744 4745 void *InsertPos = nullptr; 4746 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 4747 if (T) 4748 return QualType(T, 0); 4749 4750 QualType Canon = NamedType; 4751 if (!Canon.isCanonical()) { 4752 Canon = getCanonicalType(NamedType); 4753 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 4754 assert(!CheckT && "Elaborated canonical type broken"); 4755 (void)CheckT; 4756 } 4757 4758 void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl), 4759 TypeAlignment); 4760 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl); 4761 4762 Types.push_back(T); 4763 ElaboratedTypes.InsertNode(T, InsertPos); 4764 return QualType(T, 0); 4765 } 4766 4767 QualType 4768 ASTContext::getParenType(QualType InnerType) const { 4769 llvm::FoldingSetNodeID ID; 4770 ParenType::Profile(ID, InnerType); 4771 4772 void *InsertPos = nullptr; 4773 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 4774 if (T) 4775 return QualType(T, 0); 4776 4777 QualType Canon = InnerType; 4778 if (!Canon.isCanonical()) { 4779 Canon = getCanonicalType(InnerType); 4780 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 4781 assert(!CheckT && "Paren canonical type broken"); 4782 (void)CheckT; 4783 } 4784 4785 T = new (*this, TypeAlignment) ParenType(InnerType, Canon); 4786 Types.push_back(T); 4787 ParenTypes.InsertNode(T, InsertPos); 4788 return QualType(T, 0); 4789 } 4790 4791 QualType 4792 ASTContext::getMacroQualifiedType(QualType UnderlyingTy, 4793 const IdentifierInfo *MacroII) const { 4794 QualType Canon = UnderlyingTy; 4795 if (!Canon.isCanonical()) 4796 Canon = getCanonicalType(UnderlyingTy); 4797 4798 auto *newType = new (*this, TypeAlignment) 4799 MacroQualifiedType(UnderlyingTy, Canon, MacroII); 4800 Types.push_back(newType); 4801 return QualType(newType, 0); 4802 } 4803 4804 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword, 4805 NestedNameSpecifier *NNS, 4806 const IdentifierInfo *Name, 4807 QualType Canon) const { 4808 if (Canon.isNull()) { 4809 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 4810 if (CanonNNS != NNS) 4811 Canon = getDependentNameType(Keyword, CanonNNS, Name); 4812 } 4813 4814 llvm::FoldingSetNodeID ID; 4815 DependentNameType::Profile(ID, Keyword, NNS, Name); 4816 4817 void *InsertPos = nullptr; 4818 DependentNameType *T 4819 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos); 4820 if (T) 4821 return QualType(T, 0); 4822 4823 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon); 4824 Types.push_back(T); 4825 DependentNameTypes.InsertNode(T, InsertPos); 4826 return QualType(T, 0); 4827 } 4828 4829 QualType 4830 ASTContext::getDependentTemplateSpecializationType( 4831 ElaboratedTypeKeyword Keyword, 4832 NestedNameSpecifier *NNS, 4833 const IdentifierInfo *Name, 4834 const TemplateArgumentListInfo &Args) const { 4835 // TODO: avoid this copy 4836 SmallVector<TemplateArgument, 16> ArgCopy; 4837 for (unsigned I = 0, E = Args.size(); I != E; ++I) 4838 ArgCopy.push_back(Args[I].getArgument()); 4839 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy); 4840 } 4841 4842 QualType 4843 ASTContext::getDependentTemplateSpecializationType( 4844 ElaboratedTypeKeyword Keyword, 4845 NestedNameSpecifier *NNS, 4846 const IdentifierInfo *Name, 4847 ArrayRef<TemplateArgument> Args) const { 4848 assert((!NNS || NNS->isDependent()) && 4849 "nested-name-specifier must be dependent"); 4850 4851 llvm::FoldingSetNodeID ID; 4852 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS, 4853 Name, Args); 4854 4855 void *InsertPos = nullptr; 4856 DependentTemplateSpecializationType *T 4857 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 4858 if (T) 4859 return QualType(T, 0); 4860 4861 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 4862 4863 ElaboratedTypeKeyword CanonKeyword = Keyword; 4864 if (Keyword == ETK_None) CanonKeyword = ETK_Typename; 4865 4866 bool AnyNonCanonArgs = false; 4867 unsigned NumArgs = Args.size(); 4868 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs); 4869 for (unsigned I = 0; I != NumArgs; ++I) { 4870 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]); 4871 if (!CanonArgs[I].structurallyEquals(Args[I])) 4872 AnyNonCanonArgs = true; 4873 } 4874 4875 QualType Canon; 4876 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) { 4877 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS, 4878 Name, 4879 CanonArgs); 4880 4881 // Find the insert position again. 4882 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 4883 } 4884 4885 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) + 4886 sizeof(TemplateArgument) * NumArgs), 4887 TypeAlignment); 4888 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS, 4889 Name, Args, Canon); 4890 Types.push_back(T); 4891 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos); 4892 return QualType(T, 0); 4893 } 4894 4895 TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) { 4896 TemplateArgument Arg; 4897 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) { 4898 QualType ArgType = getTypeDeclType(TTP); 4899 if (TTP->isParameterPack()) 4900 ArgType = getPackExpansionType(ArgType, None); 4901 4902 Arg = TemplateArgument(ArgType); 4903 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 4904 QualType T = 4905 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this); 4906 // For class NTTPs, ensure we include the 'const' so the type matches that 4907 // of a real template argument. 4908 // FIXME: It would be more faithful to model this as something like an 4909 // lvalue-to-rvalue conversion applied to a const-qualified lvalue. 4910 if (T->isRecordType()) 4911 T.addConst(); 4912 Expr *E = new (*this) DeclRefExpr( 4913 *this, NTTP, /*enclosing*/ false, T, 4914 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation()); 4915 4916 if (NTTP->isParameterPack()) 4917 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(), 4918 None); 4919 Arg = TemplateArgument(E); 4920 } else { 4921 auto *TTP = cast<TemplateTemplateParmDecl>(Param); 4922 if (TTP->isParameterPack()) 4923 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>()); 4924 else 4925 Arg = TemplateArgument(TemplateName(TTP)); 4926 } 4927 4928 if (Param->isTemplateParameterPack()) 4929 Arg = TemplateArgument::CreatePackCopy(*this, Arg); 4930 4931 return Arg; 4932 } 4933 4934 void 4935 ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params, 4936 SmallVectorImpl<TemplateArgument> &Args) { 4937 Args.reserve(Args.size() + Params->size()); 4938 4939 for (NamedDecl *Param : *Params) 4940 Args.push_back(getInjectedTemplateArg(Param)); 4941 } 4942 4943 QualType ASTContext::getPackExpansionType(QualType Pattern, 4944 Optional<unsigned> NumExpansions, 4945 bool ExpectPackInType) { 4946 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) && 4947 "Pack expansions must expand one or more parameter packs"); 4948 4949 llvm::FoldingSetNodeID ID; 4950 PackExpansionType::Profile(ID, Pattern, NumExpansions); 4951 4952 void *InsertPos = nullptr; 4953 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 4954 if (T) 4955 return QualType(T, 0); 4956 4957 QualType Canon; 4958 if (!Pattern.isCanonical()) { 4959 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions, 4960 /*ExpectPackInType=*/false); 4961 4962 // Find the insert position again, in case we inserted an element into 4963 // PackExpansionTypes and invalidated our insert position. 4964 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 4965 } 4966 4967 T = new (*this, TypeAlignment) 4968 PackExpansionType(Pattern, Canon, NumExpansions); 4969 Types.push_back(T); 4970 PackExpansionTypes.InsertNode(T, InsertPos); 4971 return QualType(T, 0); 4972 } 4973 4974 /// CmpProtocolNames - Comparison predicate for sorting protocols 4975 /// alphabetically. 4976 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS, 4977 ObjCProtocolDecl *const *RHS) { 4978 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName()); 4979 } 4980 4981 static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) { 4982 if (Protocols.empty()) return true; 4983 4984 if (Protocols[0]->getCanonicalDecl() != Protocols[0]) 4985 return false; 4986 4987 for (unsigned i = 1; i != Protocols.size(); ++i) 4988 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 || 4989 Protocols[i]->getCanonicalDecl() != Protocols[i]) 4990 return false; 4991 return true; 4992 } 4993 4994 static void 4995 SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) { 4996 // Sort protocols, keyed by name. 4997 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames); 4998 4999 // Canonicalize. 5000 for (ObjCProtocolDecl *&P : Protocols) 5001 P = P->getCanonicalDecl(); 5002 5003 // Remove duplicates. 5004 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end()); 5005 Protocols.erase(ProtocolsEnd, Protocols.end()); 5006 } 5007 5008 QualType ASTContext::getObjCObjectType(QualType BaseType, 5009 ObjCProtocolDecl * const *Protocols, 5010 unsigned NumProtocols) const { 5011 return getObjCObjectType(BaseType, {}, 5012 llvm::makeArrayRef(Protocols, NumProtocols), 5013 /*isKindOf=*/false); 5014 } 5015 5016 QualType ASTContext::getObjCObjectType( 5017 QualType baseType, 5018 ArrayRef<QualType> typeArgs, 5019 ArrayRef<ObjCProtocolDecl *> protocols, 5020 bool isKindOf) const { 5021 // If the base type is an interface and there aren't any protocols or 5022 // type arguments to add, then the interface type will do just fine. 5023 if (typeArgs.empty() && protocols.empty() && !isKindOf && 5024 isa<ObjCInterfaceType>(baseType)) 5025 return baseType; 5026 5027 // Look in the folding set for an existing type. 5028 llvm::FoldingSetNodeID ID; 5029 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf); 5030 void *InsertPos = nullptr; 5031 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos)) 5032 return QualType(QT, 0); 5033 5034 // Determine the type arguments to be used for canonicalization, 5035 // which may be explicitly specified here or written on the base 5036 // type. 5037 ArrayRef<QualType> effectiveTypeArgs = typeArgs; 5038 if (effectiveTypeArgs.empty()) { 5039 if (const auto *baseObject = baseType->getAs<ObjCObjectType>()) 5040 effectiveTypeArgs = baseObject->getTypeArgs(); 5041 } 5042 5043 // Build the canonical type, which has the canonical base type and a 5044 // sorted-and-uniqued list of protocols and the type arguments 5045 // canonicalized. 5046 QualType canonical; 5047 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(), 5048 effectiveTypeArgs.end(), 5049 [&](QualType type) { 5050 return type.isCanonical(); 5051 }); 5052 bool protocolsSorted = areSortedAndUniqued(protocols); 5053 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) { 5054 // Determine the canonical type arguments. 5055 ArrayRef<QualType> canonTypeArgs; 5056 SmallVector<QualType, 4> canonTypeArgsVec; 5057 if (!typeArgsAreCanonical) { 5058 canonTypeArgsVec.reserve(effectiveTypeArgs.size()); 5059 for (auto typeArg : effectiveTypeArgs) 5060 canonTypeArgsVec.push_back(getCanonicalType(typeArg)); 5061 canonTypeArgs = canonTypeArgsVec; 5062 } else { 5063 canonTypeArgs = effectiveTypeArgs; 5064 } 5065 5066 ArrayRef<ObjCProtocolDecl *> canonProtocols; 5067 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec; 5068 if (!protocolsSorted) { 5069 canonProtocolsVec.append(protocols.begin(), protocols.end()); 5070 SortAndUniqueProtocols(canonProtocolsVec); 5071 canonProtocols = canonProtocolsVec; 5072 } else { 5073 canonProtocols = protocols; 5074 } 5075 5076 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs, 5077 canonProtocols, isKindOf); 5078 5079 // Regenerate InsertPos. 5080 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos); 5081 } 5082 5083 unsigned size = sizeof(ObjCObjectTypeImpl); 5084 size += typeArgs.size() * sizeof(QualType); 5085 size += protocols.size() * sizeof(ObjCProtocolDecl *); 5086 void *mem = Allocate(size, TypeAlignment); 5087 auto *T = 5088 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols, 5089 isKindOf); 5090 5091 Types.push_back(T); 5092 ObjCObjectTypes.InsertNode(T, InsertPos); 5093 return QualType(T, 0); 5094 } 5095 5096 /// Apply Objective-C protocol qualifiers to the given type. 5097 /// If this is for the canonical type of a type parameter, we can apply 5098 /// protocol qualifiers on the ObjCObjectPointerType. 5099 QualType 5100 ASTContext::applyObjCProtocolQualifiers(QualType type, 5101 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError, 5102 bool allowOnPointerType) const { 5103 hasError = false; 5104 5105 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) { 5106 return getObjCTypeParamType(objT->getDecl(), protocols); 5107 } 5108 5109 // Apply protocol qualifiers to ObjCObjectPointerType. 5110 if (allowOnPointerType) { 5111 if (const auto *objPtr = 5112 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) { 5113 const ObjCObjectType *objT = objPtr->getObjectType(); 5114 // Merge protocol lists and construct ObjCObjectType. 5115 SmallVector<ObjCProtocolDecl*, 8> protocolsVec; 5116 protocolsVec.append(objT->qual_begin(), 5117 objT->qual_end()); 5118 protocolsVec.append(protocols.begin(), protocols.end()); 5119 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec; 5120 type = getObjCObjectType( 5121 objT->getBaseType(), 5122 objT->getTypeArgsAsWritten(), 5123 protocols, 5124 objT->isKindOfTypeAsWritten()); 5125 return getObjCObjectPointerType(type); 5126 } 5127 } 5128 5129 // Apply protocol qualifiers to ObjCObjectType. 5130 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){ 5131 // FIXME: Check for protocols to which the class type is already 5132 // known to conform. 5133 5134 return getObjCObjectType(objT->getBaseType(), 5135 objT->getTypeArgsAsWritten(), 5136 protocols, 5137 objT->isKindOfTypeAsWritten()); 5138 } 5139 5140 // If the canonical type is ObjCObjectType, ... 5141 if (type->isObjCObjectType()) { 5142 // Silently overwrite any existing protocol qualifiers. 5143 // TODO: determine whether that's the right thing to do. 5144 5145 // FIXME: Check for protocols to which the class type is already 5146 // known to conform. 5147 return getObjCObjectType(type, {}, protocols, false); 5148 } 5149 5150 // id<protocol-list> 5151 if (type->isObjCIdType()) { 5152 const auto *objPtr = type->castAs<ObjCObjectPointerType>(); 5153 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols, 5154 objPtr->isKindOfType()); 5155 return getObjCObjectPointerType(type); 5156 } 5157 5158 // Class<protocol-list> 5159 if (type->isObjCClassType()) { 5160 const auto *objPtr = type->castAs<ObjCObjectPointerType>(); 5161 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols, 5162 objPtr->isKindOfType()); 5163 return getObjCObjectPointerType(type); 5164 } 5165 5166 hasError = true; 5167 return type; 5168 } 5169 5170 QualType 5171 ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl, 5172 ArrayRef<ObjCProtocolDecl *> protocols) const { 5173 // Look in the folding set for an existing type. 5174 llvm::FoldingSetNodeID ID; 5175 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols); 5176 void *InsertPos = nullptr; 5177 if (ObjCTypeParamType *TypeParam = 5178 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos)) 5179 return QualType(TypeParam, 0); 5180 5181 // We canonicalize to the underlying type. 5182 QualType Canonical = getCanonicalType(Decl->getUnderlyingType()); 5183 if (!protocols.empty()) { 5184 // Apply the protocol qualifers. 5185 bool hasError; 5186 Canonical = getCanonicalType(applyObjCProtocolQualifiers( 5187 Canonical, protocols, hasError, true /*allowOnPointerType*/)); 5188 assert(!hasError && "Error when apply protocol qualifier to bound type"); 5189 } 5190 5191 unsigned size = sizeof(ObjCTypeParamType); 5192 size += protocols.size() * sizeof(ObjCProtocolDecl *); 5193 void *mem = Allocate(size, TypeAlignment); 5194 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols); 5195 5196 Types.push_back(newType); 5197 ObjCTypeParamTypes.InsertNode(newType, InsertPos); 5198 return QualType(newType, 0); 5199 } 5200 5201 void ASTContext::adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig, 5202 ObjCTypeParamDecl *New) const { 5203 New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType())); 5204 // Update TypeForDecl after updating TypeSourceInfo. 5205 auto NewTypeParamTy = cast<ObjCTypeParamType>(New->getTypeForDecl()); 5206 SmallVector<ObjCProtocolDecl *, 8> protocols; 5207 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end()); 5208 QualType UpdatedTy = getObjCTypeParamType(New, protocols); 5209 New->setTypeForDecl(UpdatedTy.getTypePtr()); 5210 } 5211 5212 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's 5213 /// protocol list adopt all protocols in QT's qualified-id protocol 5214 /// list. 5215 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT, 5216 ObjCInterfaceDecl *IC) { 5217 if (!QT->isObjCQualifiedIdType()) 5218 return false; 5219 5220 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) { 5221 // If both the right and left sides have qualifiers. 5222 for (auto *Proto : OPT->quals()) { 5223 if (!IC->ClassImplementsProtocol(Proto, false)) 5224 return false; 5225 } 5226 return true; 5227 } 5228 return false; 5229 } 5230 5231 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in 5232 /// QT's qualified-id protocol list adopt all protocols in IDecl's list 5233 /// of protocols. 5234 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT, 5235 ObjCInterfaceDecl *IDecl) { 5236 if (!QT->isObjCQualifiedIdType()) 5237 return false; 5238 const auto *OPT = QT->getAs<ObjCObjectPointerType>(); 5239 if (!OPT) 5240 return false; 5241 if (!IDecl->hasDefinition()) 5242 return false; 5243 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols; 5244 CollectInheritedProtocols(IDecl, InheritedProtocols); 5245 if (InheritedProtocols.empty()) 5246 return false; 5247 // Check that if every protocol in list of id<plist> conforms to a protocol 5248 // of IDecl's, then bridge casting is ok. 5249 bool Conforms = false; 5250 for (auto *Proto : OPT->quals()) { 5251 Conforms = false; 5252 for (auto *PI : InheritedProtocols) { 5253 if (ProtocolCompatibleWithProtocol(Proto, PI)) { 5254 Conforms = true; 5255 break; 5256 } 5257 } 5258 if (!Conforms) 5259 break; 5260 } 5261 if (Conforms) 5262 return true; 5263 5264 for (auto *PI : InheritedProtocols) { 5265 // If both the right and left sides have qualifiers. 5266 bool Adopts = false; 5267 for (auto *Proto : OPT->quals()) { 5268 // return 'true' if 'PI' is in the inheritance hierarchy of Proto 5269 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto))) 5270 break; 5271 } 5272 if (!Adopts) 5273 return false; 5274 } 5275 return true; 5276 } 5277 5278 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for 5279 /// the given object type. 5280 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const { 5281 llvm::FoldingSetNodeID ID; 5282 ObjCObjectPointerType::Profile(ID, ObjectT); 5283 5284 void *InsertPos = nullptr; 5285 if (ObjCObjectPointerType *QT = 5286 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 5287 return QualType(QT, 0); 5288 5289 // Find the canonical object type. 5290 QualType Canonical; 5291 if (!ObjectT.isCanonical()) { 5292 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT)); 5293 5294 // Regenerate InsertPos. 5295 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 5296 } 5297 5298 // No match. 5299 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment); 5300 auto *QType = 5301 new (Mem) ObjCObjectPointerType(Canonical, ObjectT); 5302 5303 Types.push_back(QType); 5304 ObjCObjectPointerTypes.InsertNode(QType, InsertPos); 5305 return QualType(QType, 0); 5306 } 5307 5308 /// getObjCInterfaceType - Return the unique reference to the type for the 5309 /// specified ObjC interface decl. The list of protocols is optional. 5310 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl, 5311 ObjCInterfaceDecl *PrevDecl) const { 5312 if (Decl->TypeForDecl) 5313 return QualType(Decl->TypeForDecl, 0); 5314 5315 if (PrevDecl) { 5316 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl"); 5317 Decl->TypeForDecl = PrevDecl->TypeForDecl; 5318 return QualType(PrevDecl->TypeForDecl, 0); 5319 } 5320 5321 // Prefer the definition, if there is one. 5322 if (const ObjCInterfaceDecl *Def = Decl->getDefinition()) 5323 Decl = Def; 5324 5325 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment); 5326 auto *T = new (Mem) ObjCInterfaceType(Decl); 5327 Decl->TypeForDecl = T; 5328 Types.push_back(T); 5329 return QualType(T, 0); 5330 } 5331 5332 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique 5333 /// TypeOfExprType AST's (since expression's are never shared). For example, 5334 /// multiple declarations that refer to "typeof(x)" all contain different 5335 /// DeclRefExpr's. This doesn't effect the type checker, since it operates 5336 /// on canonical type's (which are always unique). 5337 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const { 5338 TypeOfExprType *toe; 5339 if (tofExpr->isTypeDependent()) { 5340 llvm::FoldingSetNodeID ID; 5341 DependentTypeOfExprType::Profile(ID, *this, tofExpr); 5342 5343 void *InsertPos = nullptr; 5344 DependentTypeOfExprType *Canon 5345 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos); 5346 if (Canon) { 5347 // We already have a "canonical" version of an identical, dependent 5348 // typeof(expr) type. Use that as our canonical type. 5349 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, 5350 QualType((TypeOfExprType*)Canon, 0)); 5351 } else { 5352 // Build a new, canonical typeof(expr) type. 5353 Canon 5354 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr); 5355 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos); 5356 toe = Canon; 5357 } 5358 } else { 5359 QualType Canonical = getCanonicalType(tofExpr->getType()); 5360 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical); 5361 } 5362 Types.push_back(toe); 5363 return QualType(toe, 0); 5364 } 5365 5366 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique 5367 /// TypeOfType nodes. The only motivation to unique these nodes would be 5368 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be 5369 /// an issue. This doesn't affect the type checker, since it operates 5370 /// on canonical types (which are always unique). 5371 QualType ASTContext::getTypeOfType(QualType tofType) const { 5372 QualType Canonical = getCanonicalType(tofType); 5373 auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical); 5374 Types.push_back(tot); 5375 return QualType(tot, 0); 5376 } 5377 5378 /// Unlike many "get<Type>" functions, we don't unique DecltypeType 5379 /// nodes. This would never be helpful, since each such type has its own 5380 /// expression, and would not give a significant memory saving, since there 5381 /// is an Expr tree under each such type. 5382 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const { 5383 DecltypeType *dt; 5384 5385 // C++11 [temp.type]p2: 5386 // If an expression e involves a template parameter, decltype(e) denotes a 5387 // unique dependent type. Two such decltype-specifiers refer to the same 5388 // type only if their expressions are equivalent (14.5.6.1). 5389 if (e->isInstantiationDependent()) { 5390 llvm::FoldingSetNodeID ID; 5391 DependentDecltypeType::Profile(ID, *this, e); 5392 5393 void *InsertPos = nullptr; 5394 DependentDecltypeType *Canon 5395 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos); 5396 if (!Canon) { 5397 // Build a new, canonical decltype(expr) type. 5398 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e); 5399 DependentDecltypeTypes.InsertNode(Canon, InsertPos); 5400 } 5401 dt = new (*this, TypeAlignment) 5402 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0)); 5403 } else { 5404 dt = new (*this, TypeAlignment) 5405 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType)); 5406 } 5407 Types.push_back(dt); 5408 return QualType(dt, 0); 5409 } 5410 5411 /// getUnaryTransformationType - We don't unique these, since the memory 5412 /// savings are minimal and these are rare. 5413 QualType ASTContext::getUnaryTransformType(QualType BaseType, 5414 QualType UnderlyingType, 5415 UnaryTransformType::UTTKind Kind) 5416 const { 5417 UnaryTransformType *ut = nullptr; 5418 5419 if (BaseType->isDependentType()) { 5420 // Look in the folding set for an existing type. 5421 llvm::FoldingSetNodeID ID; 5422 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind); 5423 5424 void *InsertPos = nullptr; 5425 DependentUnaryTransformType *Canon 5426 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos); 5427 5428 if (!Canon) { 5429 // Build a new, canonical __underlying_type(type) type. 5430 Canon = new (*this, TypeAlignment) 5431 DependentUnaryTransformType(*this, getCanonicalType(BaseType), 5432 Kind); 5433 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos); 5434 } 5435 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType, 5436 QualType(), Kind, 5437 QualType(Canon, 0)); 5438 } else { 5439 QualType CanonType = getCanonicalType(UnderlyingType); 5440 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType, 5441 UnderlyingType, Kind, 5442 CanonType); 5443 } 5444 Types.push_back(ut); 5445 return QualType(ut, 0); 5446 } 5447 5448 /// getAutoType - Return the uniqued reference to the 'auto' type which has been 5449 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the 5450 /// canonical deduced-but-dependent 'auto' type. 5451 QualType 5452 ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, 5453 bool IsDependent, bool IsPack, 5454 ConceptDecl *TypeConstraintConcept, 5455 ArrayRef<TemplateArgument> TypeConstraintArgs) const { 5456 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack"); 5457 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && 5458 !TypeConstraintConcept && !IsDependent) 5459 return getAutoDeductType(); 5460 5461 // Look in the folding set for an existing type. 5462 void *InsertPos = nullptr; 5463 llvm::FoldingSetNodeID ID; 5464 AutoType::Profile(ID, *this, DeducedType, Keyword, IsDependent, 5465 TypeConstraintConcept, TypeConstraintArgs); 5466 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos)) 5467 return QualType(AT, 0); 5468 5469 void *Mem = Allocate(sizeof(AutoType) + 5470 sizeof(TemplateArgument) * TypeConstraintArgs.size(), 5471 TypeAlignment); 5472 auto *AT = new (Mem) AutoType( 5473 DeducedType, Keyword, 5474 (IsDependent ? TypeDependence::DependentInstantiation 5475 : TypeDependence::None) | 5476 (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None), 5477 TypeConstraintConcept, TypeConstraintArgs); 5478 Types.push_back(AT); 5479 if (InsertPos) 5480 AutoTypes.InsertNode(AT, InsertPos); 5481 return QualType(AT, 0); 5482 } 5483 5484 /// Return the uniqued reference to the deduced template specialization type 5485 /// which has been deduced to the given type, or to the canonical undeduced 5486 /// such type, or the canonical deduced-but-dependent such type. 5487 QualType ASTContext::getDeducedTemplateSpecializationType( 5488 TemplateName Template, QualType DeducedType, bool IsDependent) const { 5489 // Look in the folding set for an existing type. 5490 void *InsertPos = nullptr; 5491 llvm::FoldingSetNodeID ID; 5492 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType, 5493 IsDependent); 5494 if (DeducedTemplateSpecializationType *DTST = 5495 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos)) 5496 return QualType(DTST, 0); 5497 5498 auto *DTST = new (*this, TypeAlignment) 5499 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent); 5500 Types.push_back(DTST); 5501 if (InsertPos) 5502 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos); 5503 return QualType(DTST, 0); 5504 } 5505 5506 /// getAtomicType - Return the uniqued reference to the atomic type for 5507 /// the given value type. 5508 QualType ASTContext::getAtomicType(QualType T) const { 5509 // Unique pointers, to guarantee there is only one pointer of a particular 5510 // structure. 5511 llvm::FoldingSetNodeID ID; 5512 AtomicType::Profile(ID, T); 5513 5514 void *InsertPos = nullptr; 5515 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos)) 5516 return QualType(AT, 0); 5517 5518 // If the atomic value type isn't canonical, this won't be a canonical type 5519 // either, so fill in the canonical type field. 5520 QualType Canonical; 5521 if (!T.isCanonical()) { 5522 Canonical = getAtomicType(getCanonicalType(T)); 5523 5524 // Get the new insert position for the node we care about. 5525 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos); 5526 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 5527 } 5528 auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical); 5529 Types.push_back(New); 5530 AtomicTypes.InsertNode(New, InsertPos); 5531 return QualType(New, 0); 5532 } 5533 5534 /// getAutoDeductType - Get type pattern for deducing against 'auto'. 5535 QualType ASTContext::getAutoDeductType() const { 5536 if (AutoDeductTy.isNull()) 5537 AutoDeductTy = QualType(new (*this, TypeAlignment) 5538 AutoType(QualType(), AutoTypeKeyword::Auto, 5539 TypeDependence::None, 5540 /*concept*/ nullptr, /*args*/ {}), 5541 0); 5542 return AutoDeductTy; 5543 } 5544 5545 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'. 5546 QualType ASTContext::getAutoRRefDeductType() const { 5547 if (AutoRRefDeductTy.isNull()) 5548 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType()); 5549 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern"); 5550 return AutoRRefDeductTy; 5551 } 5552 5553 /// getTagDeclType - Return the unique reference to the type for the 5554 /// specified TagDecl (struct/union/class/enum) decl. 5555 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const { 5556 assert(Decl); 5557 // FIXME: What is the design on getTagDeclType when it requires casting 5558 // away const? mutable? 5559 return getTypeDeclType(const_cast<TagDecl*>(Decl)); 5560 } 5561 5562 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result 5563 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and 5564 /// needs to agree with the definition in <stddef.h>. 5565 CanQualType ASTContext::getSizeType() const { 5566 return getFromTargetType(Target->getSizeType()); 5567 } 5568 5569 /// Return the unique signed counterpart of the integer type 5570 /// corresponding to size_t. 5571 CanQualType ASTContext::getSignedSizeType() const { 5572 return getFromTargetType(Target->getSignedSizeType()); 5573 } 5574 5575 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5). 5576 CanQualType ASTContext::getIntMaxType() const { 5577 return getFromTargetType(Target->getIntMaxType()); 5578 } 5579 5580 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5). 5581 CanQualType ASTContext::getUIntMaxType() const { 5582 return getFromTargetType(Target->getUIntMaxType()); 5583 } 5584 5585 /// getSignedWCharType - Return the type of "signed wchar_t". 5586 /// Used when in C++, as a GCC extension. 5587 QualType ASTContext::getSignedWCharType() const { 5588 // FIXME: derive from "Target" ? 5589 return WCharTy; 5590 } 5591 5592 /// getUnsignedWCharType - Return the type of "unsigned wchar_t". 5593 /// Used when in C++, as a GCC extension. 5594 QualType ASTContext::getUnsignedWCharType() const { 5595 // FIXME: derive from "Target" ? 5596 return UnsignedIntTy; 5597 } 5598 5599 QualType ASTContext::getIntPtrType() const { 5600 return getFromTargetType(Target->getIntPtrType()); 5601 } 5602 5603 QualType ASTContext::getUIntPtrType() const { 5604 return getCorrespondingUnsignedType(getIntPtrType()); 5605 } 5606 5607 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17) 5608 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9). 5609 QualType ASTContext::getPointerDiffType() const { 5610 return getFromTargetType(Target->getPtrDiffType(0)); 5611 } 5612 5613 /// Return the unique unsigned counterpart of "ptrdiff_t" 5614 /// integer type. The standard (C11 7.21.6.1p7) refers to this type 5615 /// in the definition of %tu format specifier. 5616 QualType ASTContext::getUnsignedPointerDiffType() const { 5617 return getFromTargetType(Target->getUnsignedPtrDiffType(0)); 5618 } 5619 5620 /// Return the unique type for "pid_t" defined in 5621 /// <sys/types.h>. We need this to compute the correct type for vfork(). 5622 QualType ASTContext::getProcessIDType() const { 5623 return getFromTargetType(Target->getProcessIDType()); 5624 } 5625 5626 //===----------------------------------------------------------------------===// 5627 // Type Operators 5628 //===----------------------------------------------------------------------===// 5629 5630 CanQualType ASTContext::getCanonicalParamType(QualType T) const { 5631 // Push qualifiers into arrays, and then discard any remaining 5632 // qualifiers. 5633 T = getCanonicalType(T); 5634 T = getVariableArrayDecayedType(T); 5635 const Type *Ty = T.getTypePtr(); 5636 QualType Result; 5637 if (isa<ArrayType>(Ty)) { 5638 Result = getArrayDecayedType(QualType(Ty,0)); 5639 } else if (isa<FunctionType>(Ty)) { 5640 Result = getPointerType(QualType(Ty, 0)); 5641 } else { 5642 Result = QualType(Ty, 0); 5643 } 5644 5645 return CanQualType::CreateUnsafe(Result); 5646 } 5647 5648 QualType ASTContext::getUnqualifiedArrayType(QualType type, 5649 Qualifiers &quals) { 5650 SplitQualType splitType = type.getSplitUnqualifiedType(); 5651 5652 // FIXME: getSplitUnqualifiedType() actually walks all the way to 5653 // the unqualified desugared type and then drops it on the floor. 5654 // We then have to strip that sugar back off with 5655 // getUnqualifiedDesugaredType(), which is silly. 5656 const auto *AT = 5657 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType()); 5658 5659 // If we don't have an array, just use the results in splitType. 5660 if (!AT) { 5661 quals = splitType.Quals; 5662 return QualType(splitType.Ty, 0); 5663 } 5664 5665 // Otherwise, recurse on the array's element type. 5666 QualType elementType = AT->getElementType(); 5667 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals); 5668 5669 // If that didn't change the element type, AT has no qualifiers, so we 5670 // can just use the results in splitType. 5671 if (elementType == unqualElementType) { 5672 assert(quals.empty()); // from the recursive call 5673 quals = splitType.Quals; 5674 return QualType(splitType.Ty, 0); 5675 } 5676 5677 // Otherwise, add in the qualifiers from the outermost type, then 5678 // build the type back up. 5679 quals.addConsistentQualifiers(splitType.Quals); 5680 5681 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 5682 return getConstantArrayType(unqualElementType, CAT->getSize(), 5683 CAT->getSizeExpr(), CAT->getSizeModifier(), 0); 5684 } 5685 5686 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) { 5687 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0); 5688 } 5689 5690 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) { 5691 return getVariableArrayType(unqualElementType, 5692 VAT->getSizeExpr(), 5693 VAT->getSizeModifier(), 5694 VAT->getIndexTypeCVRQualifiers(), 5695 VAT->getBracketsRange()); 5696 } 5697 5698 const auto *DSAT = cast<DependentSizedArrayType>(AT); 5699 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(), 5700 DSAT->getSizeModifier(), 0, 5701 SourceRange()); 5702 } 5703 5704 /// Attempt to unwrap two types that may both be array types with the same bound 5705 /// (or both be array types of unknown bound) for the purpose of comparing the 5706 /// cv-decomposition of two types per C++ [conv.qual]. 5707 bool ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2) { 5708 bool UnwrappedAny = false; 5709 while (true) { 5710 auto *AT1 = getAsArrayType(T1); 5711 if (!AT1) return UnwrappedAny; 5712 5713 auto *AT2 = getAsArrayType(T2); 5714 if (!AT2) return UnwrappedAny; 5715 5716 // If we don't have two array types with the same constant bound nor two 5717 // incomplete array types, we've unwrapped everything we can. 5718 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) { 5719 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2); 5720 if (!CAT2 || CAT1->getSize() != CAT2->getSize()) 5721 return UnwrappedAny; 5722 } else if (!isa<IncompleteArrayType>(AT1) || 5723 !isa<IncompleteArrayType>(AT2)) { 5724 return UnwrappedAny; 5725 } 5726 5727 T1 = AT1->getElementType(); 5728 T2 = AT2->getElementType(); 5729 UnwrappedAny = true; 5730 } 5731 } 5732 5733 /// Attempt to unwrap two types that may be similar (C++ [conv.qual]). 5734 /// 5735 /// If T1 and T2 are both pointer types of the same kind, or both array types 5736 /// with the same bound, unwraps layers from T1 and T2 until a pointer type is 5737 /// unwrapped. Top-level qualifiers on T1 and T2 are ignored. 5738 /// 5739 /// This function will typically be called in a loop that successively 5740 /// "unwraps" pointer and pointer-to-member types to compare them at each 5741 /// level. 5742 /// 5743 /// \return \c true if a pointer type was unwrapped, \c false if we reached a 5744 /// pair of types that can't be unwrapped further. 5745 bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) { 5746 UnwrapSimilarArrayTypes(T1, T2); 5747 5748 const auto *T1PtrType = T1->getAs<PointerType>(); 5749 const auto *T2PtrType = T2->getAs<PointerType>(); 5750 if (T1PtrType && T2PtrType) { 5751 T1 = T1PtrType->getPointeeType(); 5752 T2 = T2PtrType->getPointeeType(); 5753 return true; 5754 } 5755 5756 const auto *T1MPType = T1->getAs<MemberPointerType>(); 5757 const auto *T2MPType = T2->getAs<MemberPointerType>(); 5758 if (T1MPType && T2MPType && 5759 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0), 5760 QualType(T2MPType->getClass(), 0))) { 5761 T1 = T1MPType->getPointeeType(); 5762 T2 = T2MPType->getPointeeType(); 5763 return true; 5764 } 5765 5766 if (getLangOpts().ObjC) { 5767 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>(); 5768 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>(); 5769 if (T1OPType && T2OPType) { 5770 T1 = T1OPType->getPointeeType(); 5771 T2 = T2OPType->getPointeeType(); 5772 return true; 5773 } 5774 } 5775 5776 // FIXME: Block pointers, too? 5777 5778 return false; 5779 } 5780 5781 bool ASTContext::hasSimilarType(QualType T1, QualType T2) { 5782 while (true) { 5783 Qualifiers Quals; 5784 T1 = getUnqualifiedArrayType(T1, Quals); 5785 T2 = getUnqualifiedArrayType(T2, Quals); 5786 if (hasSameType(T1, T2)) 5787 return true; 5788 if (!UnwrapSimilarTypes(T1, T2)) 5789 return false; 5790 } 5791 } 5792 5793 bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) { 5794 while (true) { 5795 Qualifiers Quals1, Quals2; 5796 T1 = getUnqualifiedArrayType(T1, Quals1); 5797 T2 = getUnqualifiedArrayType(T2, Quals2); 5798 5799 Quals1.removeCVRQualifiers(); 5800 Quals2.removeCVRQualifiers(); 5801 if (Quals1 != Quals2) 5802 return false; 5803 5804 if (hasSameType(T1, T2)) 5805 return true; 5806 5807 if (!UnwrapSimilarTypes(T1, T2)) 5808 return false; 5809 } 5810 } 5811 5812 DeclarationNameInfo 5813 ASTContext::getNameForTemplate(TemplateName Name, 5814 SourceLocation NameLoc) const { 5815 switch (Name.getKind()) { 5816 case TemplateName::QualifiedTemplate: 5817 case TemplateName::Template: 5818 // DNInfo work in progress: CHECKME: what about DNLoc? 5819 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(), 5820 NameLoc); 5821 5822 case TemplateName::OverloadedTemplate: { 5823 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate(); 5824 // DNInfo work in progress: CHECKME: what about DNLoc? 5825 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc); 5826 } 5827 5828 case TemplateName::AssumedTemplate: { 5829 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName(); 5830 return DeclarationNameInfo(Storage->getDeclName(), NameLoc); 5831 } 5832 5833 case TemplateName::DependentTemplate: { 5834 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 5835 DeclarationName DName; 5836 if (DTN->isIdentifier()) { 5837 DName = DeclarationNames.getIdentifier(DTN->getIdentifier()); 5838 return DeclarationNameInfo(DName, NameLoc); 5839 } else { 5840 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator()); 5841 // DNInfo work in progress: FIXME: source locations? 5842 DeclarationNameLoc DNLoc; 5843 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding(); 5844 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding(); 5845 return DeclarationNameInfo(DName, NameLoc, DNLoc); 5846 } 5847 } 5848 5849 case TemplateName::SubstTemplateTemplateParm: { 5850 SubstTemplateTemplateParmStorage *subst 5851 = Name.getAsSubstTemplateTemplateParm(); 5852 return DeclarationNameInfo(subst->getParameter()->getDeclName(), 5853 NameLoc); 5854 } 5855 5856 case TemplateName::SubstTemplateTemplateParmPack: { 5857 SubstTemplateTemplateParmPackStorage *subst 5858 = Name.getAsSubstTemplateTemplateParmPack(); 5859 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(), 5860 NameLoc); 5861 } 5862 } 5863 5864 llvm_unreachable("bad template name kind!"); 5865 } 5866 5867 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const { 5868 switch (Name.getKind()) { 5869 case TemplateName::QualifiedTemplate: 5870 case TemplateName::Template: { 5871 TemplateDecl *Template = Name.getAsTemplateDecl(); 5872 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template)) 5873 Template = getCanonicalTemplateTemplateParmDecl(TTP); 5874 5875 // The canonical template name is the canonical template declaration. 5876 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl())); 5877 } 5878 5879 case TemplateName::OverloadedTemplate: 5880 case TemplateName::AssumedTemplate: 5881 llvm_unreachable("cannot canonicalize unresolved template"); 5882 5883 case TemplateName::DependentTemplate: { 5884 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 5885 assert(DTN && "Non-dependent template names must refer to template decls."); 5886 return DTN->CanonicalTemplateName; 5887 } 5888 5889 case TemplateName::SubstTemplateTemplateParm: { 5890 SubstTemplateTemplateParmStorage *subst 5891 = Name.getAsSubstTemplateTemplateParm(); 5892 return getCanonicalTemplateName(subst->getReplacement()); 5893 } 5894 5895 case TemplateName::SubstTemplateTemplateParmPack: { 5896 SubstTemplateTemplateParmPackStorage *subst 5897 = Name.getAsSubstTemplateTemplateParmPack(); 5898 TemplateTemplateParmDecl *canonParameter 5899 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack()); 5900 TemplateArgument canonArgPack 5901 = getCanonicalTemplateArgument(subst->getArgumentPack()); 5902 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack); 5903 } 5904 } 5905 5906 llvm_unreachable("bad template name!"); 5907 } 5908 5909 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) { 5910 X = getCanonicalTemplateName(X); 5911 Y = getCanonicalTemplateName(Y); 5912 return X.getAsVoidPointer() == Y.getAsVoidPointer(); 5913 } 5914 5915 TemplateArgument 5916 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const { 5917 switch (Arg.getKind()) { 5918 case TemplateArgument::Null: 5919 return Arg; 5920 5921 case TemplateArgument::Expression: 5922 return Arg; 5923 5924 case TemplateArgument::Declaration: { 5925 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl()); 5926 return TemplateArgument(D, Arg.getParamTypeForDecl()); 5927 } 5928 5929 case TemplateArgument::NullPtr: 5930 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()), 5931 /*isNullPtr*/true); 5932 5933 case TemplateArgument::Template: 5934 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate())); 5935 5936 case TemplateArgument::TemplateExpansion: 5937 return TemplateArgument(getCanonicalTemplateName( 5938 Arg.getAsTemplateOrTemplatePattern()), 5939 Arg.getNumTemplateExpansions()); 5940 5941 case TemplateArgument::Integral: 5942 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType())); 5943 5944 case TemplateArgument::UncommonValue: 5945 return TemplateArgument(*this, 5946 getCanonicalType(Arg.getUncommonValueType()), 5947 Arg.getAsUncommonValue()); 5948 5949 case TemplateArgument::Type: 5950 return TemplateArgument(getCanonicalType(Arg.getAsType())); 5951 5952 case TemplateArgument::Pack: { 5953 if (Arg.pack_size() == 0) 5954 return Arg; 5955 5956 auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()]; 5957 unsigned Idx = 0; 5958 for (TemplateArgument::pack_iterator A = Arg.pack_begin(), 5959 AEnd = Arg.pack_end(); 5960 A != AEnd; (void)++A, ++Idx) 5961 CanonArgs[Idx] = getCanonicalTemplateArgument(*A); 5962 5963 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size())); 5964 } 5965 } 5966 5967 // Silence GCC warning 5968 llvm_unreachable("Unhandled template argument kind"); 5969 } 5970 5971 NestedNameSpecifier * 5972 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const { 5973 if (!NNS) 5974 return nullptr; 5975 5976 switch (NNS->getKind()) { 5977 case NestedNameSpecifier::Identifier: 5978 // Canonicalize the prefix but keep the identifier the same. 5979 return NestedNameSpecifier::Create(*this, 5980 getCanonicalNestedNameSpecifier(NNS->getPrefix()), 5981 NNS->getAsIdentifier()); 5982 5983 case NestedNameSpecifier::Namespace: 5984 // A namespace is canonical; build a nested-name-specifier with 5985 // this namespace and no prefix. 5986 return NestedNameSpecifier::Create(*this, nullptr, 5987 NNS->getAsNamespace()->getOriginalNamespace()); 5988 5989 case NestedNameSpecifier::NamespaceAlias: 5990 // A namespace is canonical; build a nested-name-specifier with 5991 // this namespace and no prefix. 5992 return NestedNameSpecifier::Create(*this, nullptr, 5993 NNS->getAsNamespaceAlias()->getNamespace() 5994 ->getOriginalNamespace()); 5995 5996 case NestedNameSpecifier::TypeSpec: 5997 case NestedNameSpecifier::TypeSpecWithTemplate: { 5998 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0)); 5999 6000 // If we have some kind of dependent-named type (e.g., "typename T::type"), 6001 // break it apart into its prefix and identifier, then reconsititute those 6002 // as the canonical nested-name-specifier. This is required to canonicalize 6003 // a dependent nested-name-specifier involving typedefs of dependent-name 6004 // types, e.g., 6005 // typedef typename T::type T1; 6006 // typedef typename T1::type T2; 6007 if (const auto *DNT = T->getAs<DependentNameType>()) 6008 return NestedNameSpecifier::Create(*this, DNT->getQualifier(), 6009 const_cast<IdentifierInfo *>(DNT->getIdentifier())); 6010 6011 // Otherwise, just canonicalize the type, and force it to be a TypeSpec. 6012 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the 6013 // first place? 6014 return NestedNameSpecifier::Create(*this, nullptr, false, 6015 const_cast<Type *>(T.getTypePtr())); 6016 } 6017 6018 case NestedNameSpecifier::Global: 6019 case NestedNameSpecifier::Super: 6020 // The global specifier and __super specifer are canonical and unique. 6021 return NNS; 6022 } 6023 6024 llvm_unreachable("Invalid NestedNameSpecifier::Kind!"); 6025 } 6026 6027 const ArrayType *ASTContext::getAsArrayType(QualType T) const { 6028 // Handle the non-qualified case efficiently. 6029 if (!T.hasLocalQualifiers()) { 6030 // Handle the common positive case fast. 6031 if (const auto *AT = dyn_cast<ArrayType>(T)) 6032 return AT; 6033 } 6034 6035 // Handle the common negative case fast. 6036 if (!isa<ArrayType>(T.getCanonicalType())) 6037 return nullptr; 6038 6039 // Apply any qualifiers from the array type to the element type. This 6040 // implements C99 6.7.3p8: "If the specification of an array type includes 6041 // any type qualifiers, the element type is so qualified, not the array type." 6042 6043 // If we get here, we either have type qualifiers on the type, or we have 6044 // sugar such as a typedef in the way. If we have type qualifiers on the type 6045 // we must propagate them down into the element type. 6046 6047 SplitQualType split = T.getSplitDesugaredType(); 6048 Qualifiers qs = split.Quals; 6049 6050 // If we have a simple case, just return now. 6051 const auto *ATy = dyn_cast<ArrayType>(split.Ty); 6052 if (!ATy || qs.empty()) 6053 return ATy; 6054 6055 // Otherwise, we have an array and we have qualifiers on it. Push the 6056 // qualifiers into the array element type and return a new array type. 6057 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs); 6058 6059 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy)) 6060 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(), 6061 CAT->getSizeExpr(), 6062 CAT->getSizeModifier(), 6063 CAT->getIndexTypeCVRQualifiers())); 6064 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy)) 6065 return cast<ArrayType>(getIncompleteArrayType(NewEltTy, 6066 IAT->getSizeModifier(), 6067 IAT->getIndexTypeCVRQualifiers())); 6068 6069 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy)) 6070 return cast<ArrayType>( 6071 getDependentSizedArrayType(NewEltTy, 6072 DSAT->getSizeExpr(), 6073 DSAT->getSizeModifier(), 6074 DSAT->getIndexTypeCVRQualifiers(), 6075 DSAT->getBracketsRange())); 6076 6077 const auto *VAT = cast<VariableArrayType>(ATy); 6078 return cast<ArrayType>(getVariableArrayType(NewEltTy, 6079 VAT->getSizeExpr(), 6080 VAT->getSizeModifier(), 6081 VAT->getIndexTypeCVRQualifiers(), 6082 VAT->getBracketsRange())); 6083 } 6084 6085 QualType ASTContext::getAdjustedParameterType(QualType T) const { 6086 if (T->isArrayType() || T->isFunctionType()) 6087 return getDecayedType(T); 6088 return T; 6089 } 6090 6091 QualType ASTContext::getSignatureParameterType(QualType T) const { 6092 T = getVariableArrayDecayedType(T); 6093 T = getAdjustedParameterType(T); 6094 return T.getUnqualifiedType(); 6095 } 6096 6097 QualType ASTContext::getExceptionObjectType(QualType T) const { 6098 // C++ [except.throw]p3: 6099 // A throw-expression initializes a temporary object, called the exception 6100 // object, the type of which is determined by removing any top-level 6101 // cv-qualifiers from the static type of the operand of throw and adjusting 6102 // the type from "array of T" or "function returning T" to "pointer to T" 6103 // or "pointer to function returning T", [...] 6104 T = getVariableArrayDecayedType(T); 6105 if (T->isArrayType() || T->isFunctionType()) 6106 T = getDecayedType(T); 6107 return T.getUnqualifiedType(); 6108 } 6109 6110 /// getArrayDecayedType - Return the properly qualified result of decaying the 6111 /// specified array type to a pointer. This operation is non-trivial when 6112 /// handling typedefs etc. The canonical type of "T" must be an array type, 6113 /// this returns a pointer to a properly qualified element of the array. 6114 /// 6115 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3. 6116 QualType ASTContext::getArrayDecayedType(QualType Ty) const { 6117 // Get the element type with 'getAsArrayType' so that we don't lose any 6118 // typedefs in the element type of the array. This also handles propagation 6119 // of type qualifiers from the array type into the element type if present 6120 // (C99 6.7.3p8). 6121 const ArrayType *PrettyArrayType = getAsArrayType(Ty); 6122 assert(PrettyArrayType && "Not an array type!"); 6123 6124 QualType PtrTy = getPointerType(PrettyArrayType->getElementType()); 6125 6126 // int x[restrict 4] -> int *restrict 6127 QualType Result = getQualifiedType(PtrTy, 6128 PrettyArrayType->getIndexTypeQualifiers()); 6129 6130 // int x[_Nullable] -> int * _Nullable 6131 if (auto Nullability = Ty->getNullability(*this)) { 6132 Result = const_cast<ASTContext *>(this)->getAttributedType( 6133 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result); 6134 } 6135 return Result; 6136 } 6137 6138 QualType ASTContext::getBaseElementType(const ArrayType *array) const { 6139 return getBaseElementType(array->getElementType()); 6140 } 6141 6142 QualType ASTContext::getBaseElementType(QualType type) const { 6143 Qualifiers qs; 6144 while (true) { 6145 SplitQualType split = type.getSplitDesugaredType(); 6146 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe(); 6147 if (!array) break; 6148 6149 type = array->getElementType(); 6150 qs.addConsistentQualifiers(split.Quals); 6151 } 6152 6153 return getQualifiedType(type, qs); 6154 } 6155 6156 /// getConstantArrayElementCount - Returns number of constant array elements. 6157 uint64_t 6158 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const { 6159 uint64_t ElementCount = 1; 6160 do { 6161 ElementCount *= CA->getSize().getZExtValue(); 6162 CA = dyn_cast_or_null<ConstantArrayType>( 6163 CA->getElementType()->getAsArrayTypeUnsafe()); 6164 } while (CA); 6165 return ElementCount; 6166 } 6167 6168 /// getFloatingRank - Return a relative rank for floating point types. 6169 /// This routine will assert if passed a built-in type that isn't a float. 6170 static FloatingRank getFloatingRank(QualType T) { 6171 if (const auto *CT = T->getAs<ComplexType>()) 6172 return getFloatingRank(CT->getElementType()); 6173 6174 switch (T->castAs<BuiltinType>()->getKind()) { 6175 default: llvm_unreachable("getFloatingRank(): not a floating type"); 6176 case BuiltinType::Float16: return Float16Rank; 6177 case BuiltinType::Half: return HalfRank; 6178 case BuiltinType::Float: return FloatRank; 6179 case BuiltinType::Double: return DoubleRank; 6180 case BuiltinType::LongDouble: return LongDoubleRank; 6181 case BuiltinType::Float128: return Float128Rank; 6182 case BuiltinType::BFloat16: return BFloat16Rank; 6183 } 6184 } 6185 6186 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating 6187 /// point or a complex type (based on typeDomain/typeSize). 6188 /// 'typeDomain' is a real floating point or complex type. 6189 /// 'typeSize' is a real floating point or complex type. 6190 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size, 6191 QualType Domain) const { 6192 FloatingRank EltRank = getFloatingRank(Size); 6193 if (Domain->isComplexType()) { 6194 switch (EltRank) { 6195 case BFloat16Rank: llvm_unreachable("Complex bfloat16 is not supported"); 6196 case Float16Rank: 6197 case HalfRank: llvm_unreachable("Complex half is not supported"); 6198 case FloatRank: return FloatComplexTy; 6199 case DoubleRank: return DoubleComplexTy; 6200 case LongDoubleRank: return LongDoubleComplexTy; 6201 case Float128Rank: return Float128ComplexTy; 6202 } 6203 } 6204 6205 assert(Domain->isRealFloatingType() && "Unknown domain!"); 6206 switch (EltRank) { 6207 case Float16Rank: return HalfTy; 6208 case BFloat16Rank: return BFloat16Ty; 6209 case HalfRank: return HalfTy; 6210 case FloatRank: return FloatTy; 6211 case DoubleRank: return DoubleTy; 6212 case LongDoubleRank: return LongDoubleTy; 6213 case Float128Rank: return Float128Ty; 6214 } 6215 llvm_unreachable("getFloatingRank(): illegal value for rank"); 6216 } 6217 6218 /// getFloatingTypeOrder - Compare the rank of the two specified floating 6219 /// point types, ignoring the domain of the type (i.e. 'double' == 6220 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If 6221 /// LHS < RHS, return -1. 6222 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const { 6223 FloatingRank LHSR = getFloatingRank(LHS); 6224 FloatingRank RHSR = getFloatingRank(RHS); 6225 6226 if (LHSR == RHSR) 6227 return 0; 6228 if (LHSR > RHSR) 6229 return 1; 6230 return -1; 6231 } 6232 6233 int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const { 6234 if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS)) 6235 return 0; 6236 return getFloatingTypeOrder(LHS, RHS); 6237 } 6238 6239 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This 6240 /// routine will assert if passed a built-in type that isn't an integer or enum, 6241 /// or if it is not canonicalized. 6242 unsigned ASTContext::getIntegerRank(const Type *T) const { 6243 assert(T->isCanonicalUnqualified() && "T should be canonicalized"); 6244 6245 // Results in this 'losing' to any type of the same size, but winning if 6246 // larger. 6247 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 6248 return 0 + (EIT->getNumBits() << 3); 6249 6250 switch (cast<BuiltinType>(T)->getKind()) { 6251 default: llvm_unreachable("getIntegerRank(): not a built-in integer"); 6252 case BuiltinType::Bool: 6253 return 1 + (getIntWidth(BoolTy) << 3); 6254 case BuiltinType::Char_S: 6255 case BuiltinType::Char_U: 6256 case BuiltinType::SChar: 6257 case BuiltinType::UChar: 6258 return 2 + (getIntWidth(CharTy) << 3); 6259 case BuiltinType::Short: 6260 case BuiltinType::UShort: 6261 return 3 + (getIntWidth(ShortTy) << 3); 6262 case BuiltinType::Int: 6263 case BuiltinType::UInt: 6264 return 4 + (getIntWidth(IntTy) << 3); 6265 case BuiltinType::Long: 6266 case BuiltinType::ULong: 6267 return 5 + (getIntWidth(LongTy) << 3); 6268 case BuiltinType::LongLong: 6269 case BuiltinType::ULongLong: 6270 return 6 + (getIntWidth(LongLongTy) << 3); 6271 case BuiltinType::Int128: 6272 case BuiltinType::UInt128: 6273 return 7 + (getIntWidth(Int128Ty) << 3); 6274 } 6275 } 6276 6277 /// Whether this is a promotable bitfield reference according 6278 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions). 6279 /// 6280 /// \returns the type this bit-field will promote to, or NULL if no 6281 /// promotion occurs. 6282 QualType ASTContext::isPromotableBitField(Expr *E) const { 6283 if (E->isTypeDependent() || E->isValueDependent()) 6284 return {}; 6285 6286 // C++ [conv.prom]p5: 6287 // If the bit-field has an enumerated type, it is treated as any other 6288 // value of that type for promotion purposes. 6289 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType()) 6290 return {}; 6291 6292 // FIXME: We should not do this unless E->refersToBitField() is true. This 6293 // matters in C where getSourceBitField() will find bit-fields for various 6294 // cases where the source expression is not a bit-field designator. 6295 6296 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields? 6297 if (!Field) 6298 return {}; 6299 6300 QualType FT = Field->getType(); 6301 6302 uint64_t BitWidth = Field->getBitWidthValue(*this); 6303 uint64_t IntSize = getTypeSize(IntTy); 6304 // C++ [conv.prom]p5: 6305 // A prvalue for an integral bit-field can be converted to a prvalue of type 6306 // int if int can represent all the values of the bit-field; otherwise, it 6307 // can be converted to unsigned int if unsigned int can represent all the 6308 // values of the bit-field. If the bit-field is larger yet, no integral 6309 // promotion applies to it. 6310 // C11 6.3.1.1/2: 6311 // [For a bit-field of type _Bool, int, signed int, or unsigned int:] 6312 // If an int can represent all values of the original type (as restricted by 6313 // the width, for a bit-field), the value is converted to an int; otherwise, 6314 // it is converted to an unsigned int. 6315 // 6316 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int. 6317 // We perform that promotion here to match GCC and C++. 6318 // FIXME: C does not permit promotion of an enum bit-field whose rank is 6319 // greater than that of 'int'. We perform that promotion to match GCC. 6320 if (BitWidth < IntSize) 6321 return IntTy; 6322 6323 if (BitWidth == IntSize) 6324 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy; 6325 6326 // Bit-fields wider than int are not subject to promotions, and therefore act 6327 // like the base type. GCC has some weird bugs in this area that we 6328 // deliberately do not follow (GCC follows a pre-standard resolution to 6329 // C's DR315 which treats bit-width as being part of the type, and this leaks 6330 // into their semantics in some cases). 6331 return {}; 6332 } 6333 6334 /// getPromotedIntegerType - Returns the type that Promotable will 6335 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable 6336 /// integer type. 6337 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const { 6338 assert(!Promotable.isNull()); 6339 assert(Promotable->isPromotableIntegerType()); 6340 if (const auto *ET = Promotable->getAs<EnumType>()) 6341 return ET->getDecl()->getPromotionType(); 6342 6343 if (const auto *BT = Promotable->getAs<BuiltinType>()) { 6344 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t 6345 // (3.9.1) can be converted to a prvalue of the first of the following 6346 // types that can represent all the values of its underlying type: 6347 // int, unsigned int, long int, unsigned long int, long long int, or 6348 // unsigned long long int [...] 6349 // FIXME: Is there some better way to compute this? 6350 if (BT->getKind() == BuiltinType::WChar_S || 6351 BT->getKind() == BuiltinType::WChar_U || 6352 BT->getKind() == BuiltinType::Char8 || 6353 BT->getKind() == BuiltinType::Char16 || 6354 BT->getKind() == BuiltinType::Char32) { 6355 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S; 6356 uint64_t FromSize = getTypeSize(BT); 6357 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy, 6358 LongLongTy, UnsignedLongLongTy }; 6359 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) { 6360 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]); 6361 if (FromSize < ToSize || 6362 (FromSize == ToSize && 6363 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) 6364 return PromoteTypes[Idx]; 6365 } 6366 llvm_unreachable("char type should fit into long long"); 6367 } 6368 } 6369 6370 // At this point, we should have a signed or unsigned integer type. 6371 if (Promotable->isSignedIntegerType()) 6372 return IntTy; 6373 uint64_t PromotableSize = getIntWidth(Promotable); 6374 uint64_t IntSize = getIntWidth(IntTy); 6375 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize); 6376 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy; 6377 } 6378 6379 /// Recurses in pointer/array types until it finds an objc retainable 6380 /// type and returns its ownership. 6381 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const { 6382 while (!T.isNull()) { 6383 if (T.getObjCLifetime() != Qualifiers::OCL_None) 6384 return T.getObjCLifetime(); 6385 if (T->isArrayType()) 6386 T = getBaseElementType(T); 6387 else if (const auto *PT = T->getAs<PointerType>()) 6388 T = PT->getPointeeType(); 6389 else if (const auto *RT = T->getAs<ReferenceType>()) 6390 T = RT->getPointeeType(); 6391 else 6392 break; 6393 } 6394 6395 return Qualifiers::OCL_None; 6396 } 6397 6398 static const Type *getIntegerTypeForEnum(const EnumType *ET) { 6399 // Incomplete enum types are not treated as integer types. 6400 // FIXME: In C++, enum types are never integer types. 6401 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped()) 6402 return ET->getDecl()->getIntegerType().getTypePtr(); 6403 return nullptr; 6404 } 6405 6406 /// getIntegerTypeOrder - Returns the highest ranked integer type: 6407 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If 6408 /// LHS < RHS, return -1. 6409 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const { 6410 const Type *LHSC = getCanonicalType(LHS).getTypePtr(); 6411 const Type *RHSC = getCanonicalType(RHS).getTypePtr(); 6412 6413 // Unwrap enums to their underlying type. 6414 if (const auto *ET = dyn_cast<EnumType>(LHSC)) 6415 LHSC = getIntegerTypeForEnum(ET); 6416 if (const auto *ET = dyn_cast<EnumType>(RHSC)) 6417 RHSC = getIntegerTypeForEnum(ET); 6418 6419 if (LHSC == RHSC) return 0; 6420 6421 bool LHSUnsigned = LHSC->isUnsignedIntegerType(); 6422 bool RHSUnsigned = RHSC->isUnsignedIntegerType(); 6423 6424 unsigned LHSRank = getIntegerRank(LHSC); 6425 unsigned RHSRank = getIntegerRank(RHSC); 6426 6427 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned. 6428 if (LHSRank == RHSRank) return 0; 6429 return LHSRank > RHSRank ? 1 : -1; 6430 } 6431 6432 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa. 6433 if (LHSUnsigned) { 6434 // If the unsigned [LHS] type is larger, return it. 6435 if (LHSRank >= RHSRank) 6436 return 1; 6437 6438 // If the signed type can represent all values of the unsigned type, it 6439 // wins. Because we are dealing with 2's complement and types that are 6440 // powers of two larger than each other, this is always safe. 6441 return -1; 6442 } 6443 6444 // If the unsigned [RHS] type is larger, return it. 6445 if (RHSRank >= LHSRank) 6446 return -1; 6447 6448 // If the signed type can represent all values of the unsigned type, it 6449 // wins. Because we are dealing with 2's complement and types that are 6450 // powers of two larger than each other, this is always safe. 6451 return 1; 6452 } 6453 6454 TypedefDecl *ASTContext::getCFConstantStringDecl() const { 6455 if (CFConstantStringTypeDecl) 6456 return CFConstantStringTypeDecl; 6457 6458 assert(!CFConstantStringTagDecl && 6459 "tag and typedef should be initialized together"); 6460 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag"); 6461 CFConstantStringTagDecl->startDefinition(); 6462 6463 struct { 6464 QualType Type; 6465 const char *Name; 6466 } Fields[5]; 6467 unsigned Count = 0; 6468 6469 /// Objective-C ABI 6470 /// 6471 /// typedef struct __NSConstantString_tag { 6472 /// const int *isa; 6473 /// int flags; 6474 /// const char *str; 6475 /// long length; 6476 /// } __NSConstantString; 6477 /// 6478 /// Swift ABI (4.1, 4.2) 6479 /// 6480 /// typedef struct __NSConstantString_tag { 6481 /// uintptr_t _cfisa; 6482 /// uintptr_t _swift_rc; 6483 /// _Atomic(uint64_t) _cfinfoa; 6484 /// const char *_ptr; 6485 /// uint32_t _length; 6486 /// } __NSConstantString; 6487 /// 6488 /// Swift ABI (5.0) 6489 /// 6490 /// typedef struct __NSConstantString_tag { 6491 /// uintptr_t _cfisa; 6492 /// uintptr_t _swift_rc; 6493 /// _Atomic(uint64_t) _cfinfoa; 6494 /// const char *_ptr; 6495 /// uintptr_t _length; 6496 /// } __NSConstantString; 6497 6498 const auto CFRuntime = getLangOpts().CFRuntime; 6499 if (static_cast<unsigned>(CFRuntime) < 6500 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) { 6501 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" }; 6502 Fields[Count++] = { IntTy, "flags" }; 6503 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" }; 6504 Fields[Count++] = { LongTy, "length" }; 6505 } else { 6506 Fields[Count++] = { getUIntPtrType(), "_cfisa" }; 6507 Fields[Count++] = { getUIntPtrType(), "_swift_rc" }; 6508 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" }; 6509 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" }; 6510 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 || 6511 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2) 6512 Fields[Count++] = { IntTy, "_ptr" }; 6513 else 6514 Fields[Count++] = { getUIntPtrType(), "_ptr" }; 6515 } 6516 6517 // Create fields 6518 for (unsigned i = 0; i < Count; ++i) { 6519 FieldDecl *Field = 6520 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(), 6521 SourceLocation(), &Idents.get(Fields[i].Name), 6522 Fields[i].Type, /*TInfo=*/nullptr, 6523 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); 6524 Field->setAccess(AS_public); 6525 CFConstantStringTagDecl->addDecl(Field); 6526 } 6527 6528 CFConstantStringTagDecl->completeDefinition(); 6529 // This type is designed to be compatible with NSConstantString, but cannot 6530 // use the same name, since NSConstantString is an interface. 6531 auto tagType = getTagDeclType(CFConstantStringTagDecl); 6532 CFConstantStringTypeDecl = 6533 buildImplicitTypedef(tagType, "__NSConstantString"); 6534 6535 return CFConstantStringTypeDecl; 6536 } 6537 6538 RecordDecl *ASTContext::getCFConstantStringTagDecl() const { 6539 if (!CFConstantStringTagDecl) 6540 getCFConstantStringDecl(); // Build the tag and the typedef. 6541 return CFConstantStringTagDecl; 6542 } 6543 6544 // getCFConstantStringType - Return the type used for constant CFStrings. 6545 QualType ASTContext::getCFConstantStringType() const { 6546 return getTypedefType(getCFConstantStringDecl()); 6547 } 6548 6549 QualType ASTContext::getObjCSuperType() const { 6550 if (ObjCSuperType.isNull()) { 6551 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super"); 6552 TUDecl->addDecl(ObjCSuperTypeDecl); 6553 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl); 6554 } 6555 return ObjCSuperType; 6556 } 6557 6558 void ASTContext::setCFConstantStringType(QualType T) { 6559 const auto *TD = T->castAs<TypedefType>(); 6560 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl()); 6561 const auto *TagType = 6562 CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>(); 6563 CFConstantStringTagDecl = TagType->getDecl(); 6564 } 6565 6566 QualType ASTContext::getBlockDescriptorType() const { 6567 if (BlockDescriptorType) 6568 return getTagDeclType(BlockDescriptorType); 6569 6570 RecordDecl *RD; 6571 // FIXME: Needs the FlagAppleBlock bit. 6572 RD = buildImplicitRecord("__block_descriptor"); 6573 RD->startDefinition(); 6574 6575 QualType FieldTypes[] = { 6576 UnsignedLongTy, 6577 UnsignedLongTy, 6578 }; 6579 6580 static const char *const FieldNames[] = { 6581 "reserved", 6582 "Size" 6583 }; 6584 6585 for (size_t i = 0; i < 2; ++i) { 6586 FieldDecl *Field = FieldDecl::Create( 6587 *this, RD, SourceLocation(), SourceLocation(), 6588 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, 6589 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); 6590 Field->setAccess(AS_public); 6591 RD->addDecl(Field); 6592 } 6593 6594 RD->completeDefinition(); 6595 6596 BlockDescriptorType = RD; 6597 6598 return getTagDeclType(BlockDescriptorType); 6599 } 6600 6601 QualType ASTContext::getBlockDescriptorExtendedType() const { 6602 if (BlockDescriptorExtendedType) 6603 return getTagDeclType(BlockDescriptorExtendedType); 6604 6605 RecordDecl *RD; 6606 // FIXME: Needs the FlagAppleBlock bit. 6607 RD = buildImplicitRecord("__block_descriptor_withcopydispose"); 6608 RD->startDefinition(); 6609 6610 QualType FieldTypes[] = { 6611 UnsignedLongTy, 6612 UnsignedLongTy, 6613 getPointerType(VoidPtrTy), 6614 getPointerType(VoidPtrTy) 6615 }; 6616 6617 static const char *const FieldNames[] = { 6618 "reserved", 6619 "Size", 6620 "CopyFuncPtr", 6621 "DestroyFuncPtr" 6622 }; 6623 6624 for (size_t i = 0; i < 4; ++i) { 6625 FieldDecl *Field = FieldDecl::Create( 6626 *this, RD, SourceLocation(), SourceLocation(), 6627 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, 6628 /*BitWidth=*/nullptr, 6629 /*Mutable=*/false, ICIS_NoInit); 6630 Field->setAccess(AS_public); 6631 RD->addDecl(Field); 6632 } 6633 6634 RD->completeDefinition(); 6635 6636 BlockDescriptorExtendedType = RD; 6637 return getTagDeclType(BlockDescriptorExtendedType); 6638 } 6639 6640 OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const { 6641 const auto *BT = dyn_cast<BuiltinType>(T); 6642 6643 if (!BT) { 6644 if (isa<PipeType>(T)) 6645 return OCLTK_Pipe; 6646 6647 return OCLTK_Default; 6648 } 6649 6650 switch (BT->getKind()) { 6651 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6652 case BuiltinType::Id: \ 6653 return OCLTK_Image; 6654 #include "clang/Basic/OpenCLImageTypes.def" 6655 6656 case BuiltinType::OCLClkEvent: 6657 return OCLTK_ClkEvent; 6658 6659 case BuiltinType::OCLEvent: 6660 return OCLTK_Event; 6661 6662 case BuiltinType::OCLQueue: 6663 return OCLTK_Queue; 6664 6665 case BuiltinType::OCLReserveID: 6666 return OCLTK_ReserveID; 6667 6668 case BuiltinType::OCLSampler: 6669 return OCLTK_Sampler; 6670 6671 default: 6672 return OCLTK_Default; 6673 } 6674 } 6675 6676 LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const { 6677 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)); 6678 } 6679 6680 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty" 6681 /// requires copy/dispose. Note that this must match the logic 6682 /// in buildByrefHelpers. 6683 bool ASTContext::BlockRequiresCopying(QualType Ty, 6684 const VarDecl *D) { 6685 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) { 6686 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr(); 6687 if (!copyExpr && record->hasTrivialDestructor()) return false; 6688 6689 return true; 6690 } 6691 6692 // The block needs copy/destroy helpers if Ty is non-trivial to destructively 6693 // move or destroy. 6694 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType()) 6695 return true; 6696 6697 if (!Ty->isObjCRetainableType()) return false; 6698 6699 Qualifiers qs = Ty.getQualifiers(); 6700 6701 // If we have lifetime, that dominates. 6702 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) { 6703 switch (lifetime) { 6704 case Qualifiers::OCL_None: llvm_unreachable("impossible"); 6705 6706 // These are just bits as far as the runtime is concerned. 6707 case Qualifiers::OCL_ExplicitNone: 6708 case Qualifiers::OCL_Autoreleasing: 6709 return false; 6710 6711 // These cases should have been taken care of when checking the type's 6712 // non-triviality. 6713 case Qualifiers::OCL_Weak: 6714 case Qualifiers::OCL_Strong: 6715 llvm_unreachable("impossible"); 6716 } 6717 llvm_unreachable("fell out of lifetime switch!"); 6718 } 6719 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) || 6720 Ty->isObjCObjectPointerType()); 6721 } 6722 6723 bool ASTContext::getByrefLifetime(QualType Ty, 6724 Qualifiers::ObjCLifetime &LifeTime, 6725 bool &HasByrefExtendedLayout) const { 6726 if (!getLangOpts().ObjC || 6727 getLangOpts().getGC() != LangOptions::NonGC) 6728 return false; 6729 6730 HasByrefExtendedLayout = false; 6731 if (Ty->isRecordType()) { 6732 HasByrefExtendedLayout = true; 6733 LifeTime = Qualifiers::OCL_None; 6734 } else if ((LifeTime = Ty.getObjCLifetime())) { 6735 // Honor the ARC qualifiers. 6736 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) { 6737 // The MRR rule. 6738 LifeTime = Qualifiers::OCL_ExplicitNone; 6739 } else { 6740 LifeTime = Qualifiers::OCL_None; 6741 } 6742 return true; 6743 } 6744 6745 CanQualType ASTContext::getNSUIntegerType() const { 6746 assert(Target && "Expected target to be initialized"); 6747 const llvm::Triple &T = Target->getTriple(); 6748 // Windows is LLP64 rather than LP64 6749 if (T.isOSWindows() && T.isArch64Bit()) 6750 return UnsignedLongLongTy; 6751 return UnsignedLongTy; 6752 } 6753 6754 CanQualType ASTContext::getNSIntegerType() const { 6755 assert(Target && "Expected target to be initialized"); 6756 const llvm::Triple &T = Target->getTriple(); 6757 // Windows is LLP64 rather than LP64 6758 if (T.isOSWindows() && T.isArch64Bit()) 6759 return LongLongTy; 6760 return LongTy; 6761 } 6762 6763 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() { 6764 if (!ObjCInstanceTypeDecl) 6765 ObjCInstanceTypeDecl = 6766 buildImplicitTypedef(getObjCIdType(), "instancetype"); 6767 return ObjCInstanceTypeDecl; 6768 } 6769 6770 // This returns true if a type has been typedefed to BOOL: 6771 // typedef <type> BOOL; 6772 static bool isTypeTypedefedAsBOOL(QualType T) { 6773 if (const auto *TT = dyn_cast<TypedefType>(T)) 6774 if (IdentifierInfo *II = TT->getDecl()->getIdentifier()) 6775 return II->isStr("BOOL"); 6776 6777 return false; 6778 } 6779 6780 /// getObjCEncodingTypeSize returns size of type for objective-c encoding 6781 /// purpose. 6782 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const { 6783 if (!type->isIncompleteArrayType() && type->isIncompleteType()) 6784 return CharUnits::Zero(); 6785 6786 CharUnits sz = getTypeSizeInChars(type); 6787 6788 // Make all integer and enum types at least as large as an int 6789 if (sz.isPositive() && type->isIntegralOrEnumerationType()) 6790 sz = std::max(sz, getTypeSizeInChars(IntTy)); 6791 // Treat arrays as pointers, since that's how they're passed in. 6792 else if (type->isArrayType()) 6793 sz = getTypeSizeInChars(VoidPtrTy); 6794 return sz; 6795 } 6796 6797 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const { 6798 return getTargetInfo().getCXXABI().isMicrosoft() && 6799 VD->isStaticDataMember() && 6800 VD->getType()->isIntegralOrEnumerationType() && 6801 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit(); 6802 } 6803 6804 ASTContext::InlineVariableDefinitionKind 6805 ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const { 6806 if (!VD->isInline()) 6807 return InlineVariableDefinitionKind::None; 6808 6809 // In almost all cases, it's a weak definition. 6810 auto *First = VD->getFirstDecl(); 6811 if (First->isInlineSpecified() || !First->isStaticDataMember()) 6812 return InlineVariableDefinitionKind::Weak; 6813 6814 // If there's a file-context declaration in this translation unit, it's a 6815 // non-discardable definition. 6816 for (auto *D : VD->redecls()) 6817 if (D->getLexicalDeclContext()->isFileContext() && 6818 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr())) 6819 return InlineVariableDefinitionKind::Strong; 6820 6821 // If we've not seen one yet, we don't know. 6822 return InlineVariableDefinitionKind::WeakUnknown; 6823 } 6824 6825 static std::string charUnitsToString(const CharUnits &CU) { 6826 return llvm::itostr(CU.getQuantity()); 6827 } 6828 6829 /// getObjCEncodingForBlock - Return the encoded type for this block 6830 /// declaration. 6831 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const { 6832 std::string S; 6833 6834 const BlockDecl *Decl = Expr->getBlockDecl(); 6835 QualType BlockTy = 6836 Expr->getType()->castAs<BlockPointerType>()->getPointeeType(); 6837 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType(); 6838 // Encode result type. 6839 if (getLangOpts().EncodeExtendedBlockSig) 6840 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, BlockReturnTy, S, 6841 true /*Extended*/); 6842 else 6843 getObjCEncodingForType(BlockReturnTy, S); 6844 // Compute size of all parameters. 6845 // Start with computing size of a pointer in number of bytes. 6846 // FIXME: There might(should) be a better way of doing this computation! 6847 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 6848 CharUnits ParmOffset = PtrSize; 6849 for (auto PI : Decl->parameters()) { 6850 QualType PType = PI->getType(); 6851 CharUnits sz = getObjCEncodingTypeSize(PType); 6852 if (sz.isZero()) 6853 continue; 6854 assert(sz.isPositive() && "BlockExpr - Incomplete param type"); 6855 ParmOffset += sz; 6856 } 6857 // Size of the argument frame 6858 S += charUnitsToString(ParmOffset); 6859 // Block pointer and offset. 6860 S += "@?0"; 6861 6862 // Argument types. 6863 ParmOffset = PtrSize; 6864 for (auto PVDecl : Decl->parameters()) { 6865 QualType PType = PVDecl->getOriginalType(); 6866 if (const auto *AT = 6867 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 6868 // Use array's original type only if it has known number of 6869 // elements. 6870 if (!isa<ConstantArrayType>(AT)) 6871 PType = PVDecl->getType(); 6872 } else if (PType->isFunctionType()) 6873 PType = PVDecl->getType(); 6874 if (getLangOpts().EncodeExtendedBlockSig) 6875 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType, 6876 S, true /*Extended*/); 6877 else 6878 getObjCEncodingForType(PType, S); 6879 S += charUnitsToString(ParmOffset); 6880 ParmOffset += getObjCEncodingTypeSize(PType); 6881 } 6882 6883 return S; 6884 } 6885 6886 std::string 6887 ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const { 6888 std::string S; 6889 // Encode result type. 6890 getObjCEncodingForType(Decl->getReturnType(), S); 6891 CharUnits ParmOffset; 6892 // Compute size of all parameters. 6893 for (auto PI : Decl->parameters()) { 6894 QualType PType = PI->getType(); 6895 CharUnits sz = getObjCEncodingTypeSize(PType); 6896 if (sz.isZero()) 6897 continue; 6898 6899 assert(sz.isPositive() && 6900 "getObjCEncodingForFunctionDecl - Incomplete param type"); 6901 ParmOffset += sz; 6902 } 6903 S += charUnitsToString(ParmOffset); 6904 ParmOffset = CharUnits::Zero(); 6905 6906 // Argument types. 6907 for (auto PVDecl : Decl->parameters()) { 6908 QualType PType = PVDecl->getOriginalType(); 6909 if (const auto *AT = 6910 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 6911 // Use array's original type only if it has known number of 6912 // elements. 6913 if (!isa<ConstantArrayType>(AT)) 6914 PType = PVDecl->getType(); 6915 } else if (PType->isFunctionType()) 6916 PType = PVDecl->getType(); 6917 getObjCEncodingForType(PType, S); 6918 S += charUnitsToString(ParmOffset); 6919 ParmOffset += getObjCEncodingTypeSize(PType); 6920 } 6921 6922 return S; 6923 } 6924 6925 /// getObjCEncodingForMethodParameter - Return the encoded type for a single 6926 /// method parameter or return type. If Extended, include class names and 6927 /// block object types. 6928 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, 6929 QualType T, std::string& S, 6930 bool Extended) const { 6931 // Encode type qualifer, 'in', 'inout', etc. for the parameter. 6932 getObjCEncodingForTypeQualifier(QT, S); 6933 // Encode parameter type. 6934 ObjCEncOptions Options = ObjCEncOptions() 6935 .setExpandPointedToStructures() 6936 .setExpandStructures() 6937 .setIsOutermostType(); 6938 if (Extended) 6939 Options.setEncodeBlockParameters().setEncodeClassNames(); 6940 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr); 6941 } 6942 6943 /// getObjCEncodingForMethodDecl - Return the encoded type for this method 6944 /// declaration. 6945 std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, 6946 bool Extended) const { 6947 // FIXME: This is not very efficient. 6948 // Encode return type. 6949 std::string S; 6950 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(), 6951 Decl->getReturnType(), S, Extended); 6952 // Compute size of all parameters. 6953 // Start with computing size of a pointer in number of bytes. 6954 // FIXME: There might(should) be a better way of doing this computation! 6955 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 6956 // The first two arguments (self and _cmd) are pointers; account for 6957 // their size. 6958 CharUnits ParmOffset = 2 * PtrSize; 6959 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 6960 E = Decl->sel_param_end(); PI != E; ++PI) { 6961 QualType PType = (*PI)->getType(); 6962 CharUnits sz = getObjCEncodingTypeSize(PType); 6963 if (sz.isZero()) 6964 continue; 6965 6966 assert(sz.isPositive() && 6967 "getObjCEncodingForMethodDecl - Incomplete param type"); 6968 ParmOffset += sz; 6969 } 6970 S += charUnitsToString(ParmOffset); 6971 S += "@0:"; 6972 S += charUnitsToString(PtrSize); 6973 6974 // Argument types. 6975 ParmOffset = 2 * PtrSize; 6976 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 6977 E = Decl->sel_param_end(); PI != E; ++PI) { 6978 const ParmVarDecl *PVDecl = *PI; 6979 QualType PType = PVDecl->getOriginalType(); 6980 if (const auto *AT = 6981 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 6982 // Use array's original type only if it has known number of 6983 // elements. 6984 if (!isa<ConstantArrayType>(AT)) 6985 PType = PVDecl->getType(); 6986 } else if (PType->isFunctionType()) 6987 PType = PVDecl->getType(); 6988 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(), 6989 PType, S, Extended); 6990 S += charUnitsToString(ParmOffset); 6991 ParmOffset += getObjCEncodingTypeSize(PType); 6992 } 6993 6994 return S; 6995 } 6996 6997 ObjCPropertyImplDecl * 6998 ASTContext::getObjCPropertyImplDeclForPropertyDecl( 6999 const ObjCPropertyDecl *PD, 7000 const Decl *Container) const { 7001 if (!Container) 7002 return nullptr; 7003 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) { 7004 for (auto *PID : CID->property_impls()) 7005 if (PID->getPropertyDecl() == PD) 7006 return PID; 7007 } else { 7008 const auto *OID = cast<ObjCImplementationDecl>(Container); 7009 for (auto *PID : OID->property_impls()) 7010 if (PID->getPropertyDecl() == PD) 7011 return PID; 7012 } 7013 return nullptr; 7014 } 7015 7016 /// getObjCEncodingForPropertyDecl - Return the encoded type for this 7017 /// property declaration. If non-NULL, Container must be either an 7018 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be 7019 /// NULL when getting encodings for protocol properties. 7020 /// Property attributes are stored as a comma-delimited C string. The simple 7021 /// attributes readonly and bycopy are encoded as single characters. The 7022 /// parametrized attributes, getter=name, setter=name, and ivar=name, are 7023 /// encoded as single characters, followed by an identifier. Property types 7024 /// are also encoded as a parametrized attribute. The characters used to encode 7025 /// these attributes are defined by the following enumeration: 7026 /// @code 7027 /// enum PropertyAttributes { 7028 /// kPropertyReadOnly = 'R', // property is read-only. 7029 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned 7030 /// kPropertyByref = '&', // property is a reference to the value last assigned 7031 /// kPropertyDynamic = 'D', // property is dynamic 7032 /// kPropertyGetter = 'G', // followed by getter selector name 7033 /// kPropertySetter = 'S', // followed by setter selector name 7034 /// kPropertyInstanceVariable = 'V' // followed by instance variable name 7035 /// kPropertyType = 'T' // followed by old-style type encoding. 7036 /// kPropertyWeak = 'W' // 'weak' property 7037 /// kPropertyStrong = 'P' // property GC'able 7038 /// kPropertyNonAtomic = 'N' // property non-atomic 7039 /// }; 7040 /// @endcode 7041 std::string 7042 ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, 7043 const Decl *Container) const { 7044 // Collect information from the property implementation decl(s). 7045 bool Dynamic = false; 7046 ObjCPropertyImplDecl *SynthesizePID = nullptr; 7047 7048 if (ObjCPropertyImplDecl *PropertyImpDecl = 7049 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) { 7050 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) 7051 Dynamic = true; 7052 else 7053 SynthesizePID = PropertyImpDecl; 7054 } 7055 7056 // FIXME: This is not very efficient. 7057 std::string S = "T"; 7058 7059 // Encode result type. 7060 // GCC has some special rules regarding encoding of properties which 7061 // closely resembles encoding of ivars. 7062 getObjCEncodingForPropertyType(PD->getType(), S); 7063 7064 if (PD->isReadOnly()) { 7065 S += ",R"; 7066 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy) 7067 S += ",C"; 7068 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain) 7069 S += ",&"; 7070 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak) 7071 S += ",W"; 7072 } else { 7073 switch (PD->getSetterKind()) { 7074 case ObjCPropertyDecl::Assign: break; 7075 case ObjCPropertyDecl::Copy: S += ",C"; break; 7076 case ObjCPropertyDecl::Retain: S += ",&"; break; 7077 case ObjCPropertyDecl::Weak: S += ",W"; break; 7078 } 7079 } 7080 7081 // It really isn't clear at all what this means, since properties 7082 // are "dynamic by default". 7083 if (Dynamic) 7084 S += ",D"; 7085 7086 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_nonatomic) 7087 S += ",N"; 7088 7089 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) { 7090 S += ",G"; 7091 S += PD->getGetterName().getAsString(); 7092 } 7093 7094 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) { 7095 S += ",S"; 7096 S += PD->getSetterName().getAsString(); 7097 } 7098 7099 if (SynthesizePID) { 7100 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl(); 7101 S += ",V"; 7102 S += OID->getNameAsString(); 7103 } 7104 7105 // FIXME: OBJCGC: weak & strong 7106 return S; 7107 } 7108 7109 /// getLegacyIntegralTypeEncoding - 7110 /// Another legacy compatibility encoding: 32-bit longs are encoded as 7111 /// 'l' or 'L' , but not always. For typedefs, we need to use 7112 /// 'i' or 'I' instead if encoding a struct field, or a pointer! 7113 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const { 7114 if (isa<TypedefType>(PointeeTy.getTypePtr())) { 7115 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) { 7116 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32) 7117 PointeeTy = UnsignedIntTy; 7118 else 7119 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32) 7120 PointeeTy = IntTy; 7121 } 7122 } 7123 } 7124 7125 void ASTContext::getObjCEncodingForType(QualType T, std::string& S, 7126 const FieldDecl *Field, 7127 QualType *NotEncodedT) const { 7128 // We follow the behavior of gcc, expanding structures which are 7129 // directly pointed to, and expanding embedded structures. Note that 7130 // these rules are sufficient to prevent recursive encoding of the 7131 // same type. 7132 getObjCEncodingForTypeImpl(T, S, 7133 ObjCEncOptions() 7134 .setExpandPointedToStructures() 7135 .setExpandStructures() 7136 .setIsOutermostType(), 7137 Field, NotEncodedT); 7138 } 7139 7140 void ASTContext::getObjCEncodingForPropertyType(QualType T, 7141 std::string& S) const { 7142 // Encode result type. 7143 // GCC has some special rules regarding encoding of properties which 7144 // closely resembles encoding of ivars. 7145 getObjCEncodingForTypeImpl(T, S, 7146 ObjCEncOptions() 7147 .setExpandPointedToStructures() 7148 .setExpandStructures() 7149 .setIsOutermostType() 7150 .setEncodingProperty(), 7151 /*Field=*/nullptr); 7152 } 7153 7154 static char getObjCEncodingForPrimitiveType(const ASTContext *C, 7155 const BuiltinType *BT) { 7156 BuiltinType::Kind kind = BT->getKind(); 7157 switch (kind) { 7158 case BuiltinType::Void: return 'v'; 7159 case BuiltinType::Bool: return 'B'; 7160 case BuiltinType::Char8: 7161 case BuiltinType::Char_U: 7162 case BuiltinType::UChar: return 'C'; 7163 case BuiltinType::Char16: 7164 case BuiltinType::UShort: return 'S'; 7165 case BuiltinType::Char32: 7166 case BuiltinType::UInt: return 'I'; 7167 case BuiltinType::ULong: 7168 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q'; 7169 case BuiltinType::UInt128: return 'T'; 7170 case BuiltinType::ULongLong: return 'Q'; 7171 case BuiltinType::Char_S: 7172 case BuiltinType::SChar: return 'c'; 7173 case BuiltinType::Short: return 's'; 7174 case BuiltinType::WChar_S: 7175 case BuiltinType::WChar_U: 7176 case BuiltinType::Int: return 'i'; 7177 case BuiltinType::Long: 7178 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q'; 7179 case BuiltinType::LongLong: return 'q'; 7180 case BuiltinType::Int128: return 't'; 7181 case BuiltinType::Float: return 'f'; 7182 case BuiltinType::Double: return 'd'; 7183 case BuiltinType::LongDouble: return 'D'; 7184 case BuiltinType::NullPtr: return '*'; // like char* 7185 7186 case BuiltinType::BFloat16: 7187 case BuiltinType::Float16: 7188 case BuiltinType::Float128: 7189 case BuiltinType::Half: 7190 case BuiltinType::ShortAccum: 7191 case BuiltinType::Accum: 7192 case BuiltinType::LongAccum: 7193 case BuiltinType::UShortAccum: 7194 case BuiltinType::UAccum: 7195 case BuiltinType::ULongAccum: 7196 case BuiltinType::ShortFract: 7197 case BuiltinType::Fract: 7198 case BuiltinType::LongFract: 7199 case BuiltinType::UShortFract: 7200 case BuiltinType::UFract: 7201 case BuiltinType::ULongFract: 7202 case BuiltinType::SatShortAccum: 7203 case BuiltinType::SatAccum: 7204 case BuiltinType::SatLongAccum: 7205 case BuiltinType::SatUShortAccum: 7206 case BuiltinType::SatUAccum: 7207 case BuiltinType::SatULongAccum: 7208 case BuiltinType::SatShortFract: 7209 case BuiltinType::SatFract: 7210 case BuiltinType::SatLongFract: 7211 case BuiltinType::SatUShortFract: 7212 case BuiltinType::SatUFract: 7213 case BuiltinType::SatULongFract: 7214 // FIXME: potentially need @encodes for these! 7215 return ' '; 7216 7217 #define SVE_TYPE(Name, Id, SingletonId) \ 7218 case BuiltinType::Id: 7219 #include "clang/Basic/AArch64SVEACLETypes.def" 7220 { 7221 DiagnosticsEngine &Diags = C->getDiagnostics(); 7222 unsigned DiagID = Diags.getCustomDiagID( 7223 DiagnosticsEngine::Error, "cannot yet @encode type %0"); 7224 Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy()); 7225 return ' '; 7226 } 7227 7228 case BuiltinType::ObjCId: 7229 case BuiltinType::ObjCClass: 7230 case BuiltinType::ObjCSel: 7231 llvm_unreachable("@encoding ObjC primitive type"); 7232 7233 // OpenCL and placeholder types don't need @encodings. 7234 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 7235 case BuiltinType::Id: 7236 #include "clang/Basic/OpenCLImageTypes.def" 7237 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 7238 case BuiltinType::Id: 7239 #include "clang/Basic/OpenCLExtensionTypes.def" 7240 case BuiltinType::OCLEvent: 7241 case BuiltinType::OCLClkEvent: 7242 case BuiltinType::OCLQueue: 7243 case BuiltinType::OCLReserveID: 7244 case BuiltinType::OCLSampler: 7245 case BuiltinType::Dependent: 7246 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 7247 case BuiltinType::Id: 7248 #include "clang/Basic/PPCTypes.def" 7249 #define BUILTIN_TYPE(KIND, ID) 7250 #define PLACEHOLDER_TYPE(KIND, ID) \ 7251 case BuiltinType::KIND: 7252 #include "clang/AST/BuiltinTypes.def" 7253 llvm_unreachable("invalid builtin type for @encode"); 7254 } 7255 llvm_unreachable("invalid BuiltinType::Kind value"); 7256 } 7257 7258 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) { 7259 EnumDecl *Enum = ET->getDecl(); 7260 7261 // The encoding of an non-fixed enum type is always 'i', regardless of size. 7262 if (!Enum->isFixed()) 7263 return 'i'; 7264 7265 // The encoding of a fixed enum type matches its fixed underlying type. 7266 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>(); 7267 return getObjCEncodingForPrimitiveType(C, BT); 7268 } 7269 7270 static void EncodeBitField(const ASTContext *Ctx, std::string& S, 7271 QualType T, const FieldDecl *FD) { 7272 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl"); 7273 S += 'b'; 7274 // The NeXT runtime encodes bit fields as b followed by the number of bits. 7275 // The GNU runtime requires more information; bitfields are encoded as b, 7276 // then the offset (in bits) of the first element, then the type of the 7277 // bitfield, then the size in bits. For example, in this structure: 7278 // 7279 // struct 7280 // { 7281 // int integer; 7282 // int flags:2; 7283 // }; 7284 // On a 32-bit system, the encoding for flags would be b2 for the NeXT 7285 // runtime, but b32i2 for the GNU runtime. The reason for this extra 7286 // information is not especially sensible, but we're stuck with it for 7287 // compatibility with GCC, although providing it breaks anything that 7288 // actually uses runtime introspection and wants to work on both runtimes... 7289 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) { 7290 uint64_t Offset; 7291 7292 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) { 7293 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr, 7294 IVD); 7295 } else { 7296 const RecordDecl *RD = FD->getParent(); 7297 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD); 7298 Offset = RL.getFieldOffset(FD->getFieldIndex()); 7299 } 7300 7301 S += llvm::utostr(Offset); 7302 7303 if (const auto *ET = T->getAs<EnumType>()) 7304 S += ObjCEncodingForEnumType(Ctx, ET); 7305 else { 7306 const auto *BT = T->castAs<BuiltinType>(); 7307 S += getObjCEncodingForPrimitiveType(Ctx, BT); 7308 } 7309 } 7310 S += llvm::utostr(FD->getBitWidthValue(*Ctx)); 7311 } 7312 7313 // FIXME: Use SmallString for accumulating string. 7314 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S, 7315 const ObjCEncOptions Options, 7316 const FieldDecl *FD, 7317 QualType *NotEncodedT) const { 7318 CanQualType CT = getCanonicalType(T); 7319 switch (CT->getTypeClass()) { 7320 case Type::Builtin: 7321 case Type::Enum: 7322 if (FD && FD->isBitField()) 7323 return EncodeBitField(this, S, T, FD); 7324 if (const auto *BT = dyn_cast<BuiltinType>(CT)) 7325 S += getObjCEncodingForPrimitiveType(this, BT); 7326 else 7327 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT)); 7328 return; 7329 7330 case Type::Complex: 7331 S += 'j'; 7332 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S, 7333 ObjCEncOptions(), 7334 /*Field=*/nullptr); 7335 return; 7336 7337 case Type::Atomic: 7338 S += 'A'; 7339 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S, 7340 ObjCEncOptions(), 7341 /*Field=*/nullptr); 7342 return; 7343 7344 // encoding for pointer or reference types. 7345 case Type::Pointer: 7346 case Type::LValueReference: 7347 case Type::RValueReference: { 7348 QualType PointeeTy; 7349 if (isa<PointerType>(CT)) { 7350 const auto *PT = T->castAs<PointerType>(); 7351 if (PT->isObjCSelType()) { 7352 S += ':'; 7353 return; 7354 } 7355 PointeeTy = PT->getPointeeType(); 7356 } else { 7357 PointeeTy = T->castAs<ReferenceType>()->getPointeeType(); 7358 } 7359 7360 bool isReadOnly = false; 7361 // For historical/compatibility reasons, the read-only qualifier of the 7362 // pointee gets emitted _before_ the '^'. The read-only qualifier of 7363 // the pointer itself gets ignored, _unless_ we are looking at a typedef! 7364 // Also, do not emit the 'r' for anything but the outermost type! 7365 if (isa<TypedefType>(T.getTypePtr())) { 7366 if (Options.IsOutermostType() && T.isConstQualified()) { 7367 isReadOnly = true; 7368 S += 'r'; 7369 } 7370 } else if (Options.IsOutermostType()) { 7371 QualType P = PointeeTy; 7372 while (auto PT = P->getAs<PointerType>()) 7373 P = PT->getPointeeType(); 7374 if (P.isConstQualified()) { 7375 isReadOnly = true; 7376 S += 'r'; 7377 } 7378 } 7379 if (isReadOnly) { 7380 // Another legacy compatibility encoding. Some ObjC qualifier and type 7381 // combinations need to be rearranged. 7382 // Rewrite "in const" from "nr" to "rn" 7383 if (StringRef(S).endswith("nr")) 7384 S.replace(S.end()-2, S.end(), "rn"); 7385 } 7386 7387 if (PointeeTy->isCharType()) { 7388 // char pointer types should be encoded as '*' unless it is a 7389 // type that has been typedef'd to 'BOOL'. 7390 if (!isTypeTypedefedAsBOOL(PointeeTy)) { 7391 S += '*'; 7392 return; 7393 } 7394 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) { 7395 // GCC binary compat: Need to convert "struct objc_class *" to "#". 7396 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) { 7397 S += '#'; 7398 return; 7399 } 7400 // GCC binary compat: Need to convert "struct objc_object *" to "@". 7401 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) { 7402 S += '@'; 7403 return; 7404 } 7405 // fall through... 7406 } 7407 S += '^'; 7408 getLegacyIntegralTypeEncoding(PointeeTy); 7409 7410 ObjCEncOptions NewOptions; 7411 if (Options.ExpandPointedToStructures()) 7412 NewOptions.setExpandStructures(); 7413 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions, 7414 /*Field=*/nullptr, NotEncodedT); 7415 return; 7416 } 7417 7418 case Type::ConstantArray: 7419 case Type::IncompleteArray: 7420 case Type::VariableArray: { 7421 const auto *AT = cast<ArrayType>(CT); 7422 7423 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) { 7424 // Incomplete arrays are encoded as a pointer to the array element. 7425 S += '^'; 7426 7427 getObjCEncodingForTypeImpl( 7428 AT->getElementType(), S, 7429 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD); 7430 } else { 7431 S += '['; 7432 7433 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) 7434 S += llvm::utostr(CAT->getSize().getZExtValue()); 7435 else { 7436 //Variable length arrays are encoded as a regular array with 0 elements. 7437 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) && 7438 "Unknown array type!"); 7439 S += '0'; 7440 } 7441 7442 getObjCEncodingForTypeImpl( 7443 AT->getElementType(), S, 7444 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD, 7445 NotEncodedT); 7446 S += ']'; 7447 } 7448 return; 7449 } 7450 7451 case Type::FunctionNoProto: 7452 case Type::FunctionProto: 7453 S += '?'; 7454 return; 7455 7456 case Type::Record: { 7457 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl(); 7458 S += RDecl->isUnion() ? '(' : '{'; 7459 // Anonymous structures print as '?' 7460 if (const IdentifierInfo *II = RDecl->getIdentifier()) { 7461 S += II->getName(); 7462 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) { 7463 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 7464 llvm::raw_string_ostream OS(S); 7465 printTemplateArgumentList(OS, TemplateArgs.asArray(), 7466 getPrintingPolicy()); 7467 } 7468 } else { 7469 S += '?'; 7470 } 7471 if (Options.ExpandStructures()) { 7472 S += '='; 7473 if (!RDecl->isUnion()) { 7474 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT); 7475 } else { 7476 for (const auto *Field : RDecl->fields()) { 7477 if (FD) { 7478 S += '"'; 7479 S += Field->getNameAsString(); 7480 S += '"'; 7481 } 7482 7483 // Special case bit-fields. 7484 if (Field->isBitField()) { 7485 getObjCEncodingForTypeImpl(Field->getType(), S, 7486 ObjCEncOptions().setExpandStructures(), 7487 Field); 7488 } else { 7489 QualType qt = Field->getType(); 7490 getLegacyIntegralTypeEncoding(qt); 7491 getObjCEncodingForTypeImpl( 7492 qt, S, 7493 ObjCEncOptions().setExpandStructures().setIsStructField(), FD, 7494 NotEncodedT); 7495 } 7496 } 7497 } 7498 } 7499 S += RDecl->isUnion() ? ')' : '}'; 7500 return; 7501 } 7502 7503 case Type::BlockPointer: { 7504 const auto *BT = T->castAs<BlockPointerType>(); 7505 S += "@?"; // Unlike a pointer-to-function, which is "^?". 7506 if (Options.EncodeBlockParameters()) { 7507 const auto *FT = BT->getPointeeType()->castAs<FunctionType>(); 7508 7509 S += '<'; 7510 // Block return type 7511 getObjCEncodingForTypeImpl(FT->getReturnType(), S, 7512 Options.forComponentType(), FD, NotEncodedT); 7513 // Block self 7514 S += "@?"; 7515 // Block parameters 7516 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) { 7517 for (const auto &I : FPT->param_types()) 7518 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD, 7519 NotEncodedT); 7520 } 7521 S += '>'; 7522 } 7523 return; 7524 } 7525 7526 case Type::ObjCObject: { 7527 // hack to match legacy encoding of *id and *Class 7528 QualType Ty = getObjCObjectPointerType(CT); 7529 if (Ty->isObjCIdType()) { 7530 S += "{objc_object=}"; 7531 return; 7532 } 7533 else if (Ty->isObjCClassType()) { 7534 S += "{objc_class=}"; 7535 return; 7536 } 7537 // TODO: Double check to make sure this intentionally falls through. 7538 LLVM_FALLTHROUGH; 7539 } 7540 7541 case Type::ObjCInterface: { 7542 // Ignore protocol qualifiers when mangling at this level. 7543 // @encode(class_name) 7544 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface(); 7545 S += '{'; 7546 S += OI->getObjCRuntimeNameAsString(); 7547 if (Options.ExpandStructures()) { 7548 S += '='; 7549 SmallVector<const ObjCIvarDecl*, 32> Ivars; 7550 DeepCollectObjCIvars(OI, true, Ivars); 7551 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) { 7552 const FieldDecl *Field = Ivars[i]; 7553 if (Field->isBitField()) 7554 getObjCEncodingForTypeImpl(Field->getType(), S, 7555 ObjCEncOptions().setExpandStructures(), 7556 Field); 7557 else 7558 getObjCEncodingForTypeImpl(Field->getType(), S, 7559 ObjCEncOptions().setExpandStructures(), FD, 7560 NotEncodedT); 7561 } 7562 } 7563 S += '}'; 7564 return; 7565 } 7566 7567 case Type::ObjCObjectPointer: { 7568 const auto *OPT = T->castAs<ObjCObjectPointerType>(); 7569 if (OPT->isObjCIdType()) { 7570 S += '@'; 7571 return; 7572 } 7573 7574 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) { 7575 // FIXME: Consider if we need to output qualifiers for 'Class<p>'. 7576 // Since this is a binary compatibility issue, need to consult with 7577 // runtime folks. Fortunately, this is a *very* obscure construct. 7578 S += '#'; 7579 return; 7580 } 7581 7582 if (OPT->isObjCQualifiedIdType()) { 7583 getObjCEncodingForTypeImpl( 7584 getObjCIdType(), S, 7585 Options.keepingOnly(ObjCEncOptions() 7586 .setExpandPointedToStructures() 7587 .setExpandStructures()), 7588 FD); 7589 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) { 7590 // Note that we do extended encoding of protocol qualifer list 7591 // Only when doing ivar or property encoding. 7592 S += '"'; 7593 for (const auto *I : OPT->quals()) { 7594 S += '<'; 7595 S += I->getObjCRuntimeNameAsString(); 7596 S += '>'; 7597 } 7598 S += '"'; 7599 } 7600 return; 7601 } 7602 7603 S += '@'; 7604 if (OPT->getInterfaceDecl() && 7605 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) { 7606 S += '"'; 7607 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString(); 7608 for (const auto *I : OPT->quals()) { 7609 S += '<'; 7610 S += I->getObjCRuntimeNameAsString(); 7611 S += '>'; 7612 } 7613 S += '"'; 7614 } 7615 return; 7616 } 7617 7618 // gcc just blithely ignores member pointers. 7619 // FIXME: we should do better than that. 'M' is available. 7620 case Type::MemberPointer: 7621 // This matches gcc's encoding, even though technically it is insufficient. 7622 //FIXME. We should do a better job than gcc. 7623 case Type::Vector: 7624 case Type::ExtVector: 7625 // Until we have a coherent encoding of these three types, issue warning. 7626 if (NotEncodedT) 7627 *NotEncodedT = T; 7628 return; 7629 7630 case Type::ConstantMatrix: 7631 if (NotEncodedT) 7632 *NotEncodedT = T; 7633 return; 7634 7635 // We could see an undeduced auto type here during error recovery. 7636 // Just ignore it. 7637 case Type::Auto: 7638 case Type::DeducedTemplateSpecialization: 7639 return; 7640 7641 case Type::Pipe: 7642 case Type::ExtInt: 7643 #define ABSTRACT_TYPE(KIND, BASE) 7644 #define TYPE(KIND, BASE) 7645 #define DEPENDENT_TYPE(KIND, BASE) \ 7646 case Type::KIND: 7647 #define NON_CANONICAL_TYPE(KIND, BASE) \ 7648 case Type::KIND: 7649 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \ 7650 case Type::KIND: 7651 #include "clang/AST/TypeNodes.inc" 7652 llvm_unreachable("@encode for dependent type!"); 7653 } 7654 llvm_unreachable("bad type kind!"); 7655 } 7656 7657 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl, 7658 std::string &S, 7659 const FieldDecl *FD, 7660 bool includeVBases, 7661 QualType *NotEncodedT) const { 7662 assert(RDecl && "Expected non-null RecordDecl"); 7663 assert(!RDecl->isUnion() && "Should not be called for unions"); 7664 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl()) 7665 return; 7666 7667 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl); 7668 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets; 7669 const ASTRecordLayout &layout = getASTRecordLayout(RDecl); 7670 7671 if (CXXRec) { 7672 for (const auto &BI : CXXRec->bases()) { 7673 if (!BI.isVirtual()) { 7674 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); 7675 if (base->isEmpty()) 7676 continue; 7677 uint64_t offs = toBits(layout.getBaseClassOffset(base)); 7678 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 7679 std::make_pair(offs, base)); 7680 } 7681 } 7682 } 7683 7684 unsigned i = 0; 7685 for (FieldDecl *Field : RDecl->fields()) { 7686 if (!Field->isZeroLengthBitField(*this) && Field->isZeroSize(*this)) 7687 continue; 7688 uint64_t offs = layout.getFieldOffset(i); 7689 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 7690 std::make_pair(offs, Field)); 7691 ++i; 7692 } 7693 7694 if (CXXRec && includeVBases) { 7695 for (const auto &BI : CXXRec->vbases()) { 7696 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); 7697 if (base->isEmpty()) 7698 continue; 7699 uint64_t offs = toBits(layout.getVBaseClassOffset(base)); 7700 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) && 7701 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end()) 7702 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(), 7703 std::make_pair(offs, base)); 7704 } 7705 } 7706 7707 CharUnits size; 7708 if (CXXRec) { 7709 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize(); 7710 } else { 7711 size = layout.getSize(); 7712 } 7713 7714 #ifndef NDEBUG 7715 uint64_t CurOffs = 0; 7716 #endif 7717 std::multimap<uint64_t, NamedDecl *>::iterator 7718 CurLayObj = FieldOrBaseOffsets.begin(); 7719 7720 if (CXXRec && CXXRec->isDynamicClass() && 7721 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) { 7722 if (FD) { 7723 S += "\"_vptr$"; 7724 std::string recname = CXXRec->getNameAsString(); 7725 if (recname.empty()) recname = "?"; 7726 S += recname; 7727 S += '"'; 7728 } 7729 S += "^^?"; 7730 #ifndef NDEBUG 7731 CurOffs += getTypeSize(VoidPtrTy); 7732 #endif 7733 } 7734 7735 if (!RDecl->hasFlexibleArrayMember()) { 7736 // Mark the end of the structure. 7737 uint64_t offs = toBits(size); 7738 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 7739 std::make_pair(offs, nullptr)); 7740 } 7741 7742 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) { 7743 #ifndef NDEBUG 7744 assert(CurOffs <= CurLayObj->first); 7745 if (CurOffs < CurLayObj->first) { 7746 uint64_t padding = CurLayObj->first - CurOffs; 7747 // FIXME: There doesn't seem to be a way to indicate in the encoding that 7748 // packing/alignment of members is different that normal, in which case 7749 // the encoding will be out-of-sync with the real layout. 7750 // If the runtime switches to just consider the size of types without 7751 // taking into account alignment, we could make padding explicit in the 7752 // encoding (e.g. using arrays of chars). The encoding strings would be 7753 // longer then though. 7754 CurOffs += padding; 7755 } 7756 #endif 7757 7758 NamedDecl *dcl = CurLayObj->second; 7759 if (!dcl) 7760 break; // reached end of structure. 7761 7762 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) { 7763 // We expand the bases without their virtual bases since those are going 7764 // in the initial structure. Note that this differs from gcc which 7765 // expands virtual bases each time one is encountered in the hierarchy, 7766 // making the encoding type bigger than it really is. 7767 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false, 7768 NotEncodedT); 7769 assert(!base->isEmpty()); 7770 #ifndef NDEBUG 7771 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize()); 7772 #endif 7773 } else { 7774 const auto *field = cast<FieldDecl>(dcl); 7775 if (FD) { 7776 S += '"'; 7777 S += field->getNameAsString(); 7778 S += '"'; 7779 } 7780 7781 if (field->isBitField()) { 7782 EncodeBitField(this, S, field->getType(), field); 7783 #ifndef NDEBUG 7784 CurOffs += field->getBitWidthValue(*this); 7785 #endif 7786 } else { 7787 QualType qt = field->getType(); 7788 getLegacyIntegralTypeEncoding(qt); 7789 getObjCEncodingForTypeImpl( 7790 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(), 7791 FD, NotEncodedT); 7792 #ifndef NDEBUG 7793 CurOffs += getTypeSize(field->getType()); 7794 #endif 7795 } 7796 } 7797 } 7798 } 7799 7800 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, 7801 std::string& S) const { 7802 if (QT & Decl::OBJC_TQ_In) 7803 S += 'n'; 7804 if (QT & Decl::OBJC_TQ_Inout) 7805 S += 'N'; 7806 if (QT & Decl::OBJC_TQ_Out) 7807 S += 'o'; 7808 if (QT & Decl::OBJC_TQ_Bycopy) 7809 S += 'O'; 7810 if (QT & Decl::OBJC_TQ_Byref) 7811 S += 'R'; 7812 if (QT & Decl::OBJC_TQ_Oneway) 7813 S += 'V'; 7814 } 7815 7816 TypedefDecl *ASTContext::getObjCIdDecl() const { 7817 if (!ObjCIdDecl) { 7818 QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {}); 7819 T = getObjCObjectPointerType(T); 7820 ObjCIdDecl = buildImplicitTypedef(T, "id"); 7821 } 7822 return ObjCIdDecl; 7823 } 7824 7825 TypedefDecl *ASTContext::getObjCSelDecl() const { 7826 if (!ObjCSelDecl) { 7827 QualType T = getPointerType(ObjCBuiltinSelTy); 7828 ObjCSelDecl = buildImplicitTypedef(T, "SEL"); 7829 } 7830 return ObjCSelDecl; 7831 } 7832 7833 TypedefDecl *ASTContext::getObjCClassDecl() const { 7834 if (!ObjCClassDecl) { 7835 QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {}); 7836 T = getObjCObjectPointerType(T); 7837 ObjCClassDecl = buildImplicitTypedef(T, "Class"); 7838 } 7839 return ObjCClassDecl; 7840 } 7841 7842 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const { 7843 if (!ObjCProtocolClassDecl) { 7844 ObjCProtocolClassDecl 7845 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(), 7846 SourceLocation(), 7847 &Idents.get("Protocol"), 7848 /*typeParamList=*/nullptr, 7849 /*PrevDecl=*/nullptr, 7850 SourceLocation(), true); 7851 } 7852 7853 return ObjCProtocolClassDecl; 7854 } 7855 7856 //===----------------------------------------------------------------------===// 7857 // __builtin_va_list Construction Functions 7858 //===----------------------------------------------------------------------===// 7859 7860 static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context, 7861 StringRef Name) { 7862 // typedef char* __builtin[_ms]_va_list; 7863 QualType T = Context->getPointerType(Context->CharTy); 7864 return Context->buildImplicitTypedef(T, Name); 7865 } 7866 7867 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) { 7868 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list"); 7869 } 7870 7871 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) { 7872 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list"); 7873 } 7874 7875 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) { 7876 // typedef void* __builtin_va_list; 7877 QualType T = Context->getPointerType(Context->VoidTy); 7878 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 7879 } 7880 7881 static TypedefDecl * 7882 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) { 7883 // struct __va_list 7884 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list"); 7885 if (Context->getLangOpts().CPlusPlus) { 7886 // namespace std { struct __va_list { 7887 NamespaceDecl *NS; 7888 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context), 7889 Context->getTranslationUnitDecl(), 7890 /*Inline*/ false, SourceLocation(), 7891 SourceLocation(), &Context->Idents.get("std"), 7892 /*PrevDecl*/ nullptr); 7893 NS->setImplicit(); 7894 VaListTagDecl->setDeclContext(NS); 7895 } 7896 7897 VaListTagDecl->startDefinition(); 7898 7899 const size_t NumFields = 5; 7900 QualType FieldTypes[NumFields]; 7901 const char *FieldNames[NumFields]; 7902 7903 // void *__stack; 7904 FieldTypes[0] = Context->getPointerType(Context->VoidTy); 7905 FieldNames[0] = "__stack"; 7906 7907 // void *__gr_top; 7908 FieldTypes[1] = Context->getPointerType(Context->VoidTy); 7909 FieldNames[1] = "__gr_top"; 7910 7911 // void *__vr_top; 7912 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 7913 FieldNames[2] = "__vr_top"; 7914 7915 // int __gr_offs; 7916 FieldTypes[3] = Context->IntTy; 7917 FieldNames[3] = "__gr_offs"; 7918 7919 // int __vr_offs; 7920 FieldTypes[4] = Context->IntTy; 7921 FieldNames[4] = "__vr_offs"; 7922 7923 // Create fields 7924 for (unsigned i = 0; i < NumFields; ++i) { 7925 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 7926 VaListTagDecl, 7927 SourceLocation(), 7928 SourceLocation(), 7929 &Context->Idents.get(FieldNames[i]), 7930 FieldTypes[i], /*TInfo=*/nullptr, 7931 /*BitWidth=*/nullptr, 7932 /*Mutable=*/false, 7933 ICIS_NoInit); 7934 Field->setAccess(AS_public); 7935 VaListTagDecl->addDecl(Field); 7936 } 7937 VaListTagDecl->completeDefinition(); 7938 Context->VaListTagDecl = VaListTagDecl; 7939 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 7940 7941 // } __builtin_va_list; 7942 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list"); 7943 } 7944 7945 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) { 7946 // typedef struct __va_list_tag { 7947 RecordDecl *VaListTagDecl; 7948 7949 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 7950 VaListTagDecl->startDefinition(); 7951 7952 const size_t NumFields = 5; 7953 QualType FieldTypes[NumFields]; 7954 const char *FieldNames[NumFields]; 7955 7956 // unsigned char gpr; 7957 FieldTypes[0] = Context->UnsignedCharTy; 7958 FieldNames[0] = "gpr"; 7959 7960 // unsigned char fpr; 7961 FieldTypes[1] = Context->UnsignedCharTy; 7962 FieldNames[1] = "fpr"; 7963 7964 // unsigned short reserved; 7965 FieldTypes[2] = Context->UnsignedShortTy; 7966 FieldNames[2] = "reserved"; 7967 7968 // void* overflow_arg_area; 7969 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 7970 FieldNames[3] = "overflow_arg_area"; 7971 7972 // void* reg_save_area; 7973 FieldTypes[4] = Context->getPointerType(Context->VoidTy); 7974 FieldNames[4] = "reg_save_area"; 7975 7976 // Create fields 7977 for (unsigned i = 0; i < NumFields; ++i) { 7978 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl, 7979 SourceLocation(), 7980 SourceLocation(), 7981 &Context->Idents.get(FieldNames[i]), 7982 FieldTypes[i], /*TInfo=*/nullptr, 7983 /*BitWidth=*/nullptr, 7984 /*Mutable=*/false, 7985 ICIS_NoInit); 7986 Field->setAccess(AS_public); 7987 VaListTagDecl->addDecl(Field); 7988 } 7989 VaListTagDecl->completeDefinition(); 7990 Context->VaListTagDecl = VaListTagDecl; 7991 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 7992 7993 // } __va_list_tag; 7994 TypedefDecl *VaListTagTypedefDecl = 7995 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); 7996 7997 QualType VaListTagTypedefType = 7998 Context->getTypedefType(VaListTagTypedefDecl); 7999 8000 // typedef __va_list_tag __builtin_va_list[1]; 8001 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8002 QualType VaListTagArrayType 8003 = Context->getConstantArrayType(VaListTagTypedefType, 8004 Size, nullptr, ArrayType::Normal, 0); 8005 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8006 } 8007 8008 static TypedefDecl * 8009 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) { 8010 // struct __va_list_tag { 8011 RecordDecl *VaListTagDecl; 8012 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8013 VaListTagDecl->startDefinition(); 8014 8015 const size_t NumFields = 4; 8016 QualType FieldTypes[NumFields]; 8017 const char *FieldNames[NumFields]; 8018 8019 // unsigned gp_offset; 8020 FieldTypes[0] = Context->UnsignedIntTy; 8021 FieldNames[0] = "gp_offset"; 8022 8023 // unsigned fp_offset; 8024 FieldTypes[1] = Context->UnsignedIntTy; 8025 FieldNames[1] = "fp_offset"; 8026 8027 // void* overflow_arg_area; 8028 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8029 FieldNames[2] = "overflow_arg_area"; 8030 8031 // void* reg_save_area; 8032 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 8033 FieldNames[3] = "reg_save_area"; 8034 8035 // Create fields 8036 for (unsigned i = 0; i < NumFields; ++i) { 8037 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8038 VaListTagDecl, 8039 SourceLocation(), 8040 SourceLocation(), 8041 &Context->Idents.get(FieldNames[i]), 8042 FieldTypes[i], /*TInfo=*/nullptr, 8043 /*BitWidth=*/nullptr, 8044 /*Mutable=*/false, 8045 ICIS_NoInit); 8046 Field->setAccess(AS_public); 8047 VaListTagDecl->addDecl(Field); 8048 } 8049 VaListTagDecl->completeDefinition(); 8050 Context->VaListTagDecl = VaListTagDecl; 8051 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8052 8053 // }; 8054 8055 // typedef struct __va_list_tag __builtin_va_list[1]; 8056 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8057 QualType VaListTagArrayType = Context->getConstantArrayType( 8058 VaListTagType, Size, nullptr, ArrayType::Normal, 0); 8059 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8060 } 8061 8062 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) { 8063 // typedef int __builtin_va_list[4]; 8064 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4); 8065 QualType IntArrayType = Context->getConstantArrayType( 8066 Context->IntTy, Size, nullptr, ArrayType::Normal, 0); 8067 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list"); 8068 } 8069 8070 static TypedefDecl * 8071 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) { 8072 // struct __va_list 8073 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list"); 8074 if (Context->getLangOpts().CPlusPlus) { 8075 // namespace std { struct __va_list { 8076 NamespaceDecl *NS; 8077 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context), 8078 Context->getTranslationUnitDecl(), 8079 /*Inline*/false, SourceLocation(), 8080 SourceLocation(), &Context->Idents.get("std"), 8081 /*PrevDecl*/ nullptr); 8082 NS->setImplicit(); 8083 VaListDecl->setDeclContext(NS); 8084 } 8085 8086 VaListDecl->startDefinition(); 8087 8088 // void * __ap; 8089 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8090 VaListDecl, 8091 SourceLocation(), 8092 SourceLocation(), 8093 &Context->Idents.get("__ap"), 8094 Context->getPointerType(Context->VoidTy), 8095 /*TInfo=*/nullptr, 8096 /*BitWidth=*/nullptr, 8097 /*Mutable=*/false, 8098 ICIS_NoInit); 8099 Field->setAccess(AS_public); 8100 VaListDecl->addDecl(Field); 8101 8102 // }; 8103 VaListDecl->completeDefinition(); 8104 Context->VaListTagDecl = VaListDecl; 8105 8106 // typedef struct __va_list __builtin_va_list; 8107 QualType T = Context->getRecordType(VaListDecl); 8108 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 8109 } 8110 8111 static TypedefDecl * 8112 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) { 8113 // struct __va_list_tag { 8114 RecordDecl *VaListTagDecl; 8115 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8116 VaListTagDecl->startDefinition(); 8117 8118 const size_t NumFields = 4; 8119 QualType FieldTypes[NumFields]; 8120 const char *FieldNames[NumFields]; 8121 8122 // long __gpr; 8123 FieldTypes[0] = Context->LongTy; 8124 FieldNames[0] = "__gpr"; 8125 8126 // long __fpr; 8127 FieldTypes[1] = Context->LongTy; 8128 FieldNames[1] = "__fpr"; 8129 8130 // void *__overflow_arg_area; 8131 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8132 FieldNames[2] = "__overflow_arg_area"; 8133 8134 // void *__reg_save_area; 8135 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 8136 FieldNames[3] = "__reg_save_area"; 8137 8138 // Create fields 8139 for (unsigned i = 0; i < NumFields; ++i) { 8140 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8141 VaListTagDecl, 8142 SourceLocation(), 8143 SourceLocation(), 8144 &Context->Idents.get(FieldNames[i]), 8145 FieldTypes[i], /*TInfo=*/nullptr, 8146 /*BitWidth=*/nullptr, 8147 /*Mutable=*/false, 8148 ICIS_NoInit); 8149 Field->setAccess(AS_public); 8150 VaListTagDecl->addDecl(Field); 8151 } 8152 VaListTagDecl->completeDefinition(); 8153 Context->VaListTagDecl = VaListTagDecl; 8154 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8155 8156 // }; 8157 8158 // typedef __va_list_tag __builtin_va_list[1]; 8159 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8160 QualType VaListTagArrayType = Context->getConstantArrayType( 8161 VaListTagType, Size, nullptr, ArrayType::Normal, 0); 8162 8163 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8164 } 8165 8166 static TypedefDecl *CreateHexagonBuiltinVaListDecl(const ASTContext *Context) { 8167 // typedef struct __va_list_tag { 8168 RecordDecl *VaListTagDecl; 8169 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8170 VaListTagDecl->startDefinition(); 8171 8172 const size_t NumFields = 3; 8173 QualType FieldTypes[NumFields]; 8174 const char *FieldNames[NumFields]; 8175 8176 // void *CurrentSavedRegisterArea; 8177 FieldTypes[0] = Context->getPointerType(Context->VoidTy); 8178 FieldNames[0] = "__current_saved_reg_area_pointer"; 8179 8180 // void *SavedRegAreaEnd; 8181 FieldTypes[1] = Context->getPointerType(Context->VoidTy); 8182 FieldNames[1] = "__saved_reg_area_end_pointer"; 8183 8184 // void *OverflowArea; 8185 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8186 FieldNames[2] = "__overflow_area_pointer"; 8187 8188 // Create fields 8189 for (unsigned i = 0; i < NumFields; ++i) { 8190 FieldDecl *Field = FieldDecl::Create( 8191 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(), 8192 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i], 8193 /*TInfo=*/0, 8194 /*BitWidth=*/0, 8195 /*Mutable=*/false, ICIS_NoInit); 8196 Field->setAccess(AS_public); 8197 VaListTagDecl->addDecl(Field); 8198 } 8199 VaListTagDecl->completeDefinition(); 8200 Context->VaListTagDecl = VaListTagDecl; 8201 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8202 8203 // } __va_list_tag; 8204 TypedefDecl *VaListTagTypedefDecl = 8205 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); 8206 8207 QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl); 8208 8209 // typedef __va_list_tag __builtin_va_list[1]; 8210 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8211 QualType VaListTagArrayType = Context->getConstantArrayType( 8212 VaListTagTypedefType, Size, nullptr, ArrayType::Normal, 0); 8213 8214 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8215 } 8216 8217 static TypedefDecl *CreateVaListDecl(const ASTContext *Context, 8218 TargetInfo::BuiltinVaListKind Kind) { 8219 switch (Kind) { 8220 case TargetInfo::CharPtrBuiltinVaList: 8221 return CreateCharPtrBuiltinVaListDecl(Context); 8222 case TargetInfo::VoidPtrBuiltinVaList: 8223 return CreateVoidPtrBuiltinVaListDecl(Context); 8224 case TargetInfo::AArch64ABIBuiltinVaList: 8225 return CreateAArch64ABIBuiltinVaListDecl(Context); 8226 case TargetInfo::PowerABIBuiltinVaList: 8227 return CreatePowerABIBuiltinVaListDecl(Context); 8228 case TargetInfo::X86_64ABIBuiltinVaList: 8229 return CreateX86_64ABIBuiltinVaListDecl(Context); 8230 case TargetInfo::PNaClABIBuiltinVaList: 8231 return CreatePNaClABIBuiltinVaListDecl(Context); 8232 case TargetInfo::AAPCSABIBuiltinVaList: 8233 return CreateAAPCSABIBuiltinVaListDecl(Context); 8234 case TargetInfo::SystemZBuiltinVaList: 8235 return CreateSystemZBuiltinVaListDecl(Context); 8236 case TargetInfo::HexagonBuiltinVaList: 8237 return CreateHexagonBuiltinVaListDecl(Context); 8238 } 8239 8240 llvm_unreachable("Unhandled __builtin_va_list type kind"); 8241 } 8242 8243 TypedefDecl *ASTContext::getBuiltinVaListDecl() const { 8244 if (!BuiltinVaListDecl) { 8245 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind()); 8246 assert(BuiltinVaListDecl->isImplicit()); 8247 } 8248 8249 return BuiltinVaListDecl; 8250 } 8251 8252 Decl *ASTContext::getVaListTagDecl() const { 8253 // Force the creation of VaListTagDecl by building the __builtin_va_list 8254 // declaration. 8255 if (!VaListTagDecl) 8256 (void)getBuiltinVaListDecl(); 8257 8258 return VaListTagDecl; 8259 } 8260 8261 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const { 8262 if (!BuiltinMSVaListDecl) 8263 BuiltinMSVaListDecl = CreateMSVaListDecl(this); 8264 8265 return BuiltinMSVaListDecl; 8266 } 8267 8268 bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const { 8269 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID()); 8270 } 8271 8272 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) { 8273 assert(ObjCConstantStringType.isNull() && 8274 "'NSConstantString' type already set!"); 8275 8276 ObjCConstantStringType = getObjCInterfaceType(Decl); 8277 } 8278 8279 /// Retrieve the template name that corresponds to a non-empty 8280 /// lookup. 8281 TemplateName 8282 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin, 8283 UnresolvedSetIterator End) const { 8284 unsigned size = End - Begin; 8285 assert(size > 1 && "set is not overloaded!"); 8286 8287 void *memory = Allocate(sizeof(OverloadedTemplateStorage) + 8288 size * sizeof(FunctionTemplateDecl*)); 8289 auto *OT = new (memory) OverloadedTemplateStorage(size); 8290 8291 NamedDecl **Storage = OT->getStorage(); 8292 for (UnresolvedSetIterator I = Begin; I != End; ++I) { 8293 NamedDecl *D = *I; 8294 assert(isa<FunctionTemplateDecl>(D) || 8295 isa<UnresolvedUsingValueDecl>(D) || 8296 (isa<UsingShadowDecl>(D) && 8297 isa<FunctionTemplateDecl>(D->getUnderlyingDecl()))); 8298 *Storage++ = D; 8299 } 8300 8301 return TemplateName(OT); 8302 } 8303 8304 /// Retrieve a template name representing an unqualified-id that has been 8305 /// assumed to name a template for ADL purposes. 8306 TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const { 8307 auto *OT = new (*this) AssumedTemplateStorage(Name); 8308 return TemplateName(OT); 8309 } 8310 8311 /// Retrieve the template name that represents a qualified 8312 /// template name such as \c std::vector. 8313 TemplateName 8314 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, 8315 bool TemplateKeyword, 8316 TemplateDecl *Template) const { 8317 assert(NNS && "Missing nested-name-specifier in qualified template name"); 8318 8319 // FIXME: Canonicalization? 8320 llvm::FoldingSetNodeID ID; 8321 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template); 8322 8323 void *InsertPos = nullptr; 8324 QualifiedTemplateName *QTN = 8325 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 8326 if (!QTN) { 8327 QTN = new (*this, alignof(QualifiedTemplateName)) 8328 QualifiedTemplateName(NNS, TemplateKeyword, Template); 8329 QualifiedTemplateNames.InsertNode(QTN, InsertPos); 8330 } 8331 8332 return TemplateName(QTN); 8333 } 8334 8335 /// Retrieve the template name that represents a dependent 8336 /// template name such as \c MetaFun::template apply. 8337 TemplateName 8338 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 8339 const IdentifierInfo *Name) const { 8340 assert((!NNS || NNS->isDependent()) && 8341 "Nested name specifier must be dependent"); 8342 8343 llvm::FoldingSetNodeID ID; 8344 DependentTemplateName::Profile(ID, NNS, Name); 8345 8346 void *InsertPos = nullptr; 8347 DependentTemplateName *QTN = 8348 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 8349 8350 if (QTN) 8351 return TemplateName(QTN); 8352 8353 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 8354 if (CanonNNS == NNS) { 8355 QTN = new (*this, alignof(DependentTemplateName)) 8356 DependentTemplateName(NNS, Name); 8357 } else { 8358 TemplateName Canon = getDependentTemplateName(CanonNNS, Name); 8359 QTN = new (*this, alignof(DependentTemplateName)) 8360 DependentTemplateName(NNS, Name, Canon); 8361 DependentTemplateName *CheckQTN = 8362 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 8363 assert(!CheckQTN && "Dependent type name canonicalization broken"); 8364 (void)CheckQTN; 8365 } 8366 8367 DependentTemplateNames.InsertNode(QTN, InsertPos); 8368 return TemplateName(QTN); 8369 } 8370 8371 /// Retrieve the template name that represents a dependent 8372 /// template name such as \c MetaFun::template operator+. 8373 TemplateName 8374 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 8375 OverloadedOperatorKind Operator) const { 8376 assert((!NNS || NNS->isDependent()) && 8377 "Nested name specifier must be dependent"); 8378 8379 llvm::FoldingSetNodeID ID; 8380 DependentTemplateName::Profile(ID, NNS, Operator); 8381 8382 void *InsertPos = nullptr; 8383 DependentTemplateName *QTN 8384 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 8385 8386 if (QTN) 8387 return TemplateName(QTN); 8388 8389 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 8390 if (CanonNNS == NNS) { 8391 QTN = new (*this, alignof(DependentTemplateName)) 8392 DependentTemplateName(NNS, Operator); 8393 } else { 8394 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator); 8395 QTN = new (*this, alignof(DependentTemplateName)) 8396 DependentTemplateName(NNS, Operator, Canon); 8397 8398 DependentTemplateName *CheckQTN 8399 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 8400 assert(!CheckQTN && "Dependent template name canonicalization broken"); 8401 (void)CheckQTN; 8402 } 8403 8404 DependentTemplateNames.InsertNode(QTN, InsertPos); 8405 return TemplateName(QTN); 8406 } 8407 8408 TemplateName 8409 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param, 8410 TemplateName replacement) const { 8411 llvm::FoldingSetNodeID ID; 8412 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement); 8413 8414 void *insertPos = nullptr; 8415 SubstTemplateTemplateParmStorage *subst 8416 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos); 8417 8418 if (!subst) { 8419 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement); 8420 SubstTemplateTemplateParms.InsertNode(subst, insertPos); 8421 } 8422 8423 return TemplateName(subst); 8424 } 8425 8426 TemplateName 8427 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param, 8428 const TemplateArgument &ArgPack) const { 8429 auto &Self = const_cast<ASTContext &>(*this); 8430 llvm::FoldingSetNodeID ID; 8431 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack); 8432 8433 void *InsertPos = nullptr; 8434 SubstTemplateTemplateParmPackStorage *Subst 8435 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos); 8436 8437 if (!Subst) { 8438 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param, 8439 ArgPack.pack_size(), 8440 ArgPack.pack_begin()); 8441 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos); 8442 } 8443 8444 return TemplateName(Subst); 8445 } 8446 8447 /// getFromTargetType - Given one of the integer types provided by 8448 /// TargetInfo, produce the corresponding type. The unsigned @p Type 8449 /// is actually a value of type @c TargetInfo::IntType. 8450 CanQualType ASTContext::getFromTargetType(unsigned Type) const { 8451 switch (Type) { 8452 case TargetInfo::NoInt: return {}; 8453 case TargetInfo::SignedChar: return SignedCharTy; 8454 case TargetInfo::UnsignedChar: return UnsignedCharTy; 8455 case TargetInfo::SignedShort: return ShortTy; 8456 case TargetInfo::UnsignedShort: return UnsignedShortTy; 8457 case TargetInfo::SignedInt: return IntTy; 8458 case TargetInfo::UnsignedInt: return UnsignedIntTy; 8459 case TargetInfo::SignedLong: return LongTy; 8460 case TargetInfo::UnsignedLong: return UnsignedLongTy; 8461 case TargetInfo::SignedLongLong: return LongLongTy; 8462 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy; 8463 } 8464 8465 llvm_unreachable("Unhandled TargetInfo::IntType value"); 8466 } 8467 8468 //===----------------------------------------------------------------------===// 8469 // Type Predicates. 8470 //===----------------------------------------------------------------------===// 8471 8472 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's 8473 /// garbage collection attribute. 8474 /// 8475 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const { 8476 if (getLangOpts().getGC() == LangOptions::NonGC) 8477 return Qualifiers::GCNone; 8478 8479 assert(getLangOpts().ObjC); 8480 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr(); 8481 8482 // Default behaviour under objective-C's gc is for ObjC pointers 8483 // (or pointers to them) be treated as though they were declared 8484 // as __strong. 8485 if (GCAttrs == Qualifiers::GCNone) { 8486 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) 8487 return Qualifiers::Strong; 8488 else if (Ty->isPointerType()) 8489 return getObjCGCAttrKind(Ty->castAs<PointerType>()->getPointeeType()); 8490 } else { 8491 // It's not valid to set GC attributes on anything that isn't a 8492 // pointer. 8493 #ifndef NDEBUG 8494 QualType CT = Ty->getCanonicalTypeInternal(); 8495 while (const auto *AT = dyn_cast<ArrayType>(CT)) 8496 CT = AT->getElementType(); 8497 assert(CT->isAnyPointerType() || CT->isBlockPointerType()); 8498 #endif 8499 } 8500 return GCAttrs; 8501 } 8502 8503 //===----------------------------------------------------------------------===// 8504 // Type Compatibility Testing 8505 //===----------------------------------------------------------------------===// 8506 8507 /// areCompatVectorTypes - Return true if the two specified vector types are 8508 /// compatible. 8509 static bool areCompatVectorTypes(const VectorType *LHS, 8510 const VectorType *RHS) { 8511 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 8512 return LHS->getElementType() == RHS->getElementType() && 8513 LHS->getNumElements() == RHS->getNumElements(); 8514 } 8515 8516 /// areCompatMatrixTypes - Return true if the two specified matrix types are 8517 /// compatible. 8518 static bool areCompatMatrixTypes(const ConstantMatrixType *LHS, 8519 const ConstantMatrixType *RHS) { 8520 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 8521 return LHS->getElementType() == RHS->getElementType() && 8522 LHS->getNumRows() == RHS->getNumRows() && 8523 LHS->getNumColumns() == RHS->getNumColumns(); 8524 } 8525 8526 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec, 8527 QualType SecondVec) { 8528 assert(FirstVec->isVectorType() && "FirstVec should be a vector type"); 8529 assert(SecondVec->isVectorType() && "SecondVec should be a vector type"); 8530 8531 if (hasSameUnqualifiedType(FirstVec, SecondVec)) 8532 return true; 8533 8534 // Treat Neon vector types and most AltiVec vector types as if they are the 8535 // equivalent GCC vector types. 8536 const auto *First = FirstVec->castAs<VectorType>(); 8537 const auto *Second = SecondVec->castAs<VectorType>(); 8538 if (First->getNumElements() == Second->getNumElements() && 8539 hasSameType(First->getElementType(), Second->getElementType()) && 8540 First->getVectorKind() != VectorType::AltiVecPixel && 8541 First->getVectorKind() != VectorType::AltiVecBool && 8542 Second->getVectorKind() != VectorType::AltiVecPixel && 8543 Second->getVectorKind() != VectorType::AltiVecBool && 8544 First->getVectorKind() != VectorType::SveFixedLengthDataVector && 8545 First->getVectorKind() != VectorType::SveFixedLengthPredicateVector && 8546 Second->getVectorKind() != VectorType::SveFixedLengthDataVector && 8547 Second->getVectorKind() != VectorType::SveFixedLengthPredicateVector) 8548 return true; 8549 8550 return false; 8551 } 8552 8553 bool ASTContext::areCompatibleSveTypes(QualType FirstType, 8554 QualType SecondType) { 8555 assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) || 8556 (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) && 8557 "Expected SVE builtin type and vector type!"); 8558 8559 auto IsValidCast = [this](QualType FirstType, QualType SecondType) { 8560 if (const auto *BT = FirstType->getAs<BuiltinType>()) { 8561 if (const auto *VT = SecondType->getAs<VectorType>()) { 8562 // Predicates have the same representation as uint8 so we also have to 8563 // check the kind to make these types incompatible. 8564 if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 8565 return BT->getKind() == BuiltinType::SveBool; 8566 else if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) 8567 return VT->getElementType().getCanonicalType() == 8568 FirstType->getSveEltType(*this); 8569 else if (VT->getVectorKind() == VectorType::GenericVector) 8570 return getTypeSize(SecondType) == getLangOpts().ArmSveVectorBits && 8571 hasSameType(VT->getElementType(), 8572 getBuiltinVectorTypeInfo(BT).ElementType); 8573 } 8574 } 8575 return false; 8576 }; 8577 8578 return IsValidCast(FirstType, SecondType) || 8579 IsValidCast(SecondType, FirstType); 8580 } 8581 8582 bool ASTContext::areLaxCompatibleSveTypes(QualType FirstType, 8583 QualType SecondType) { 8584 assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) || 8585 (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) && 8586 "Expected SVE builtin type and vector type!"); 8587 8588 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) { 8589 if (!FirstType->getAs<BuiltinType>()) 8590 return false; 8591 8592 const auto *VecTy = SecondType->getAs<VectorType>(); 8593 if (VecTy && 8594 (VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector || 8595 VecTy->getVectorKind() == VectorType::GenericVector)) { 8596 const LangOptions::LaxVectorConversionKind LVCKind = 8597 getLangOpts().getLaxVectorConversions(); 8598 8599 // If __ARM_FEATURE_SVE_BITS != N do not allow GNU vector lax conversion. 8600 // "Whenever __ARM_FEATURE_SVE_BITS==N, GNUT implicitly 8601 // converts to VLAT and VLAT implicitly converts to GNUT." 8602 // ACLE Spec Version 00bet6, 3.7.3.2. Behavior common to vectors and 8603 // predicates. 8604 if (VecTy->getVectorKind() == VectorType::GenericVector && 8605 getTypeSize(SecondType) != getLangOpts().ArmSveVectorBits) 8606 return false; 8607 8608 // If -flax-vector-conversions=all is specified, the types are 8609 // certainly compatible. 8610 if (LVCKind == LangOptions::LaxVectorConversionKind::All) 8611 return true; 8612 8613 // If -flax-vector-conversions=integer is specified, the types are 8614 // compatible if the elements are integer types. 8615 if (LVCKind == LangOptions::LaxVectorConversionKind::Integer) 8616 return VecTy->getElementType().getCanonicalType()->isIntegerType() && 8617 FirstType->getSveEltType(*this)->isIntegerType(); 8618 } 8619 8620 return false; 8621 }; 8622 8623 return IsLaxCompatible(FirstType, SecondType) || 8624 IsLaxCompatible(SecondType, FirstType); 8625 } 8626 8627 bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const { 8628 while (true) { 8629 // __strong id 8630 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) { 8631 if (Attr->getAttrKind() == attr::ObjCOwnership) 8632 return true; 8633 8634 Ty = Attr->getModifiedType(); 8635 8636 // X *__strong (...) 8637 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) { 8638 Ty = Paren->getInnerType(); 8639 8640 // We do not want to look through typedefs, typeof(expr), 8641 // typeof(type), or any other way that the type is somehow 8642 // abstracted. 8643 } else { 8644 return false; 8645 } 8646 } 8647 } 8648 8649 //===----------------------------------------------------------------------===// 8650 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's. 8651 //===----------------------------------------------------------------------===// 8652 8653 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the 8654 /// inheritance hierarchy of 'rProto'. 8655 bool 8656 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, 8657 ObjCProtocolDecl *rProto) const { 8658 if (declaresSameEntity(lProto, rProto)) 8659 return true; 8660 for (auto *PI : rProto->protocols()) 8661 if (ProtocolCompatibleWithProtocol(lProto, PI)) 8662 return true; 8663 return false; 8664 } 8665 8666 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and 8667 /// Class<pr1, ...>. 8668 bool ASTContext::ObjCQualifiedClassTypesAreCompatible( 8669 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) { 8670 for (auto *lhsProto : lhs->quals()) { 8671 bool match = false; 8672 for (auto *rhsProto : rhs->quals()) { 8673 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) { 8674 match = true; 8675 break; 8676 } 8677 } 8678 if (!match) 8679 return false; 8680 } 8681 return true; 8682 } 8683 8684 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an 8685 /// ObjCQualifiedIDType. 8686 bool ASTContext::ObjCQualifiedIdTypesAreCompatible( 8687 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs, 8688 bool compare) { 8689 // Allow id<P..> and an 'id' in all cases. 8690 if (lhs->isObjCIdType() || rhs->isObjCIdType()) 8691 return true; 8692 8693 // Don't allow id<P..> to convert to Class or Class<P..> in either direction. 8694 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() || 8695 rhs->isObjCClassType() || rhs->isObjCQualifiedClassType()) 8696 return false; 8697 8698 if (lhs->isObjCQualifiedIdType()) { 8699 if (rhs->qual_empty()) { 8700 // If the RHS is a unqualified interface pointer "NSString*", 8701 // make sure we check the class hierarchy. 8702 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) { 8703 for (auto *I : lhs->quals()) { 8704 // when comparing an id<P> on lhs with a static type on rhs, 8705 // see if static class implements all of id's protocols, directly or 8706 // through its super class and categories. 8707 if (!rhsID->ClassImplementsProtocol(I, true)) 8708 return false; 8709 } 8710 } 8711 // If there are no qualifiers and no interface, we have an 'id'. 8712 return true; 8713 } 8714 // Both the right and left sides have qualifiers. 8715 for (auto *lhsProto : lhs->quals()) { 8716 bool match = false; 8717 8718 // when comparing an id<P> on lhs with a static type on rhs, 8719 // see if static class implements all of id's protocols, directly or 8720 // through its super class and categories. 8721 for (auto *rhsProto : rhs->quals()) { 8722 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 8723 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 8724 match = true; 8725 break; 8726 } 8727 } 8728 // If the RHS is a qualified interface pointer "NSString<P>*", 8729 // make sure we check the class hierarchy. 8730 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) { 8731 for (auto *I : lhs->quals()) { 8732 // when comparing an id<P> on lhs with a static type on rhs, 8733 // see if static class implements all of id's protocols, directly or 8734 // through its super class and categories. 8735 if (rhsID->ClassImplementsProtocol(I, true)) { 8736 match = true; 8737 break; 8738 } 8739 } 8740 } 8741 if (!match) 8742 return false; 8743 } 8744 8745 return true; 8746 } 8747 8748 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>"); 8749 8750 if (lhs->getInterfaceType()) { 8751 // If both the right and left sides have qualifiers. 8752 for (auto *lhsProto : lhs->quals()) { 8753 bool match = false; 8754 8755 // when comparing an id<P> on rhs with a static type on lhs, 8756 // see if static class implements all of id's protocols, directly or 8757 // through its super class and categories. 8758 // First, lhs protocols in the qualifier list must be found, direct 8759 // or indirect in rhs's qualifier list or it is a mismatch. 8760 for (auto *rhsProto : rhs->quals()) { 8761 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 8762 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 8763 match = true; 8764 break; 8765 } 8766 } 8767 if (!match) 8768 return false; 8769 } 8770 8771 // Static class's protocols, or its super class or category protocols 8772 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch. 8773 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) { 8774 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols; 8775 CollectInheritedProtocols(lhsID, LHSInheritedProtocols); 8776 // This is rather dubious but matches gcc's behavior. If lhs has 8777 // no type qualifier and its class has no static protocol(s) 8778 // assume that it is mismatch. 8779 if (LHSInheritedProtocols.empty() && lhs->qual_empty()) 8780 return false; 8781 for (auto *lhsProto : LHSInheritedProtocols) { 8782 bool match = false; 8783 for (auto *rhsProto : rhs->quals()) { 8784 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 8785 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 8786 match = true; 8787 break; 8788 } 8789 } 8790 if (!match) 8791 return false; 8792 } 8793 } 8794 return true; 8795 } 8796 return false; 8797 } 8798 8799 /// canAssignObjCInterfaces - Return true if the two interface types are 8800 /// compatible for assignment from RHS to LHS. This handles validation of any 8801 /// protocol qualifiers on the LHS or RHS. 8802 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, 8803 const ObjCObjectPointerType *RHSOPT) { 8804 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 8805 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 8806 8807 // If either type represents the built-in 'id' type, return true. 8808 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId()) 8809 return true; 8810 8811 // Function object that propagates a successful result or handles 8812 // __kindof types. 8813 auto finish = [&](bool succeeded) -> bool { 8814 if (succeeded) 8815 return true; 8816 8817 if (!RHS->isKindOfType()) 8818 return false; 8819 8820 // Strip off __kindof and protocol qualifiers, then check whether 8821 // we can assign the other way. 8822 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this), 8823 LHSOPT->stripObjCKindOfTypeAndQuals(*this)); 8824 }; 8825 8826 // Casts from or to id<P> are allowed when the other side has compatible 8827 // protocols. 8828 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) { 8829 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false)); 8830 } 8831 8832 // Verify protocol compatibility for casts from Class<P1> to Class<P2>. 8833 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) { 8834 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT)); 8835 } 8836 8837 // Casts from Class to Class<Foo>, or vice-versa, are allowed. 8838 if (LHS->isObjCClass() && RHS->isObjCClass()) { 8839 return true; 8840 } 8841 8842 // If we have 2 user-defined types, fall into that path. 8843 if (LHS->getInterface() && RHS->getInterface()) { 8844 return finish(canAssignObjCInterfaces(LHS, RHS)); 8845 } 8846 8847 return false; 8848 } 8849 8850 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written 8851 /// for providing type-safety for objective-c pointers used to pass/return 8852 /// arguments in block literals. When passed as arguments, passing 'A*' where 8853 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is 8854 /// not OK. For the return type, the opposite is not OK. 8855 bool ASTContext::canAssignObjCInterfacesInBlockPointer( 8856 const ObjCObjectPointerType *LHSOPT, 8857 const ObjCObjectPointerType *RHSOPT, 8858 bool BlockReturnType) { 8859 8860 // Function object that propagates a successful result or handles 8861 // __kindof types. 8862 auto finish = [&](bool succeeded) -> bool { 8863 if (succeeded) 8864 return true; 8865 8866 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT; 8867 if (!Expected->isKindOfType()) 8868 return false; 8869 8870 // Strip off __kindof and protocol qualifiers, then check whether 8871 // we can assign the other way. 8872 return canAssignObjCInterfacesInBlockPointer( 8873 RHSOPT->stripObjCKindOfTypeAndQuals(*this), 8874 LHSOPT->stripObjCKindOfTypeAndQuals(*this), 8875 BlockReturnType); 8876 }; 8877 8878 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType()) 8879 return true; 8880 8881 if (LHSOPT->isObjCBuiltinType()) { 8882 return finish(RHSOPT->isObjCBuiltinType() || 8883 RHSOPT->isObjCQualifiedIdType()); 8884 } 8885 8886 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) { 8887 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking) 8888 // Use for block parameters previous type checking for compatibility. 8889 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) || 8890 // Or corrected type checking as in non-compat mode. 8891 (!BlockReturnType && 8892 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false))); 8893 else 8894 return finish(ObjCQualifiedIdTypesAreCompatible( 8895 (BlockReturnType ? LHSOPT : RHSOPT), 8896 (BlockReturnType ? RHSOPT : LHSOPT), false)); 8897 } 8898 8899 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType(); 8900 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType(); 8901 if (LHS && RHS) { // We have 2 user-defined types. 8902 if (LHS != RHS) { 8903 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl())) 8904 return finish(BlockReturnType); 8905 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl())) 8906 return finish(!BlockReturnType); 8907 } 8908 else 8909 return true; 8910 } 8911 return false; 8912 } 8913 8914 /// Comparison routine for Objective-C protocols to be used with 8915 /// llvm::array_pod_sort. 8916 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs, 8917 ObjCProtocolDecl * const *rhs) { 8918 return (*lhs)->getName().compare((*rhs)->getName()); 8919 } 8920 8921 /// getIntersectionOfProtocols - This routine finds the intersection of set 8922 /// of protocols inherited from two distinct objective-c pointer objects with 8923 /// the given common base. 8924 /// It is used to build composite qualifier list of the composite type of 8925 /// the conditional expression involving two objective-c pointer objects. 8926 static 8927 void getIntersectionOfProtocols(ASTContext &Context, 8928 const ObjCInterfaceDecl *CommonBase, 8929 const ObjCObjectPointerType *LHSOPT, 8930 const ObjCObjectPointerType *RHSOPT, 8931 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) { 8932 8933 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 8934 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 8935 assert(LHS->getInterface() && "LHS must have an interface base"); 8936 assert(RHS->getInterface() && "RHS must have an interface base"); 8937 8938 // Add all of the protocols for the LHS. 8939 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet; 8940 8941 // Start with the protocol qualifiers. 8942 for (auto proto : LHS->quals()) { 8943 Context.CollectInheritedProtocols(proto, LHSProtocolSet); 8944 } 8945 8946 // Also add the protocols associated with the LHS interface. 8947 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet); 8948 8949 // Add all of the protocols for the RHS. 8950 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet; 8951 8952 // Start with the protocol qualifiers. 8953 for (auto proto : RHS->quals()) { 8954 Context.CollectInheritedProtocols(proto, RHSProtocolSet); 8955 } 8956 8957 // Also add the protocols associated with the RHS interface. 8958 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet); 8959 8960 // Compute the intersection of the collected protocol sets. 8961 for (auto proto : LHSProtocolSet) { 8962 if (RHSProtocolSet.count(proto)) 8963 IntersectionSet.push_back(proto); 8964 } 8965 8966 // Compute the set of protocols that is implied by either the common type or 8967 // the protocols within the intersection. 8968 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols; 8969 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols); 8970 8971 // Remove any implied protocols from the list of inherited protocols. 8972 if (!ImpliedProtocols.empty()) { 8973 IntersectionSet.erase( 8974 std::remove_if(IntersectionSet.begin(), 8975 IntersectionSet.end(), 8976 [&](ObjCProtocolDecl *proto) -> bool { 8977 return ImpliedProtocols.count(proto) > 0; 8978 }), 8979 IntersectionSet.end()); 8980 } 8981 8982 // Sort the remaining protocols by name. 8983 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(), 8984 compareObjCProtocolsByName); 8985 } 8986 8987 /// Determine whether the first type is a subtype of the second. 8988 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs, 8989 QualType rhs) { 8990 // Common case: two object pointers. 8991 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>(); 8992 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 8993 if (lhsOPT && rhsOPT) 8994 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT); 8995 8996 // Two block pointers. 8997 const auto *lhsBlock = lhs->getAs<BlockPointerType>(); 8998 const auto *rhsBlock = rhs->getAs<BlockPointerType>(); 8999 if (lhsBlock && rhsBlock) 9000 return ctx.typesAreBlockPointerCompatible(lhs, rhs); 9001 9002 // If either is an unqualified 'id' and the other is a block, it's 9003 // acceptable. 9004 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) || 9005 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock)) 9006 return true; 9007 9008 return false; 9009 } 9010 9011 // Check that the given Objective-C type argument lists are equivalent. 9012 static bool sameObjCTypeArgs(ASTContext &ctx, 9013 const ObjCInterfaceDecl *iface, 9014 ArrayRef<QualType> lhsArgs, 9015 ArrayRef<QualType> rhsArgs, 9016 bool stripKindOf) { 9017 if (lhsArgs.size() != rhsArgs.size()) 9018 return false; 9019 9020 ObjCTypeParamList *typeParams = iface->getTypeParamList(); 9021 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) { 9022 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i])) 9023 continue; 9024 9025 switch (typeParams->begin()[i]->getVariance()) { 9026 case ObjCTypeParamVariance::Invariant: 9027 if (!stripKindOf || 9028 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx), 9029 rhsArgs[i].stripObjCKindOfType(ctx))) { 9030 return false; 9031 } 9032 break; 9033 9034 case ObjCTypeParamVariance::Covariant: 9035 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i])) 9036 return false; 9037 break; 9038 9039 case ObjCTypeParamVariance::Contravariant: 9040 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i])) 9041 return false; 9042 break; 9043 } 9044 } 9045 9046 return true; 9047 } 9048 9049 QualType ASTContext::areCommonBaseCompatible( 9050 const ObjCObjectPointerType *Lptr, 9051 const ObjCObjectPointerType *Rptr) { 9052 const ObjCObjectType *LHS = Lptr->getObjectType(); 9053 const ObjCObjectType *RHS = Rptr->getObjectType(); 9054 const ObjCInterfaceDecl* LDecl = LHS->getInterface(); 9055 const ObjCInterfaceDecl* RDecl = RHS->getInterface(); 9056 9057 if (!LDecl || !RDecl) 9058 return {}; 9059 9060 // When either LHS or RHS is a kindof type, we should return a kindof type. 9061 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return 9062 // kindof(A). 9063 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType(); 9064 9065 // Follow the left-hand side up the class hierarchy until we either hit a 9066 // root or find the RHS. Record the ancestors in case we don't find it. 9067 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4> 9068 LHSAncestors; 9069 while (true) { 9070 // Record this ancestor. We'll need this if the common type isn't in the 9071 // path from the LHS to the root. 9072 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS; 9073 9074 if (declaresSameEntity(LHS->getInterface(), RDecl)) { 9075 // Get the type arguments. 9076 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten(); 9077 bool anyChanges = false; 9078 if (LHS->isSpecialized() && RHS->isSpecialized()) { 9079 // Both have type arguments, compare them. 9080 if (!sameObjCTypeArgs(*this, LHS->getInterface(), 9081 LHS->getTypeArgs(), RHS->getTypeArgs(), 9082 /*stripKindOf=*/true)) 9083 return {}; 9084 } else if (LHS->isSpecialized() != RHS->isSpecialized()) { 9085 // If only one has type arguments, the result will not have type 9086 // arguments. 9087 LHSTypeArgs = {}; 9088 anyChanges = true; 9089 } 9090 9091 // Compute the intersection of protocols. 9092 SmallVector<ObjCProtocolDecl *, 8> Protocols; 9093 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr, 9094 Protocols); 9095 if (!Protocols.empty()) 9096 anyChanges = true; 9097 9098 // If anything in the LHS will have changed, build a new result type. 9099 // If we need to return a kindof type but LHS is not a kindof type, we 9100 // build a new result type. 9101 if (anyChanges || LHS->isKindOfType() != anyKindOf) { 9102 QualType Result = getObjCInterfaceType(LHS->getInterface()); 9103 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols, 9104 anyKindOf || LHS->isKindOfType()); 9105 return getObjCObjectPointerType(Result); 9106 } 9107 9108 return getObjCObjectPointerType(QualType(LHS, 0)); 9109 } 9110 9111 // Find the superclass. 9112 QualType LHSSuperType = LHS->getSuperClassType(); 9113 if (LHSSuperType.isNull()) 9114 break; 9115 9116 LHS = LHSSuperType->castAs<ObjCObjectType>(); 9117 } 9118 9119 // We didn't find anything by following the LHS to its root; now check 9120 // the RHS against the cached set of ancestors. 9121 while (true) { 9122 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl()); 9123 if (KnownLHS != LHSAncestors.end()) { 9124 LHS = KnownLHS->second; 9125 9126 // Get the type arguments. 9127 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten(); 9128 bool anyChanges = false; 9129 if (LHS->isSpecialized() && RHS->isSpecialized()) { 9130 // Both have type arguments, compare them. 9131 if (!sameObjCTypeArgs(*this, LHS->getInterface(), 9132 LHS->getTypeArgs(), RHS->getTypeArgs(), 9133 /*stripKindOf=*/true)) 9134 return {}; 9135 } else if (LHS->isSpecialized() != RHS->isSpecialized()) { 9136 // If only one has type arguments, the result will not have type 9137 // arguments. 9138 RHSTypeArgs = {}; 9139 anyChanges = true; 9140 } 9141 9142 // Compute the intersection of protocols. 9143 SmallVector<ObjCProtocolDecl *, 8> Protocols; 9144 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr, 9145 Protocols); 9146 if (!Protocols.empty()) 9147 anyChanges = true; 9148 9149 // If we need to return a kindof type but RHS is not a kindof type, we 9150 // build a new result type. 9151 if (anyChanges || RHS->isKindOfType() != anyKindOf) { 9152 QualType Result = getObjCInterfaceType(RHS->getInterface()); 9153 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols, 9154 anyKindOf || RHS->isKindOfType()); 9155 return getObjCObjectPointerType(Result); 9156 } 9157 9158 return getObjCObjectPointerType(QualType(RHS, 0)); 9159 } 9160 9161 // Find the superclass of the RHS. 9162 QualType RHSSuperType = RHS->getSuperClassType(); 9163 if (RHSSuperType.isNull()) 9164 break; 9165 9166 RHS = RHSSuperType->castAs<ObjCObjectType>(); 9167 } 9168 9169 return {}; 9170 } 9171 9172 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS, 9173 const ObjCObjectType *RHS) { 9174 assert(LHS->getInterface() && "LHS is not an interface type"); 9175 assert(RHS->getInterface() && "RHS is not an interface type"); 9176 9177 // Verify that the base decls are compatible: the RHS must be a subclass of 9178 // the LHS. 9179 ObjCInterfaceDecl *LHSInterface = LHS->getInterface(); 9180 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface()); 9181 if (!IsSuperClass) 9182 return false; 9183 9184 // If the LHS has protocol qualifiers, determine whether all of them are 9185 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the 9186 // LHS). 9187 if (LHS->getNumProtocols() > 0) { 9188 // OK if conversion of LHS to SuperClass results in narrowing of types 9189 // ; i.e., SuperClass may implement at least one of the protocols 9190 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok. 9191 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>. 9192 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols; 9193 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols); 9194 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's 9195 // qualifiers. 9196 for (auto *RHSPI : RHS->quals()) 9197 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols); 9198 // If there is no protocols associated with RHS, it is not a match. 9199 if (SuperClassInheritedProtocols.empty()) 9200 return false; 9201 9202 for (const auto *LHSProto : LHS->quals()) { 9203 bool SuperImplementsProtocol = false; 9204 for (auto *SuperClassProto : SuperClassInheritedProtocols) 9205 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) { 9206 SuperImplementsProtocol = true; 9207 break; 9208 } 9209 if (!SuperImplementsProtocol) 9210 return false; 9211 } 9212 } 9213 9214 // If the LHS is specialized, we may need to check type arguments. 9215 if (LHS->isSpecialized()) { 9216 // Follow the superclass chain until we've matched the LHS class in the 9217 // hierarchy. This substitutes type arguments through. 9218 const ObjCObjectType *RHSSuper = RHS; 9219 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface)) 9220 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>(); 9221 9222 // If the RHS is specializd, compare type arguments. 9223 if (RHSSuper->isSpecialized() && 9224 !sameObjCTypeArgs(*this, LHS->getInterface(), 9225 LHS->getTypeArgs(), RHSSuper->getTypeArgs(), 9226 /*stripKindOf=*/true)) { 9227 return false; 9228 } 9229 } 9230 9231 return true; 9232 } 9233 9234 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) { 9235 // get the "pointed to" types 9236 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>(); 9237 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>(); 9238 9239 if (!LHSOPT || !RHSOPT) 9240 return false; 9241 9242 return canAssignObjCInterfaces(LHSOPT, RHSOPT) || 9243 canAssignObjCInterfaces(RHSOPT, LHSOPT); 9244 } 9245 9246 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) { 9247 return canAssignObjCInterfaces( 9248 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(), 9249 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>()); 9250 } 9251 9252 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible, 9253 /// both shall have the identically qualified version of a compatible type. 9254 /// C99 6.2.7p1: Two types have compatible types if their types are the 9255 /// same. See 6.7.[2,3,5] for additional rules. 9256 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS, 9257 bool CompareUnqualified) { 9258 if (getLangOpts().CPlusPlus) 9259 return hasSameType(LHS, RHS); 9260 9261 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull(); 9262 } 9263 9264 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) { 9265 return typesAreCompatible(LHS, RHS); 9266 } 9267 9268 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) { 9269 return !mergeTypes(LHS, RHS, true).isNull(); 9270 } 9271 9272 /// mergeTransparentUnionType - if T is a transparent union type and a member 9273 /// of T is compatible with SubType, return the merged type, else return 9274 /// QualType() 9275 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType, 9276 bool OfBlockPointer, 9277 bool Unqualified) { 9278 if (const RecordType *UT = T->getAsUnionType()) { 9279 RecordDecl *UD = UT->getDecl(); 9280 if (UD->hasAttr<TransparentUnionAttr>()) { 9281 for (const auto *I : UD->fields()) { 9282 QualType ET = I->getType().getUnqualifiedType(); 9283 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified); 9284 if (!MT.isNull()) 9285 return MT; 9286 } 9287 } 9288 } 9289 9290 return {}; 9291 } 9292 9293 /// mergeFunctionParameterTypes - merge two types which appear as function 9294 /// parameter types 9295 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs, 9296 bool OfBlockPointer, 9297 bool Unqualified) { 9298 // GNU extension: two types are compatible if they appear as a function 9299 // argument, one of the types is a transparent union type and the other 9300 // type is compatible with a union member 9301 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer, 9302 Unqualified); 9303 if (!lmerge.isNull()) 9304 return lmerge; 9305 9306 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer, 9307 Unqualified); 9308 if (!rmerge.isNull()) 9309 return rmerge; 9310 9311 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified); 9312 } 9313 9314 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, 9315 bool OfBlockPointer, bool Unqualified, 9316 bool AllowCXX) { 9317 const auto *lbase = lhs->castAs<FunctionType>(); 9318 const auto *rbase = rhs->castAs<FunctionType>(); 9319 const auto *lproto = dyn_cast<FunctionProtoType>(lbase); 9320 const auto *rproto = dyn_cast<FunctionProtoType>(rbase); 9321 bool allLTypes = true; 9322 bool allRTypes = true; 9323 9324 // Check return type 9325 QualType retType; 9326 if (OfBlockPointer) { 9327 QualType RHS = rbase->getReturnType(); 9328 QualType LHS = lbase->getReturnType(); 9329 bool UnqualifiedResult = Unqualified; 9330 if (!UnqualifiedResult) 9331 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers()); 9332 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true); 9333 } 9334 else 9335 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false, 9336 Unqualified); 9337 if (retType.isNull()) 9338 return {}; 9339 9340 if (Unqualified) 9341 retType = retType.getUnqualifiedType(); 9342 9343 CanQualType LRetType = getCanonicalType(lbase->getReturnType()); 9344 CanQualType RRetType = getCanonicalType(rbase->getReturnType()); 9345 if (Unqualified) { 9346 LRetType = LRetType.getUnqualifiedType(); 9347 RRetType = RRetType.getUnqualifiedType(); 9348 } 9349 9350 if (getCanonicalType(retType) != LRetType) 9351 allLTypes = false; 9352 if (getCanonicalType(retType) != RRetType) 9353 allRTypes = false; 9354 9355 // FIXME: double check this 9356 // FIXME: should we error if lbase->getRegParmAttr() != 0 && 9357 // rbase->getRegParmAttr() != 0 && 9358 // lbase->getRegParmAttr() != rbase->getRegParmAttr()? 9359 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo(); 9360 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo(); 9361 9362 // Compatible functions must have compatible calling conventions 9363 if (lbaseInfo.getCC() != rbaseInfo.getCC()) 9364 return {}; 9365 9366 // Regparm is part of the calling convention. 9367 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm()) 9368 return {}; 9369 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm()) 9370 return {}; 9371 9372 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult()) 9373 return {}; 9374 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs()) 9375 return {}; 9376 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck()) 9377 return {}; 9378 9379 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'. 9380 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn(); 9381 9382 if (lbaseInfo.getNoReturn() != NoReturn) 9383 allLTypes = false; 9384 if (rbaseInfo.getNoReturn() != NoReturn) 9385 allRTypes = false; 9386 9387 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn); 9388 9389 if (lproto && rproto) { // two C99 style function prototypes 9390 assert((AllowCXX || 9391 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) && 9392 "C++ shouldn't be here"); 9393 // Compatible functions must have the same number of parameters 9394 if (lproto->getNumParams() != rproto->getNumParams()) 9395 return {}; 9396 9397 // Variadic and non-variadic functions aren't compatible 9398 if (lproto->isVariadic() != rproto->isVariadic()) 9399 return {}; 9400 9401 if (lproto->getMethodQuals() != rproto->getMethodQuals()) 9402 return {}; 9403 9404 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos; 9405 bool canUseLeft, canUseRight; 9406 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight, 9407 newParamInfos)) 9408 return {}; 9409 9410 if (!canUseLeft) 9411 allLTypes = false; 9412 if (!canUseRight) 9413 allRTypes = false; 9414 9415 // Check parameter type compatibility 9416 SmallVector<QualType, 10> types; 9417 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) { 9418 QualType lParamType = lproto->getParamType(i).getUnqualifiedType(); 9419 QualType rParamType = rproto->getParamType(i).getUnqualifiedType(); 9420 QualType paramType = mergeFunctionParameterTypes( 9421 lParamType, rParamType, OfBlockPointer, Unqualified); 9422 if (paramType.isNull()) 9423 return {}; 9424 9425 if (Unqualified) 9426 paramType = paramType.getUnqualifiedType(); 9427 9428 types.push_back(paramType); 9429 if (Unqualified) { 9430 lParamType = lParamType.getUnqualifiedType(); 9431 rParamType = rParamType.getUnqualifiedType(); 9432 } 9433 9434 if (getCanonicalType(paramType) != getCanonicalType(lParamType)) 9435 allLTypes = false; 9436 if (getCanonicalType(paramType) != getCanonicalType(rParamType)) 9437 allRTypes = false; 9438 } 9439 9440 if (allLTypes) return lhs; 9441 if (allRTypes) return rhs; 9442 9443 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo(); 9444 EPI.ExtInfo = einfo; 9445 EPI.ExtParameterInfos = 9446 newParamInfos.empty() ? nullptr : newParamInfos.data(); 9447 return getFunctionType(retType, types, EPI); 9448 } 9449 9450 if (lproto) allRTypes = false; 9451 if (rproto) allLTypes = false; 9452 9453 const FunctionProtoType *proto = lproto ? lproto : rproto; 9454 if (proto) { 9455 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here"); 9456 if (proto->isVariadic()) 9457 return {}; 9458 // Check that the types are compatible with the types that 9459 // would result from default argument promotions (C99 6.7.5.3p15). 9460 // The only types actually affected are promotable integer 9461 // types and floats, which would be passed as a different 9462 // type depending on whether the prototype is visible. 9463 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) { 9464 QualType paramTy = proto->getParamType(i); 9465 9466 // Look at the converted type of enum types, since that is the type used 9467 // to pass enum values. 9468 if (const auto *Enum = paramTy->getAs<EnumType>()) { 9469 paramTy = Enum->getDecl()->getIntegerType(); 9470 if (paramTy.isNull()) 9471 return {}; 9472 } 9473 9474 if (paramTy->isPromotableIntegerType() || 9475 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy) 9476 return {}; 9477 } 9478 9479 if (allLTypes) return lhs; 9480 if (allRTypes) return rhs; 9481 9482 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo(); 9483 EPI.ExtInfo = einfo; 9484 return getFunctionType(retType, proto->getParamTypes(), EPI); 9485 } 9486 9487 if (allLTypes) return lhs; 9488 if (allRTypes) return rhs; 9489 return getFunctionNoProtoType(retType, einfo); 9490 } 9491 9492 /// Given that we have an enum type and a non-enum type, try to merge them. 9493 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET, 9494 QualType other, bool isBlockReturnType) { 9495 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char, 9496 // a signed integer type, or an unsigned integer type. 9497 // Compatibility is based on the underlying type, not the promotion 9498 // type. 9499 QualType underlyingType = ET->getDecl()->getIntegerType(); 9500 if (underlyingType.isNull()) 9501 return {}; 9502 if (Context.hasSameType(underlyingType, other)) 9503 return other; 9504 9505 // In block return types, we're more permissive and accept any 9506 // integral type of the same size. 9507 if (isBlockReturnType && other->isIntegerType() && 9508 Context.getTypeSize(underlyingType) == Context.getTypeSize(other)) 9509 return other; 9510 9511 return {}; 9512 } 9513 9514 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, 9515 bool OfBlockPointer, 9516 bool Unqualified, bool BlockReturnType) { 9517 // C++ [expr]: If an expression initially has the type "reference to T", the 9518 // type is adjusted to "T" prior to any further analysis, the expression 9519 // designates the object or function denoted by the reference, and the 9520 // expression is an lvalue unless the reference is an rvalue reference and 9521 // the expression is a function call (possibly inside parentheses). 9522 if (LHS->getAs<ReferenceType>() || RHS->getAs<ReferenceType>()) 9523 return {}; 9524 9525 if (Unqualified) { 9526 LHS = LHS.getUnqualifiedType(); 9527 RHS = RHS.getUnqualifiedType(); 9528 } 9529 9530 QualType LHSCan = getCanonicalType(LHS), 9531 RHSCan = getCanonicalType(RHS); 9532 9533 // If two types are identical, they are compatible. 9534 if (LHSCan == RHSCan) 9535 return LHS; 9536 9537 // If the qualifiers are different, the types aren't compatible... mostly. 9538 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 9539 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 9540 if (LQuals != RQuals) { 9541 // If any of these qualifiers are different, we have a type 9542 // mismatch. 9543 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 9544 LQuals.getAddressSpace() != RQuals.getAddressSpace() || 9545 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() || 9546 LQuals.hasUnaligned() != RQuals.hasUnaligned()) 9547 return {}; 9548 9549 // Exactly one GC qualifier difference is allowed: __strong is 9550 // okay if the other type has no GC qualifier but is an Objective 9551 // C object pointer (i.e. implicitly strong by default). We fix 9552 // this by pretending that the unqualified type was actually 9553 // qualified __strong. 9554 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 9555 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 9556 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 9557 9558 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 9559 return {}; 9560 9561 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) { 9562 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong)); 9563 } 9564 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) { 9565 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS); 9566 } 9567 return {}; 9568 } 9569 9570 // Okay, qualifiers are equal. 9571 9572 Type::TypeClass LHSClass = LHSCan->getTypeClass(); 9573 Type::TypeClass RHSClass = RHSCan->getTypeClass(); 9574 9575 // We want to consider the two function types to be the same for these 9576 // comparisons, just force one to the other. 9577 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto; 9578 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto; 9579 9580 // Same as above for arrays 9581 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray) 9582 LHSClass = Type::ConstantArray; 9583 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray) 9584 RHSClass = Type::ConstantArray; 9585 9586 // ObjCInterfaces are just specialized ObjCObjects. 9587 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject; 9588 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject; 9589 9590 // Canonicalize ExtVector -> Vector. 9591 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector; 9592 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector; 9593 9594 // If the canonical type classes don't match. 9595 if (LHSClass != RHSClass) { 9596 // Note that we only have special rules for turning block enum 9597 // returns into block int returns, not vice-versa. 9598 if (const auto *ETy = LHS->getAs<EnumType>()) { 9599 return mergeEnumWithInteger(*this, ETy, RHS, false); 9600 } 9601 if (const EnumType* ETy = RHS->getAs<EnumType>()) { 9602 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType); 9603 } 9604 // allow block pointer type to match an 'id' type. 9605 if (OfBlockPointer && !BlockReturnType) { 9606 if (LHS->isObjCIdType() && RHS->isBlockPointerType()) 9607 return LHS; 9608 if (RHS->isObjCIdType() && LHS->isBlockPointerType()) 9609 return RHS; 9610 } 9611 9612 return {}; 9613 } 9614 9615 // The canonical type classes match. 9616 switch (LHSClass) { 9617 #define TYPE(Class, Base) 9618 #define ABSTRACT_TYPE(Class, Base) 9619 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 9620 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 9621 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 9622 #include "clang/AST/TypeNodes.inc" 9623 llvm_unreachable("Non-canonical and dependent types shouldn't get here"); 9624 9625 case Type::Auto: 9626 case Type::DeducedTemplateSpecialization: 9627 case Type::LValueReference: 9628 case Type::RValueReference: 9629 case Type::MemberPointer: 9630 llvm_unreachable("C++ should never be in mergeTypes"); 9631 9632 case Type::ObjCInterface: 9633 case Type::IncompleteArray: 9634 case Type::VariableArray: 9635 case Type::FunctionProto: 9636 case Type::ExtVector: 9637 llvm_unreachable("Types are eliminated above"); 9638 9639 case Type::Pointer: 9640 { 9641 // Merge two pointer types, while trying to preserve typedef info 9642 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType(); 9643 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType(); 9644 if (Unqualified) { 9645 LHSPointee = LHSPointee.getUnqualifiedType(); 9646 RHSPointee = RHSPointee.getUnqualifiedType(); 9647 } 9648 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false, 9649 Unqualified); 9650 if (ResultType.isNull()) 9651 return {}; 9652 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 9653 return LHS; 9654 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 9655 return RHS; 9656 return getPointerType(ResultType); 9657 } 9658 case Type::BlockPointer: 9659 { 9660 // Merge two block pointer types, while trying to preserve typedef info 9661 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType(); 9662 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType(); 9663 if (Unqualified) { 9664 LHSPointee = LHSPointee.getUnqualifiedType(); 9665 RHSPointee = RHSPointee.getUnqualifiedType(); 9666 } 9667 if (getLangOpts().OpenCL) { 9668 Qualifiers LHSPteeQual = LHSPointee.getQualifiers(); 9669 Qualifiers RHSPteeQual = RHSPointee.getQualifiers(); 9670 // Blocks can't be an expression in a ternary operator (OpenCL v2.0 9671 // 6.12.5) thus the following check is asymmetric. 9672 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual)) 9673 return {}; 9674 LHSPteeQual.removeAddressSpace(); 9675 RHSPteeQual.removeAddressSpace(); 9676 LHSPointee = 9677 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue()); 9678 RHSPointee = 9679 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue()); 9680 } 9681 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer, 9682 Unqualified); 9683 if (ResultType.isNull()) 9684 return {}; 9685 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 9686 return LHS; 9687 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 9688 return RHS; 9689 return getBlockPointerType(ResultType); 9690 } 9691 case Type::Atomic: 9692 { 9693 // Merge two pointer types, while trying to preserve typedef info 9694 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType(); 9695 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType(); 9696 if (Unqualified) { 9697 LHSValue = LHSValue.getUnqualifiedType(); 9698 RHSValue = RHSValue.getUnqualifiedType(); 9699 } 9700 QualType ResultType = mergeTypes(LHSValue, RHSValue, false, 9701 Unqualified); 9702 if (ResultType.isNull()) 9703 return {}; 9704 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType)) 9705 return LHS; 9706 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType)) 9707 return RHS; 9708 return getAtomicType(ResultType); 9709 } 9710 case Type::ConstantArray: 9711 { 9712 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS); 9713 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS); 9714 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize()) 9715 return {}; 9716 9717 QualType LHSElem = getAsArrayType(LHS)->getElementType(); 9718 QualType RHSElem = getAsArrayType(RHS)->getElementType(); 9719 if (Unqualified) { 9720 LHSElem = LHSElem.getUnqualifiedType(); 9721 RHSElem = RHSElem.getUnqualifiedType(); 9722 } 9723 9724 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified); 9725 if (ResultType.isNull()) 9726 return {}; 9727 9728 const VariableArrayType* LVAT = getAsVariableArrayType(LHS); 9729 const VariableArrayType* RVAT = getAsVariableArrayType(RHS); 9730 9731 // If either side is a variable array, and both are complete, check whether 9732 // the current dimension is definite. 9733 if (LVAT || RVAT) { 9734 auto SizeFetch = [this](const VariableArrayType* VAT, 9735 const ConstantArrayType* CAT) 9736 -> std::pair<bool,llvm::APInt> { 9737 if (VAT) { 9738 Optional<llvm::APSInt> TheInt; 9739 Expr *E = VAT->getSizeExpr(); 9740 if (E && (TheInt = E->getIntegerConstantExpr(*this))) 9741 return std::make_pair(true, *TheInt); 9742 return std::make_pair(false, llvm::APSInt()); 9743 } 9744 if (CAT) 9745 return std::make_pair(true, CAT->getSize()); 9746 return std::make_pair(false, llvm::APInt()); 9747 }; 9748 9749 bool HaveLSize, HaveRSize; 9750 llvm::APInt LSize, RSize; 9751 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT); 9752 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT); 9753 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize)) 9754 return {}; // Definite, but unequal, array dimension 9755 } 9756 9757 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 9758 return LHS; 9759 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 9760 return RHS; 9761 if (LCAT) 9762 return getConstantArrayType(ResultType, LCAT->getSize(), 9763 LCAT->getSizeExpr(), 9764 ArrayType::ArraySizeModifier(), 0); 9765 if (RCAT) 9766 return getConstantArrayType(ResultType, RCAT->getSize(), 9767 RCAT->getSizeExpr(), 9768 ArrayType::ArraySizeModifier(), 0); 9769 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 9770 return LHS; 9771 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 9772 return RHS; 9773 if (LVAT) { 9774 // FIXME: This isn't correct! But tricky to implement because 9775 // the array's size has to be the size of LHS, but the type 9776 // has to be different. 9777 return LHS; 9778 } 9779 if (RVAT) { 9780 // FIXME: This isn't correct! But tricky to implement because 9781 // the array's size has to be the size of RHS, but the type 9782 // has to be different. 9783 return RHS; 9784 } 9785 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS; 9786 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS; 9787 return getIncompleteArrayType(ResultType, 9788 ArrayType::ArraySizeModifier(), 0); 9789 } 9790 case Type::FunctionNoProto: 9791 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified); 9792 case Type::Record: 9793 case Type::Enum: 9794 return {}; 9795 case Type::Builtin: 9796 // Only exactly equal builtin types are compatible, which is tested above. 9797 return {}; 9798 case Type::Complex: 9799 // Distinct complex types are incompatible. 9800 return {}; 9801 case Type::Vector: 9802 // FIXME: The merged type should be an ExtVector! 9803 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(), 9804 RHSCan->castAs<VectorType>())) 9805 return LHS; 9806 return {}; 9807 case Type::ConstantMatrix: 9808 if (areCompatMatrixTypes(LHSCan->castAs<ConstantMatrixType>(), 9809 RHSCan->castAs<ConstantMatrixType>())) 9810 return LHS; 9811 return {}; 9812 case Type::ObjCObject: { 9813 // Check if the types are assignment compatible. 9814 // FIXME: This should be type compatibility, e.g. whether 9815 // "LHS x; RHS x;" at global scope is legal. 9816 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectType>(), 9817 RHS->castAs<ObjCObjectType>())) 9818 return LHS; 9819 return {}; 9820 } 9821 case Type::ObjCObjectPointer: 9822 if (OfBlockPointer) { 9823 if (canAssignObjCInterfacesInBlockPointer( 9824 LHS->castAs<ObjCObjectPointerType>(), 9825 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType)) 9826 return LHS; 9827 return {}; 9828 } 9829 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectPointerType>(), 9830 RHS->castAs<ObjCObjectPointerType>())) 9831 return LHS; 9832 return {}; 9833 case Type::Pipe: 9834 assert(LHS != RHS && 9835 "Equivalent pipe types should have already been handled!"); 9836 return {}; 9837 case Type::ExtInt: { 9838 // Merge two ext-int types, while trying to preserve typedef info. 9839 bool LHSUnsigned = LHS->castAs<ExtIntType>()->isUnsigned(); 9840 bool RHSUnsigned = RHS->castAs<ExtIntType>()->isUnsigned(); 9841 unsigned LHSBits = LHS->castAs<ExtIntType>()->getNumBits(); 9842 unsigned RHSBits = RHS->castAs<ExtIntType>()->getNumBits(); 9843 9844 // Like unsigned/int, shouldn't have a type if they dont match. 9845 if (LHSUnsigned != RHSUnsigned) 9846 return {}; 9847 9848 if (LHSBits != RHSBits) 9849 return {}; 9850 return LHS; 9851 } 9852 } 9853 9854 llvm_unreachable("Invalid Type::Class!"); 9855 } 9856 9857 bool ASTContext::mergeExtParameterInfo( 9858 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType, 9859 bool &CanUseFirst, bool &CanUseSecond, 9860 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) { 9861 assert(NewParamInfos.empty() && "param info list not empty"); 9862 CanUseFirst = CanUseSecond = true; 9863 bool FirstHasInfo = FirstFnType->hasExtParameterInfos(); 9864 bool SecondHasInfo = SecondFnType->hasExtParameterInfos(); 9865 9866 // Fast path: if the first type doesn't have ext parameter infos, 9867 // we match if and only if the second type also doesn't have them. 9868 if (!FirstHasInfo && !SecondHasInfo) 9869 return true; 9870 9871 bool NeedParamInfo = false; 9872 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size() 9873 : SecondFnType->getExtParameterInfos().size(); 9874 9875 for (size_t I = 0; I < E; ++I) { 9876 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam; 9877 if (FirstHasInfo) 9878 FirstParam = FirstFnType->getExtParameterInfo(I); 9879 if (SecondHasInfo) 9880 SecondParam = SecondFnType->getExtParameterInfo(I); 9881 9882 // Cannot merge unless everything except the noescape flag matches. 9883 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false)) 9884 return false; 9885 9886 bool FirstNoEscape = FirstParam.isNoEscape(); 9887 bool SecondNoEscape = SecondParam.isNoEscape(); 9888 bool IsNoEscape = FirstNoEscape && SecondNoEscape; 9889 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape)); 9890 if (NewParamInfos.back().getOpaqueValue()) 9891 NeedParamInfo = true; 9892 if (FirstNoEscape != IsNoEscape) 9893 CanUseFirst = false; 9894 if (SecondNoEscape != IsNoEscape) 9895 CanUseSecond = false; 9896 } 9897 9898 if (!NeedParamInfo) 9899 NewParamInfos.clear(); 9900 9901 return true; 9902 } 9903 9904 void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) { 9905 ObjCLayouts[CD] = nullptr; 9906 } 9907 9908 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 9909 /// 'RHS' attributes and returns the merged version; including for function 9910 /// return types. 9911 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) { 9912 QualType LHSCan = getCanonicalType(LHS), 9913 RHSCan = getCanonicalType(RHS); 9914 // If two types are identical, they are compatible. 9915 if (LHSCan == RHSCan) 9916 return LHS; 9917 if (RHSCan->isFunctionType()) { 9918 if (!LHSCan->isFunctionType()) 9919 return {}; 9920 QualType OldReturnType = 9921 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType(); 9922 QualType NewReturnType = 9923 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType(); 9924 QualType ResReturnType = 9925 mergeObjCGCQualifiers(NewReturnType, OldReturnType); 9926 if (ResReturnType.isNull()) 9927 return {}; 9928 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) { 9929 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo(); 9930 // In either case, use OldReturnType to build the new function type. 9931 const auto *F = LHS->castAs<FunctionType>(); 9932 if (const auto *FPT = cast<FunctionProtoType>(F)) { 9933 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9934 EPI.ExtInfo = getFunctionExtInfo(LHS); 9935 QualType ResultType = 9936 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI); 9937 return ResultType; 9938 } 9939 } 9940 return {}; 9941 } 9942 9943 // If the qualifiers are different, the types can still be merged. 9944 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 9945 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 9946 if (LQuals != RQuals) { 9947 // If any of these qualifiers are different, we have a type mismatch. 9948 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 9949 LQuals.getAddressSpace() != RQuals.getAddressSpace()) 9950 return {}; 9951 9952 // Exactly one GC qualifier difference is allowed: __strong is 9953 // okay if the other type has no GC qualifier but is an Objective 9954 // C object pointer (i.e. implicitly strong by default). We fix 9955 // this by pretending that the unqualified type was actually 9956 // qualified __strong. 9957 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 9958 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 9959 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 9960 9961 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 9962 return {}; 9963 9964 if (GC_L == Qualifiers::Strong) 9965 return LHS; 9966 if (GC_R == Qualifiers::Strong) 9967 return RHS; 9968 return {}; 9969 } 9970 9971 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) { 9972 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType(); 9973 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType(); 9974 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT); 9975 if (ResQT == LHSBaseQT) 9976 return LHS; 9977 if (ResQT == RHSBaseQT) 9978 return RHS; 9979 } 9980 return {}; 9981 } 9982 9983 //===----------------------------------------------------------------------===// 9984 // Integer Predicates 9985 //===----------------------------------------------------------------------===// 9986 9987 unsigned ASTContext::getIntWidth(QualType T) const { 9988 if (const auto *ET = T->getAs<EnumType>()) 9989 T = ET->getDecl()->getIntegerType(); 9990 if (T->isBooleanType()) 9991 return 1; 9992 if(const auto *EIT = T->getAs<ExtIntType>()) 9993 return EIT->getNumBits(); 9994 // For builtin types, just use the standard type sizing method 9995 return (unsigned)getTypeSize(T); 9996 } 9997 9998 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const { 9999 assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) && 10000 "Unexpected type"); 10001 10002 // Turn <4 x signed int> -> <4 x unsigned int> 10003 if (const auto *VTy = T->getAs<VectorType>()) 10004 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()), 10005 VTy->getNumElements(), VTy->getVectorKind()); 10006 10007 // For enums, we return the unsigned version of the base type. 10008 if (const auto *ETy = T->getAs<EnumType>()) 10009 T = ETy->getDecl()->getIntegerType(); 10010 10011 switch (T->castAs<BuiltinType>()->getKind()) { 10012 case BuiltinType::Char_S: 10013 case BuiltinType::SChar: 10014 return UnsignedCharTy; 10015 case BuiltinType::Short: 10016 return UnsignedShortTy; 10017 case BuiltinType::Int: 10018 return UnsignedIntTy; 10019 case BuiltinType::Long: 10020 return UnsignedLongTy; 10021 case BuiltinType::LongLong: 10022 return UnsignedLongLongTy; 10023 case BuiltinType::Int128: 10024 return UnsignedInt128Ty; 10025 // wchar_t is special. It is either signed or not, but when it's signed, 10026 // there's no matching "unsigned wchar_t". Therefore we return the unsigned 10027 // version of it's underlying type instead. 10028 case BuiltinType::WChar_S: 10029 return getUnsignedWCharType(); 10030 10031 case BuiltinType::ShortAccum: 10032 return UnsignedShortAccumTy; 10033 case BuiltinType::Accum: 10034 return UnsignedAccumTy; 10035 case BuiltinType::LongAccum: 10036 return UnsignedLongAccumTy; 10037 case BuiltinType::SatShortAccum: 10038 return SatUnsignedShortAccumTy; 10039 case BuiltinType::SatAccum: 10040 return SatUnsignedAccumTy; 10041 case BuiltinType::SatLongAccum: 10042 return SatUnsignedLongAccumTy; 10043 case BuiltinType::ShortFract: 10044 return UnsignedShortFractTy; 10045 case BuiltinType::Fract: 10046 return UnsignedFractTy; 10047 case BuiltinType::LongFract: 10048 return UnsignedLongFractTy; 10049 case BuiltinType::SatShortFract: 10050 return SatUnsignedShortFractTy; 10051 case BuiltinType::SatFract: 10052 return SatUnsignedFractTy; 10053 case BuiltinType::SatLongFract: 10054 return SatUnsignedLongFractTy; 10055 default: 10056 llvm_unreachable("Unexpected signed integer or fixed point type"); 10057 } 10058 } 10059 10060 ASTMutationListener::~ASTMutationListener() = default; 10061 10062 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD, 10063 QualType ReturnType) {} 10064 10065 //===----------------------------------------------------------------------===// 10066 // Builtin Type Computation 10067 //===----------------------------------------------------------------------===// 10068 10069 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the 10070 /// pointer over the consumed characters. This returns the resultant type. If 10071 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic 10072 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of 10073 /// a vector of "i*". 10074 /// 10075 /// RequiresICE is filled in on return to indicate whether the value is required 10076 /// to be an Integer Constant Expression. 10077 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, 10078 ASTContext::GetBuiltinTypeError &Error, 10079 bool &RequiresICE, 10080 bool AllowTypeModifiers) { 10081 // Modifiers. 10082 int HowLong = 0; 10083 bool Signed = false, Unsigned = false; 10084 RequiresICE = false; 10085 10086 // Read the prefixed modifiers first. 10087 bool Done = false; 10088 #ifndef NDEBUG 10089 bool IsSpecial = false; 10090 #endif 10091 while (!Done) { 10092 switch (*Str++) { 10093 default: Done = true; --Str; break; 10094 case 'I': 10095 RequiresICE = true; 10096 break; 10097 case 'S': 10098 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!"); 10099 assert(!Signed && "Can't use 'S' modifier multiple times!"); 10100 Signed = true; 10101 break; 10102 case 'U': 10103 assert(!Signed && "Can't use both 'S' and 'U' modifiers!"); 10104 assert(!Unsigned && "Can't use 'U' modifier multiple times!"); 10105 Unsigned = true; 10106 break; 10107 case 'L': 10108 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers"); 10109 assert(HowLong <= 2 && "Can't have LLLL modifier"); 10110 ++HowLong; 10111 break; 10112 case 'N': 10113 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise. 10114 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10115 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!"); 10116 #ifndef NDEBUG 10117 IsSpecial = true; 10118 #endif 10119 if (Context.getTargetInfo().getLongWidth() == 32) 10120 ++HowLong; 10121 break; 10122 case 'W': 10123 // This modifier represents int64 type. 10124 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10125 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!"); 10126 #ifndef NDEBUG 10127 IsSpecial = true; 10128 #endif 10129 switch (Context.getTargetInfo().getInt64Type()) { 10130 default: 10131 llvm_unreachable("Unexpected integer type"); 10132 case TargetInfo::SignedLong: 10133 HowLong = 1; 10134 break; 10135 case TargetInfo::SignedLongLong: 10136 HowLong = 2; 10137 break; 10138 } 10139 break; 10140 case 'Z': 10141 // This modifier represents int32 type. 10142 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10143 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!"); 10144 #ifndef NDEBUG 10145 IsSpecial = true; 10146 #endif 10147 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) { 10148 default: 10149 llvm_unreachable("Unexpected integer type"); 10150 case TargetInfo::SignedInt: 10151 HowLong = 0; 10152 break; 10153 case TargetInfo::SignedLong: 10154 HowLong = 1; 10155 break; 10156 case TargetInfo::SignedLongLong: 10157 HowLong = 2; 10158 break; 10159 } 10160 break; 10161 case 'O': 10162 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10163 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!"); 10164 #ifndef NDEBUG 10165 IsSpecial = true; 10166 #endif 10167 if (Context.getLangOpts().OpenCL) 10168 HowLong = 1; 10169 else 10170 HowLong = 2; 10171 break; 10172 } 10173 } 10174 10175 QualType Type; 10176 10177 // Read the base type. 10178 switch (*Str++) { 10179 default: llvm_unreachable("Unknown builtin type letter!"); 10180 case 'y': 10181 assert(HowLong == 0 && !Signed && !Unsigned && 10182 "Bad modifiers used with 'y'!"); 10183 Type = Context.BFloat16Ty; 10184 break; 10185 case 'v': 10186 assert(HowLong == 0 && !Signed && !Unsigned && 10187 "Bad modifiers used with 'v'!"); 10188 Type = Context.VoidTy; 10189 break; 10190 case 'h': 10191 assert(HowLong == 0 && !Signed && !Unsigned && 10192 "Bad modifiers used with 'h'!"); 10193 Type = Context.HalfTy; 10194 break; 10195 case 'f': 10196 assert(HowLong == 0 && !Signed && !Unsigned && 10197 "Bad modifiers used with 'f'!"); 10198 Type = Context.FloatTy; 10199 break; 10200 case 'd': 10201 assert(HowLong < 3 && !Signed && !Unsigned && 10202 "Bad modifiers used with 'd'!"); 10203 if (HowLong == 1) 10204 Type = Context.LongDoubleTy; 10205 else if (HowLong == 2) 10206 Type = Context.Float128Ty; 10207 else 10208 Type = Context.DoubleTy; 10209 break; 10210 case 's': 10211 assert(HowLong == 0 && "Bad modifiers used with 's'!"); 10212 if (Unsigned) 10213 Type = Context.UnsignedShortTy; 10214 else 10215 Type = Context.ShortTy; 10216 break; 10217 case 'i': 10218 if (HowLong == 3) 10219 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty; 10220 else if (HowLong == 2) 10221 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy; 10222 else if (HowLong == 1) 10223 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy; 10224 else 10225 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy; 10226 break; 10227 case 'c': 10228 assert(HowLong == 0 && "Bad modifiers used with 'c'!"); 10229 if (Signed) 10230 Type = Context.SignedCharTy; 10231 else if (Unsigned) 10232 Type = Context.UnsignedCharTy; 10233 else 10234 Type = Context.CharTy; 10235 break; 10236 case 'b': // boolean 10237 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!"); 10238 Type = Context.BoolTy; 10239 break; 10240 case 'z': // size_t. 10241 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!"); 10242 Type = Context.getSizeType(); 10243 break; 10244 case 'w': // wchar_t. 10245 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!"); 10246 Type = Context.getWideCharType(); 10247 break; 10248 case 'F': 10249 Type = Context.getCFConstantStringType(); 10250 break; 10251 case 'G': 10252 Type = Context.getObjCIdType(); 10253 break; 10254 case 'H': 10255 Type = Context.getObjCSelType(); 10256 break; 10257 case 'M': 10258 Type = Context.getObjCSuperType(); 10259 break; 10260 case 'a': 10261 Type = Context.getBuiltinVaListType(); 10262 assert(!Type.isNull() && "builtin va list type not initialized!"); 10263 break; 10264 case 'A': 10265 // This is a "reference" to a va_list; however, what exactly 10266 // this means depends on how va_list is defined. There are two 10267 // different kinds of va_list: ones passed by value, and ones 10268 // passed by reference. An example of a by-value va_list is 10269 // x86, where va_list is a char*. An example of by-ref va_list 10270 // is x86-64, where va_list is a __va_list_tag[1]. For x86, 10271 // we want this argument to be a char*&; for x86-64, we want 10272 // it to be a __va_list_tag*. 10273 Type = Context.getBuiltinVaListType(); 10274 assert(!Type.isNull() && "builtin va list type not initialized!"); 10275 if (Type->isArrayType()) 10276 Type = Context.getArrayDecayedType(Type); 10277 else 10278 Type = Context.getLValueReferenceType(Type); 10279 break; 10280 case 'q': { 10281 char *End; 10282 unsigned NumElements = strtoul(Str, &End, 10); 10283 assert(End != Str && "Missing vector size"); 10284 Str = End; 10285 10286 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 10287 RequiresICE, false); 10288 assert(!RequiresICE && "Can't require vector ICE"); 10289 10290 Type = Context.getScalableVectorType(ElementType, NumElements); 10291 break; 10292 } 10293 case 'V': { 10294 char *End; 10295 unsigned NumElements = strtoul(Str, &End, 10); 10296 assert(End != Str && "Missing vector size"); 10297 Str = End; 10298 10299 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 10300 RequiresICE, false); 10301 assert(!RequiresICE && "Can't require vector ICE"); 10302 10303 // TODO: No way to make AltiVec vectors in builtins yet. 10304 Type = Context.getVectorType(ElementType, NumElements, 10305 VectorType::GenericVector); 10306 break; 10307 } 10308 case 'E': { 10309 char *End; 10310 10311 unsigned NumElements = strtoul(Str, &End, 10); 10312 assert(End != Str && "Missing vector size"); 10313 10314 Str = End; 10315 10316 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 10317 false); 10318 Type = Context.getExtVectorType(ElementType, NumElements); 10319 break; 10320 } 10321 case 'X': { 10322 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 10323 false); 10324 assert(!RequiresICE && "Can't require complex ICE"); 10325 Type = Context.getComplexType(ElementType); 10326 break; 10327 } 10328 case 'Y': 10329 Type = Context.getPointerDiffType(); 10330 break; 10331 case 'P': 10332 Type = Context.getFILEType(); 10333 if (Type.isNull()) { 10334 Error = ASTContext::GE_Missing_stdio; 10335 return {}; 10336 } 10337 break; 10338 case 'J': 10339 if (Signed) 10340 Type = Context.getsigjmp_bufType(); 10341 else 10342 Type = Context.getjmp_bufType(); 10343 10344 if (Type.isNull()) { 10345 Error = ASTContext::GE_Missing_setjmp; 10346 return {}; 10347 } 10348 break; 10349 case 'K': 10350 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!"); 10351 Type = Context.getucontext_tType(); 10352 10353 if (Type.isNull()) { 10354 Error = ASTContext::GE_Missing_ucontext; 10355 return {}; 10356 } 10357 break; 10358 case 'p': 10359 Type = Context.getProcessIDType(); 10360 break; 10361 } 10362 10363 // If there are modifiers and if we're allowed to parse them, go for it. 10364 Done = !AllowTypeModifiers; 10365 while (!Done) { 10366 switch (char c = *Str++) { 10367 default: Done = true; --Str; break; 10368 case '*': 10369 case '&': { 10370 // Both pointers and references can have their pointee types 10371 // qualified with an address space. 10372 char *End; 10373 unsigned AddrSpace = strtoul(Str, &End, 10); 10374 if (End != Str) { 10375 // Note AddrSpace == 0 is not the same as an unspecified address space. 10376 Type = Context.getAddrSpaceQualType( 10377 Type, 10378 Context.getLangASForBuiltinAddressSpace(AddrSpace)); 10379 Str = End; 10380 } 10381 if (c == '*') 10382 Type = Context.getPointerType(Type); 10383 else 10384 Type = Context.getLValueReferenceType(Type); 10385 break; 10386 } 10387 // FIXME: There's no way to have a built-in with an rvalue ref arg. 10388 case 'C': 10389 Type = Type.withConst(); 10390 break; 10391 case 'D': 10392 Type = Context.getVolatileType(Type); 10393 break; 10394 case 'R': 10395 Type = Type.withRestrict(); 10396 break; 10397 } 10398 } 10399 10400 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) && 10401 "Integer constant 'I' type must be an integer"); 10402 10403 return Type; 10404 } 10405 10406 // On some targets such as PowerPC, some of the builtins are defined with custom 10407 // type decriptors for target-dependent types. These descriptors are decoded in 10408 // other functions, but it may be useful to be able to fall back to default 10409 // descriptor decoding to define builtins mixing target-dependent and target- 10410 // independent types. This function allows decoding one type descriptor with 10411 // default decoding. 10412 QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context, 10413 GetBuiltinTypeError &Error, bool &RequireICE, 10414 bool AllowTypeModifiers) const { 10415 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers); 10416 } 10417 10418 /// GetBuiltinType - Return the type for the specified builtin. 10419 QualType ASTContext::GetBuiltinType(unsigned Id, 10420 GetBuiltinTypeError &Error, 10421 unsigned *IntegerConstantArgs) const { 10422 const char *TypeStr = BuiltinInfo.getTypeString(Id); 10423 if (TypeStr[0] == '\0') { 10424 Error = GE_Missing_type; 10425 return {}; 10426 } 10427 10428 SmallVector<QualType, 8> ArgTypes; 10429 10430 bool RequiresICE = false; 10431 Error = GE_None; 10432 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error, 10433 RequiresICE, true); 10434 if (Error != GE_None) 10435 return {}; 10436 10437 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE"); 10438 10439 while (TypeStr[0] && TypeStr[0] != '.') { 10440 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true); 10441 if (Error != GE_None) 10442 return {}; 10443 10444 // If this argument is required to be an IntegerConstantExpression and the 10445 // caller cares, fill in the bitmask we return. 10446 if (RequiresICE && IntegerConstantArgs) 10447 *IntegerConstantArgs |= 1 << ArgTypes.size(); 10448 10449 // Do array -> pointer decay. The builtin should use the decayed type. 10450 if (Ty->isArrayType()) 10451 Ty = getArrayDecayedType(Ty); 10452 10453 ArgTypes.push_back(Ty); 10454 } 10455 10456 if (Id == Builtin::BI__GetExceptionInfo) 10457 return {}; 10458 10459 assert((TypeStr[0] != '.' || TypeStr[1] == 0) && 10460 "'.' should only occur at end of builtin type list!"); 10461 10462 bool Variadic = (TypeStr[0] == '.'); 10463 10464 FunctionType::ExtInfo EI(getDefaultCallingConvention( 10465 Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true)); 10466 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true); 10467 10468 10469 // We really shouldn't be making a no-proto type here. 10470 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus) 10471 return getFunctionNoProtoType(ResType, EI); 10472 10473 FunctionProtoType::ExtProtoInfo EPI; 10474 EPI.ExtInfo = EI; 10475 EPI.Variadic = Variadic; 10476 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id)) 10477 EPI.ExceptionSpec.Type = 10478 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone; 10479 10480 return getFunctionType(ResType, ArgTypes, EPI); 10481 } 10482 10483 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, 10484 const FunctionDecl *FD) { 10485 if (!FD->isExternallyVisible()) 10486 return GVA_Internal; 10487 10488 // Non-user-provided functions get emitted as weak definitions with every 10489 // use, no matter whether they've been explicitly instantiated etc. 10490 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 10491 if (!MD->isUserProvided()) 10492 return GVA_DiscardableODR; 10493 10494 GVALinkage External; 10495 switch (FD->getTemplateSpecializationKind()) { 10496 case TSK_Undeclared: 10497 case TSK_ExplicitSpecialization: 10498 External = GVA_StrongExternal; 10499 break; 10500 10501 case TSK_ExplicitInstantiationDefinition: 10502 return GVA_StrongODR; 10503 10504 // C++11 [temp.explicit]p10: 10505 // [ Note: The intent is that an inline function that is the subject of 10506 // an explicit instantiation declaration will still be implicitly 10507 // instantiated when used so that the body can be considered for 10508 // inlining, but that no out-of-line copy of the inline function would be 10509 // generated in the translation unit. -- end note ] 10510 case TSK_ExplicitInstantiationDeclaration: 10511 return GVA_AvailableExternally; 10512 10513 case TSK_ImplicitInstantiation: 10514 External = GVA_DiscardableODR; 10515 break; 10516 } 10517 10518 if (!FD->isInlined()) 10519 return External; 10520 10521 if ((!Context.getLangOpts().CPlusPlus && 10522 !Context.getTargetInfo().getCXXABI().isMicrosoft() && 10523 !FD->hasAttr<DLLExportAttr>()) || 10524 FD->hasAttr<GNUInlineAttr>()) { 10525 // FIXME: This doesn't match gcc's behavior for dllexport inline functions. 10526 10527 // GNU or C99 inline semantics. Determine whether this symbol should be 10528 // externally visible. 10529 if (FD->isInlineDefinitionExternallyVisible()) 10530 return External; 10531 10532 // C99 inline semantics, where the symbol is not externally visible. 10533 return GVA_AvailableExternally; 10534 } 10535 10536 // Functions specified with extern and inline in -fms-compatibility mode 10537 // forcibly get emitted. While the body of the function cannot be later 10538 // replaced, the function definition cannot be discarded. 10539 if (FD->isMSExternInline()) 10540 return GVA_StrongODR; 10541 10542 return GVA_DiscardableODR; 10543 } 10544 10545 static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context, 10546 const Decl *D, GVALinkage L) { 10547 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx 10548 // dllexport/dllimport on inline functions. 10549 if (D->hasAttr<DLLImportAttr>()) { 10550 if (L == GVA_DiscardableODR || L == GVA_StrongODR) 10551 return GVA_AvailableExternally; 10552 } else if (D->hasAttr<DLLExportAttr>()) { 10553 if (L == GVA_DiscardableODR) 10554 return GVA_StrongODR; 10555 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) { 10556 // Device-side functions with __global__ attribute must always be 10557 // visible externally so they can be launched from host. 10558 if (D->hasAttr<CUDAGlobalAttr>() && 10559 (L == GVA_DiscardableODR || L == GVA_Internal)) 10560 return GVA_StrongODR; 10561 // Single source offloading languages like CUDA/HIP need to be able to 10562 // access static device variables from host code of the same compilation 10563 // unit. This is done by externalizing the static variable. 10564 if (Context.shouldExternalizeStaticVar(D)) 10565 return GVA_StrongExternal; 10566 } 10567 return L; 10568 } 10569 10570 /// Adjust the GVALinkage for a declaration based on what an external AST source 10571 /// knows about whether there can be other definitions of this declaration. 10572 static GVALinkage 10573 adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D, 10574 GVALinkage L) { 10575 ExternalASTSource *Source = Ctx.getExternalSource(); 10576 if (!Source) 10577 return L; 10578 10579 switch (Source->hasExternalDefinitions(D)) { 10580 case ExternalASTSource::EK_Never: 10581 // Other translation units rely on us to provide the definition. 10582 if (L == GVA_DiscardableODR) 10583 return GVA_StrongODR; 10584 break; 10585 10586 case ExternalASTSource::EK_Always: 10587 return GVA_AvailableExternally; 10588 10589 case ExternalASTSource::EK_ReplyHazy: 10590 break; 10591 } 10592 return L; 10593 } 10594 10595 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const { 10596 return adjustGVALinkageForExternalDefinitionKind(*this, FD, 10597 adjustGVALinkageForAttributes(*this, FD, 10598 basicGVALinkageForFunction(*this, FD))); 10599 } 10600 10601 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context, 10602 const VarDecl *VD) { 10603 if (!VD->isExternallyVisible()) 10604 return GVA_Internal; 10605 10606 if (VD->isStaticLocal()) { 10607 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod(); 10608 while (LexicalContext && !isa<FunctionDecl>(LexicalContext)) 10609 LexicalContext = LexicalContext->getLexicalParent(); 10610 10611 // ObjC Blocks can create local variables that don't have a FunctionDecl 10612 // LexicalContext. 10613 if (!LexicalContext) 10614 return GVA_DiscardableODR; 10615 10616 // Otherwise, let the static local variable inherit its linkage from the 10617 // nearest enclosing function. 10618 auto StaticLocalLinkage = 10619 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext)); 10620 10621 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must 10622 // be emitted in any object with references to the symbol for the object it 10623 // contains, whether inline or out-of-line." 10624 // Similar behavior is observed with MSVC. An alternative ABI could use 10625 // StrongODR/AvailableExternally to match the function, but none are 10626 // known/supported currently. 10627 if (StaticLocalLinkage == GVA_StrongODR || 10628 StaticLocalLinkage == GVA_AvailableExternally) 10629 return GVA_DiscardableODR; 10630 return StaticLocalLinkage; 10631 } 10632 10633 // MSVC treats in-class initialized static data members as definitions. 10634 // By giving them non-strong linkage, out-of-line definitions won't 10635 // cause link errors. 10636 if (Context.isMSStaticDataMemberInlineDefinition(VD)) 10637 return GVA_DiscardableODR; 10638 10639 // Most non-template variables have strong linkage; inline variables are 10640 // linkonce_odr or (occasionally, for compatibility) weak_odr. 10641 GVALinkage StrongLinkage; 10642 switch (Context.getInlineVariableDefinitionKind(VD)) { 10643 case ASTContext::InlineVariableDefinitionKind::None: 10644 StrongLinkage = GVA_StrongExternal; 10645 break; 10646 case ASTContext::InlineVariableDefinitionKind::Weak: 10647 case ASTContext::InlineVariableDefinitionKind::WeakUnknown: 10648 StrongLinkage = GVA_DiscardableODR; 10649 break; 10650 case ASTContext::InlineVariableDefinitionKind::Strong: 10651 StrongLinkage = GVA_StrongODR; 10652 break; 10653 } 10654 10655 switch (VD->getTemplateSpecializationKind()) { 10656 case TSK_Undeclared: 10657 return StrongLinkage; 10658 10659 case TSK_ExplicitSpecialization: 10660 return Context.getTargetInfo().getCXXABI().isMicrosoft() && 10661 VD->isStaticDataMember() 10662 ? GVA_StrongODR 10663 : StrongLinkage; 10664 10665 case TSK_ExplicitInstantiationDefinition: 10666 return GVA_StrongODR; 10667 10668 case TSK_ExplicitInstantiationDeclaration: 10669 return GVA_AvailableExternally; 10670 10671 case TSK_ImplicitInstantiation: 10672 return GVA_DiscardableODR; 10673 } 10674 10675 llvm_unreachable("Invalid Linkage!"); 10676 } 10677 10678 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) { 10679 return adjustGVALinkageForExternalDefinitionKind(*this, VD, 10680 adjustGVALinkageForAttributes(*this, VD, 10681 basicGVALinkageForVariable(*this, VD))); 10682 } 10683 10684 bool ASTContext::DeclMustBeEmitted(const Decl *D) { 10685 if (const auto *VD = dyn_cast<VarDecl>(D)) { 10686 if (!VD->isFileVarDecl()) 10687 return false; 10688 // Global named register variables (GNU extension) are never emitted. 10689 if (VD->getStorageClass() == SC_Register) 10690 return false; 10691 if (VD->getDescribedVarTemplate() || 10692 isa<VarTemplatePartialSpecializationDecl>(VD)) 10693 return false; 10694 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 10695 // We never need to emit an uninstantiated function template. 10696 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10697 return false; 10698 } else if (isa<PragmaCommentDecl>(D)) 10699 return true; 10700 else if (isa<PragmaDetectMismatchDecl>(D)) 10701 return true; 10702 else if (isa<OMPRequiresDecl>(D)) 10703 return true; 10704 else if (isa<OMPThreadPrivateDecl>(D)) 10705 return !D->getDeclContext()->isDependentContext(); 10706 else if (isa<OMPAllocateDecl>(D)) 10707 return !D->getDeclContext()->isDependentContext(); 10708 else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D)) 10709 return !D->getDeclContext()->isDependentContext(); 10710 else if (isa<ImportDecl>(D)) 10711 return true; 10712 else 10713 return false; 10714 10715 // If this is a member of a class template, we do not need to emit it. 10716 if (D->getDeclContext()->isDependentContext()) 10717 return false; 10718 10719 // Weak references don't produce any output by themselves. 10720 if (D->hasAttr<WeakRefAttr>()) 10721 return false; 10722 10723 // Aliases and used decls are required. 10724 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>()) 10725 return true; 10726 10727 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 10728 // Forward declarations aren't required. 10729 if (!FD->doesThisDeclarationHaveABody()) 10730 return FD->doesDeclarationForceExternallyVisibleDefinition(); 10731 10732 // Constructors and destructors are required. 10733 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>()) 10734 return true; 10735 10736 // The key function for a class is required. This rule only comes 10737 // into play when inline functions can be key functions, though. 10738 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 10739 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 10740 const CXXRecordDecl *RD = MD->getParent(); 10741 if (MD->isOutOfLine() && RD->isDynamicClass()) { 10742 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD); 10743 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl()) 10744 return true; 10745 } 10746 } 10747 } 10748 10749 GVALinkage Linkage = GetGVALinkageForFunction(FD); 10750 10751 // static, static inline, always_inline, and extern inline functions can 10752 // always be deferred. Normal inline functions can be deferred in C99/C++. 10753 // Implicit template instantiations can also be deferred in C++. 10754 return !isDiscardableGVALinkage(Linkage); 10755 } 10756 10757 const auto *VD = cast<VarDecl>(D); 10758 assert(VD->isFileVarDecl() && "Expected file scoped var"); 10759 10760 // If the decl is marked as `declare target to`, it should be emitted for the 10761 // host and for the device. 10762 if (LangOpts.OpenMP && 10763 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 10764 return true; 10765 10766 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly && 10767 !isMSStaticDataMemberInlineDefinition(VD)) 10768 return false; 10769 10770 // Variables that can be needed in other TUs are required. 10771 auto Linkage = GetGVALinkageForVariable(VD); 10772 if (!isDiscardableGVALinkage(Linkage)) 10773 return true; 10774 10775 // We never need to emit a variable that is available in another TU. 10776 if (Linkage == GVA_AvailableExternally) 10777 return false; 10778 10779 // Variables that have destruction with side-effects are required. 10780 if (VD->needsDestruction(*this)) 10781 return true; 10782 10783 // Variables that have initialization with side-effects are required. 10784 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) && 10785 // We can get a value-dependent initializer during error recovery. 10786 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 10787 return true; 10788 10789 // Likewise, variables with tuple-like bindings are required if their 10790 // bindings have side-effects. 10791 if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) 10792 for (const auto *BD : DD->bindings()) 10793 if (const auto *BindingVD = BD->getHoldingVar()) 10794 if (DeclMustBeEmitted(BindingVD)) 10795 return true; 10796 10797 return false; 10798 } 10799 10800 void ASTContext::forEachMultiversionedFunctionVersion( 10801 const FunctionDecl *FD, 10802 llvm::function_ref<void(FunctionDecl *)> Pred) const { 10803 assert(FD->isMultiVersion() && "Only valid for multiversioned functions"); 10804 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls; 10805 FD = FD->getMostRecentDecl(); 10806 for (auto *CurDecl : 10807 FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) { 10808 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl(); 10809 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) && 10810 std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) { 10811 SeenDecls.insert(CurFD); 10812 Pred(CurFD); 10813 } 10814 } 10815 } 10816 10817 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic, 10818 bool IsCXXMethod, 10819 bool IsBuiltin) const { 10820 // Pass through to the C++ ABI object 10821 if (IsCXXMethod) 10822 return ABI->getDefaultMethodCallConv(IsVariadic); 10823 10824 // Builtins ignore user-specified default calling convention and remain the 10825 // Target's default calling convention. 10826 if (!IsBuiltin) { 10827 switch (LangOpts.getDefaultCallingConv()) { 10828 case LangOptions::DCC_None: 10829 break; 10830 case LangOptions::DCC_CDecl: 10831 return CC_C; 10832 case LangOptions::DCC_FastCall: 10833 if (getTargetInfo().hasFeature("sse2") && !IsVariadic) 10834 return CC_X86FastCall; 10835 break; 10836 case LangOptions::DCC_StdCall: 10837 if (!IsVariadic) 10838 return CC_X86StdCall; 10839 break; 10840 case LangOptions::DCC_VectorCall: 10841 // __vectorcall cannot be applied to variadic functions. 10842 if (!IsVariadic) 10843 return CC_X86VectorCall; 10844 break; 10845 case LangOptions::DCC_RegCall: 10846 // __regcall cannot be applied to variadic functions. 10847 if (!IsVariadic) 10848 return CC_X86RegCall; 10849 break; 10850 } 10851 } 10852 return Target->getDefaultCallingConv(); 10853 } 10854 10855 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const { 10856 // Pass through to the C++ ABI object 10857 return ABI->isNearlyEmpty(RD); 10858 } 10859 10860 VTableContextBase *ASTContext::getVTableContext() { 10861 if (!VTContext.get()) { 10862 auto ABI = Target->getCXXABI(); 10863 if (ABI.isMicrosoft()) 10864 VTContext.reset(new MicrosoftVTableContext(*this)); 10865 else { 10866 auto ComponentLayout = getLangOpts().RelativeCXXABIVTables 10867 ? ItaniumVTableContext::Relative 10868 : ItaniumVTableContext::Pointer; 10869 VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout)); 10870 } 10871 } 10872 return VTContext.get(); 10873 } 10874 10875 MangleContext *ASTContext::createMangleContext(const TargetInfo *T) { 10876 if (!T) 10877 T = Target; 10878 switch (T->getCXXABI().getKind()) { 10879 case TargetCXXABI::AppleARM64: 10880 case TargetCXXABI::Fuchsia: 10881 case TargetCXXABI::GenericAArch64: 10882 case TargetCXXABI::GenericItanium: 10883 case TargetCXXABI::GenericARM: 10884 case TargetCXXABI::GenericMIPS: 10885 case TargetCXXABI::iOS: 10886 case TargetCXXABI::WebAssembly: 10887 case TargetCXXABI::WatchOS: 10888 case TargetCXXABI::XL: 10889 return ItaniumMangleContext::create(*this, getDiagnostics()); 10890 case TargetCXXABI::Microsoft: 10891 return MicrosoftMangleContext::create(*this, getDiagnostics()); 10892 } 10893 llvm_unreachable("Unsupported ABI"); 10894 } 10895 10896 CXXABI::~CXXABI() = default; 10897 10898 size_t ASTContext::getSideTableAllocatedMemory() const { 10899 return ASTRecordLayouts.getMemorySize() + 10900 llvm::capacity_in_bytes(ObjCLayouts) + 10901 llvm::capacity_in_bytes(KeyFunctions) + 10902 llvm::capacity_in_bytes(ObjCImpls) + 10903 llvm::capacity_in_bytes(BlockVarCopyInits) + 10904 llvm::capacity_in_bytes(DeclAttrs) + 10905 llvm::capacity_in_bytes(TemplateOrInstantiation) + 10906 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) + 10907 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) + 10908 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) + 10909 llvm::capacity_in_bytes(OverriddenMethods) + 10910 llvm::capacity_in_bytes(Types) + 10911 llvm::capacity_in_bytes(VariableArrayTypes); 10912 } 10913 10914 /// getIntTypeForBitwidth - 10915 /// sets integer QualTy according to specified details: 10916 /// bitwidth, signed/unsigned. 10917 /// Returns empty type if there is no appropriate target types. 10918 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth, 10919 unsigned Signed) const { 10920 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed); 10921 CanQualType QualTy = getFromTargetType(Ty); 10922 if (!QualTy && DestWidth == 128) 10923 return Signed ? Int128Ty : UnsignedInt128Ty; 10924 return QualTy; 10925 } 10926 10927 /// getRealTypeForBitwidth - 10928 /// sets floating point QualTy according to specified bitwidth. 10929 /// Returns empty type if there is no appropriate target types. 10930 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth, 10931 bool ExplicitIEEE) const { 10932 TargetInfo::RealType Ty = 10933 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitIEEE); 10934 switch (Ty) { 10935 case TargetInfo::Float: 10936 return FloatTy; 10937 case TargetInfo::Double: 10938 return DoubleTy; 10939 case TargetInfo::LongDouble: 10940 return LongDoubleTy; 10941 case TargetInfo::Float128: 10942 return Float128Ty; 10943 case TargetInfo::NoFloat: 10944 return {}; 10945 } 10946 10947 llvm_unreachable("Unhandled TargetInfo::RealType value"); 10948 } 10949 10950 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) { 10951 if (Number > 1) 10952 MangleNumbers[ND] = Number; 10953 } 10954 10955 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const { 10956 auto I = MangleNumbers.find(ND); 10957 return I != MangleNumbers.end() ? I->second : 1; 10958 } 10959 10960 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) { 10961 if (Number > 1) 10962 StaticLocalNumbers[VD] = Number; 10963 } 10964 10965 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const { 10966 auto I = StaticLocalNumbers.find(VD); 10967 return I != StaticLocalNumbers.end() ? I->second : 1; 10968 } 10969 10970 MangleNumberingContext & 10971 ASTContext::getManglingNumberContext(const DeclContext *DC) { 10972 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C. 10973 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC]; 10974 if (!MCtx) 10975 MCtx = createMangleNumberingContext(); 10976 return *MCtx; 10977 } 10978 10979 MangleNumberingContext & 10980 ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) { 10981 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C. 10982 std::unique_ptr<MangleNumberingContext> &MCtx = 10983 ExtraMangleNumberingContexts[D]; 10984 if (!MCtx) 10985 MCtx = createMangleNumberingContext(); 10986 return *MCtx; 10987 } 10988 10989 std::unique_ptr<MangleNumberingContext> 10990 ASTContext::createMangleNumberingContext() const { 10991 return ABI->createMangleNumberingContext(); 10992 } 10993 10994 const CXXConstructorDecl * 10995 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) { 10996 return ABI->getCopyConstructorForExceptionObject( 10997 cast<CXXRecordDecl>(RD->getFirstDecl())); 10998 } 10999 11000 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD, 11001 CXXConstructorDecl *CD) { 11002 return ABI->addCopyConstructorForExceptionObject( 11003 cast<CXXRecordDecl>(RD->getFirstDecl()), 11004 cast<CXXConstructorDecl>(CD->getFirstDecl())); 11005 } 11006 11007 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD, 11008 TypedefNameDecl *DD) { 11009 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD); 11010 } 11011 11012 TypedefNameDecl * 11013 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) { 11014 return ABI->getTypedefNameForUnnamedTagDecl(TD); 11015 } 11016 11017 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD, 11018 DeclaratorDecl *DD) { 11019 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD); 11020 } 11021 11022 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) { 11023 return ABI->getDeclaratorForUnnamedTagDecl(TD); 11024 } 11025 11026 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) { 11027 ParamIndices[D] = index; 11028 } 11029 11030 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const { 11031 ParameterIndexTable::const_iterator I = ParamIndices.find(D); 11032 assert(I != ParamIndices.end() && 11033 "ParmIndices lacks entry set by ParmVarDecl"); 11034 return I->second; 11035 } 11036 11037 QualType ASTContext::getStringLiteralArrayType(QualType EltTy, 11038 unsigned Length) const { 11039 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 11040 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 11041 EltTy = EltTy.withConst(); 11042 11043 EltTy = adjustStringLiteralBaseType(EltTy); 11044 11045 // Get an array type for the string, according to C99 6.4.5. This includes 11046 // the null terminator character. 11047 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr, 11048 ArrayType::Normal, /*IndexTypeQuals*/ 0); 11049 } 11050 11051 StringLiteral * 11052 ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const { 11053 StringLiteral *&Result = StringLiteralCache[Key]; 11054 if (!Result) 11055 Result = StringLiteral::Create( 11056 *this, Key, StringLiteral::Ascii, 11057 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()), 11058 SourceLocation()); 11059 return Result; 11060 } 11061 11062 MSGuidDecl * 11063 ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const { 11064 assert(MSGuidTagDecl && "building MS GUID without MS extensions?"); 11065 11066 llvm::FoldingSetNodeID ID; 11067 MSGuidDecl::Profile(ID, Parts); 11068 11069 void *InsertPos; 11070 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos)) 11071 return Existing; 11072 11073 QualType GUIDType = getMSGuidType().withConst(); 11074 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts); 11075 MSGuidDecls.InsertNode(New, InsertPos); 11076 return New; 11077 } 11078 11079 TemplateParamObjectDecl * 11080 ASTContext::getTemplateParamObjectDecl(QualType T, const APValue &V) const { 11081 assert(T->isRecordType() && "template param object of unexpected type"); 11082 11083 // C++ [temp.param]p8: 11084 // [...] a static storage duration object of type 'const T' [...] 11085 T.addConst(); 11086 11087 llvm::FoldingSetNodeID ID; 11088 TemplateParamObjectDecl::Profile(ID, T, V); 11089 11090 void *InsertPos; 11091 if (TemplateParamObjectDecl *Existing = 11092 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos)) 11093 return Existing; 11094 11095 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V); 11096 TemplateParamObjectDecls.InsertNode(New, InsertPos); 11097 return New; 11098 } 11099 11100 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const { 11101 const llvm::Triple &T = getTargetInfo().getTriple(); 11102 if (!T.isOSDarwin()) 11103 return false; 11104 11105 if (!(T.isiOS() && T.isOSVersionLT(7)) && 11106 !(T.isMacOSX() && T.isOSVersionLT(10, 9))) 11107 return false; 11108 11109 QualType AtomicTy = E->getPtr()->getType()->getPointeeType(); 11110 CharUnits sizeChars = getTypeSizeInChars(AtomicTy); 11111 uint64_t Size = sizeChars.getQuantity(); 11112 CharUnits alignChars = getTypeAlignInChars(AtomicTy); 11113 unsigned Align = alignChars.getQuantity(); 11114 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth(); 11115 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits); 11116 } 11117 11118 bool 11119 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, 11120 const ObjCMethodDecl *MethodImpl) { 11121 // No point trying to match an unavailable/deprecated mothod. 11122 if (MethodDecl->hasAttr<UnavailableAttr>() 11123 || MethodDecl->hasAttr<DeprecatedAttr>()) 11124 return false; 11125 if (MethodDecl->getObjCDeclQualifier() != 11126 MethodImpl->getObjCDeclQualifier()) 11127 return false; 11128 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType())) 11129 return false; 11130 11131 if (MethodDecl->param_size() != MethodImpl->param_size()) 11132 return false; 11133 11134 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(), 11135 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(), 11136 EF = MethodDecl->param_end(); 11137 IM != EM && IF != EF; ++IM, ++IF) { 11138 const ParmVarDecl *DeclVar = (*IF); 11139 const ParmVarDecl *ImplVar = (*IM); 11140 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier()) 11141 return false; 11142 if (!hasSameType(DeclVar->getType(), ImplVar->getType())) 11143 return false; 11144 } 11145 11146 return (MethodDecl->isVariadic() == MethodImpl->isVariadic()); 11147 } 11148 11149 uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const { 11150 LangAS AS; 11151 if (QT->getUnqualifiedDesugaredType()->isNullPtrType()) 11152 AS = LangAS::Default; 11153 else 11154 AS = QT->getPointeeType().getAddressSpace(); 11155 11156 return getTargetInfo().getNullPointerValue(AS); 11157 } 11158 11159 unsigned ASTContext::getTargetAddressSpace(LangAS AS) const { 11160 if (isTargetAddressSpace(AS)) 11161 return toTargetAddressSpace(AS); 11162 else 11163 return (*AddrSpaceMap)[(unsigned)AS]; 11164 } 11165 11166 QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const { 11167 assert(Ty->isFixedPointType()); 11168 11169 if (Ty->isSaturatedFixedPointType()) return Ty; 11170 11171 switch (Ty->castAs<BuiltinType>()->getKind()) { 11172 default: 11173 llvm_unreachable("Not a fixed point type!"); 11174 case BuiltinType::ShortAccum: 11175 return SatShortAccumTy; 11176 case BuiltinType::Accum: 11177 return SatAccumTy; 11178 case BuiltinType::LongAccum: 11179 return SatLongAccumTy; 11180 case BuiltinType::UShortAccum: 11181 return SatUnsignedShortAccumTy; 11182 case BuiltinType::UAccum: 11183 return SatUnsignedAccumTy; 11184 case BuiltinType::ULongAccum: 11185 return SatUnsignedLongAccumTy; 11186 case BuiltinType::ShortFract: 11187 return SatShortFractTy; 11188 case BuiltinType::Fract: 11189 return SatFractTy; 11190 case BuiltinType::LongFract: 11191 return SatLongFractTy; 11192 case BuiltinType::UShortFract: 11193 return SatUnsignedShortFractTy; 11194 case BuiltinType::UFract: 11195 return SatUnsignedFractTy; 11196 case BuiltinType::ULongFract: 11197 return SatUnsignedLongFractTy; 11198 } 11199 } 11200 11201 LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const { 11202 if (LangOpts.OpenCL) 11203 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS); 11204 11205 if (LangOpts.CUDA) 11206 return getTargetInfo().getCUDABuiltinAddressSpace(AS); 11207 11208 return getLangASFromTargetAS(AS); 11209 } 11210 11211 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that 11212 // doesn't include ASTContext.h 11213 template 11214 clang::LazyGenerationalUpdatePtr< 11215 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType 11216 clang::LazyGenerationalUpdatePtr< 11217 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue( 11218 const clang::ASTContext &Ctx, Decl *Value); 11219 11220 unsigned char ASTContext::getFixedPointScale(QualType Ty) const { 11221 assert(Ty->isFixedPointType()); 11222 11223 const TargetInfo &Target = getTargetInfo(); 11224 switch (Ty->castAs<BuiltinType>()->getKind()) { 11225 default: 11226 llvm_unreachable("Not a fixed point type!"); 11227 case BuiltinType::ShortAccum: 11228 case BuiltinType::SatShortAccum: 11229 return Target.getShortAccumScale(); 11230 case BuiltinType::Accum: 11231 case BuiltinType::SatAccum: 11232 return Target.getAccumScale(); 11233 case BuiltinType::LongAccum: 11234 case BuiltinType::SatLongAccum: 11235 return Target.getLongAccumScale(); 11236 case BuiltinType::UShortAccum: 11237 case BuiltinType::SatUShortAccum: 11238 return Target.getUnsignedShortAccumScale(); 11239 case BuiltinType::UAccum: 11240 case BuiltinType::SatUAccum: 11241 return Target.getUnsignedAccumScale(); 11242 case BuiltinType::ULongAccum: 11243 case BuiltinType::SatULongAccum: 11244 return Target.getUnsignedLongAccumScale(); 11245 case BuiltinType::ShortFract: 11246 case BuiltinType::SatShortFract: 11247 return Target.getShortFractScale(); 11248 case BuiltinType::Fract: 11249 case BuiltinType::SatFract: 11250 return Target.getFractScale(); 11251 case BuiltinType::LongFract: 11252 case BuiltinType::SatLongFract: 11253 return Target.getLongFractScale(); 11254 case BuiltinType::UShortFract: 11255 case BuiltinType::SatUShortFract: 11256 return Target.getUnsignedShortFractScale(); 11257 case BuiltinType::UFract: 11258 case BuiltinType::SatUFract: 11259 return Target.getUnsignedFractScale(); 11260 case BuiltinType::ULongFract: 11261 case BuiltinType::SatULongFract: 11262 return Target.getUnsignedLongFractScale(); 11263 } 11264 } 11265 11266 unsigned char ASTContext::getFixedPointIBits(QualType Ty) const { 11267 assert(Ty->isFixedPointType()); 11268 11269 const TargetInfo &Target = getTargetInfo(); 11270 switch (Ty->castAs<BuiltinType>()->getKind()) { 11271 default: 11272 llvm_unreachable("Not a fixed point type!"); 11273 case BuiltinType::ShortAccum: 11274 case BuiltinType::SatShortAccum: 11275 return Target.getShortAccumIBits(); 11276 case BuiltinType::Accum: 11277 case BuiltinType::SatAccum: 11278 return Target.getAccumIBits(); 11279 case BuiltinType::LongAccum: 11280 case BuiltinType::SatLongAccum: 11281 return Target.getLongAccumIBits(); 11282 case BuiltinType::UShortAccum: 11283 case BuiltinType::SatUShortAccum: 11284 return Target.getUnsignedShortAccumIBits(); 11285 case BuiltinType::UAccum: 11286 case BuiltinType::SatUAccum: 11287 return Target.getUnsignedAccumIBits(); 11288 case BuiltinType::ULongAccum: 11289 case BuiltinType::SatULongAccum: 11290 return Target.getUnsignedLongAccumIBits(); 11291 case BuiltinType::ShortFract: 11292 case BuiltinType::SatShortFract: 11293 case BuiltinType::Fract: 11294 case BuiltinType::SatFract: 11295 case BuiltinType::LongFract: 11296 case BuiltinType::SatLongFract: 11297 case BuiltinType::UShortFract: 11298 case BuiltinType::SatUShortFract: 11299 case BuiltinType::UFract: 11300 case BuiltinType::SatUFract: 11301 case BuiltinType::ULongFract: 11302 case BuiltinType::SatULongFract: 11303 return 0; 11304 } 11305 } 11306 11307 llvm::FixedPointSemantics 11308 ASTContext::getFixedPointSemantics(QualType Ty) const { 11309 assert((Ty->isFixedPointType() || Ty->isIntegerType()) && 11310 "Can only get the fixed point semantics for a " 11311 "fixed point or integer type."); 11312 if (Ty->isIntegerType()) 11313 return llvm::FixedPointSemantics::GetIntegerSemantics( 11314 getIntWidth(Ty), Ty->isSignedIntegerType()); 11315 11316 bool isSigned = Ty->isSignedFixedPointType(); 11317 return llvm::FixedPointSemantics( 11318 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned, 11319 Ty->isSaturatedFixedPointType(), 11320 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding()); 11321 } 11322 11323 llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const { 11324 assert(Ty->isFixedPointType()); 11325 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty)); 11326 } 11327 11328 llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const { 11329 assert(Ty->isFixedPointType()); 11330 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty)); 11331 } 11332 11333 QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const { 11334 assert(Ty->isUnsignedFixedPointType() && 11335 "Expected unsigned fixed point type"); 11336 11337 switch (Ty->castAs<BuiltinType>()->getKind()) { 11338 case BuiltinType::UShortAccum: 11339 return ShortAccumTy; 11340 case BuiltinType::UAccum: 11341 return AccumTy; 11342 case BuiltinType::ULongAccum: 11343 return LongAccumTy; 11344 case BuiltinType::SatUShortAccum: 11345 return SatShortAccumTy; 11346 case BuiltinType::SatUAccum: 11347 return SatAccumTy; 11348 case BuiltinType::SatULongAccum: 11349 return SatLongAccumTy; 11350 case BuiltinType::UShortFract: 11351 return ShortFractTy; 11352 case BuiltinType::UFract: 11353 return FractTy; 11354 case BuiltinType::ULongFract: 11355 return LongFractTy; 11356 case BuiltinType::SatUShortFract: 11357 return SatShortFractTy; 11358 case BuiltinType::SatUFract: 11359 return SatFractTy; 11360 case BuiltinType::SatULongFract: 11361 return SatLongFractTy; 11362 default: 11363 llvm_unreachable("Unexpected unsigned fixed point type"); 11364 } 11365 } 11366 11367 ParsedTargetAttr 11368 ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const { 11369 assert(TD != nullptr); 11370 ParsedTargetAttr ParsedAttr = TD->parse(); 11371 11372 ParsedAttr.Features.erase( 11373 llvm::remove_if(ParsedAttr.Features, 11374 [&](const std::string &Feat) { 11375 return !Target->isValidFeatureName( 11376 StringRef{Feat}.substr(1)); 11377 }), 11378 ParsedAttr.Features.end()); 11379 return ParsedAttr; 11380 } 11381 11382 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 11383 const FunctionDecl *FD) const { 11384 if (FD) 11385 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD)); 11386 else 11387 Target->initFeatureMap(FeatureMap, getDiagnostics(), 11388 Target->getTargetOpts().CPU, 11389 Target->getTargetOpts().Features); 11390 } 11391 11392 // Fills in the supplied string map with the set of target features for the 11393 // passed in function. 11394 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 11395 GlobalDecl GD) const { 11396 StringRef TargetCPU = Target->getTargetOpts().CPU; 11397 const FunctionDecl *FD = GD.getDecl()->getAsFunction(); 11398 if (const auto *TD = FD->getAttr<TargetAttr>()) { 11399 ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD); 11400 11401 // Make a copy of the features as passed on the command line into the 11402 // beginning of the additional features from the function to override. 11403 ParsedAttr.Features.insert( 11404 ParsedAttr.Features.begin(), 11405 Target->getTargetOpts().FeaturesAsWritten.begin(), 11406 Target->getTargetOpts().FeaturesAsWritten.end()); 11407 11408 if (ParsedAttr.Architecture != "" && 11409 Target->isValidCPUName(ParsedAttr.Architecture)) 11410 TargetCPU = ParsedAttr.Architecture; 11411 11412 // Now populate the feature map, first with the TargetCPU which is either 11413 // the default or a new one from the target attribute string. Then we'll use 11414 // the passed in features (FeaturesAsWritten) along with the new ones from 11415 // the attribute. 11416 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, 11417 ParsedAttr.Features); 11418 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) { 11419 llvm::SmallVector<StringRef, 32> FeaturesTmp; 11420 Target->getCPUSpecificCPUDispatchFeatures( 11421 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp); 11422 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end()); 11423 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features); 11424 } else { 11425 FeatureMap = Target->getTargetOpts().FeatureMap; 11426 } 11427 } 11428 11429 OMPTraitInfo &ASTContext::getNewOMPTraitInfo() { 11430 OMPTraitInfoVector.emplace_back(new OMPTraitInfo()); 11431 return *OMPTraitInfoVector.back(); 11432 } 11433 11434 const StreamingDiagnostic &clang:: 11435 operator<<(const StreamingDiagnostic &DB, 11436 const ASTContext::SectionInfo &Section) { 11437 if (Section.Decl) 11438 return DB << Section.Decl; 11439 return DB << "a prior #pragma section"; 11440 } 11441 11442 bool ASTContext::mayExternalizeStaticVar(const Decl *D) const { 11443 return !getLangOpts().GPURelocatableDeviceCode && 11444 ((D->hasAttr<CUDADeviceAttr>() && 11445 !D->getAttr<CUDADeviceAttr>()->isImplicit()) || 11446 (D->hasAttr<CUDAConstantAttr>() && 11447 !D->getAttr<CUDAConstantAttr>()->isImplicit())) && 11448 isa<VarDecl>(D) && cast<VarDecl>(D)->isFileVarDecl() && 11449 cast<VarDecl>(D)->getStorageClass() == SC_Static; 11450 } 11451 11452 bool ASTContext::shouldExternalizeStaticVar(const Decl *D) const { 11453 return mayExternalizeStaticVar(D) && 11454 CUDAStaticDeviceVarReferencedByHost.count(cast<VarDecl>(D)); 11455 } 11456