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