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