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