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