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