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