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