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