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