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