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