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