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