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