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