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