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