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