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