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