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