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