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