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