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