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