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