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