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