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