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