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