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