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