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