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