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