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