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