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