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