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