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