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