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