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