ASTContext.cpp revision b7d0844c887a72064b624dc6df12cbe1441f69d0
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/DeclCXX.h" 16#include "clang/AST/DeclObjC.h" 17#include "clang/AST/DeclTemplate.h" 18#include "clang/AST/Expr.h" 19#include "clang/AST/RecordLayout.h" 20#include "clang/Basic/TargetInfo.h" 21#include "llvm/ADT/StringExtras.h" 22#include "llvm/Bitcode/Serialize.h" 23#include "llvm/Bitcode/Deserialize.h" 24#include "llvm/Support/MathExtras.h" 25 26using namespace clang; 27 28enum FloatingRank { 29 FloatRank, DoubleRank, LongDoubleRank 30}; 31 32ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM, 33 TargetInfo &t, 34 IdentifierTable &idents, SelectorTable &sels, 35 bool FreeMem, unsigned size_reserve) : 36 CFConstantStringTypeDecl(0), ObjCFastEnumerationStateTypeDecl(0), 37 SourceMgr(SM), LangOpts(LOpts), FreeMemory(FreeMem), Target(t), 38 Idents(idents), Selectors(sels) 39{ 40 if (size_reserve > 0) Types.reserve(size_reserve); 41 InitBuiltinTypes(); 42 BuiltinInfo.InitializeBuiltins(idents, Target, LangOpts.Freestanding); 43 TUDecl = TranslationUnitDecl::Create(*this); 44} 45 46ASTContext::~ASTContext() { 47 // Deallocate all the types. 48 while (!Types.empty()) { 49 Types.back()->Destroy(*this); 50 Types.pop_back(); 51 } 52 53 { 54 llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator 55 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); 56 while (I != E) { 57 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second); 58 delete R; 59 } 60 } 61 62 { 63 llvm::DenseMap<const ObjCInterfaceDecl*, const ASTRecordLayout*>::iterator 64 I = ASTObjCInterfaces.begin(), E = ASTObjCInterfaces.end(); 65 while (I != E) { 66 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second); 67 delete R; 68 } 69 } 70 71 { 72 llvm::DenseMap<const ObjCInterfaceDecl*, const RecordDecl*>::iterator 73 I = ASTRecordForInterface.begin(), E = ASTRecordForInterface.end(); 74 while (I != E) { 75 RecordDecl *R = const_cast<RecordDecl*>((I++)->second); 76 R->Destroy(*this); 77 } 78 } 79 80 TUDecl->Destroy(*this); 81} 82 83void ASTContext::PrintStats() const { 84 fprintf(stderr, "*** AST Context Stats:\n"); 85 fprintf(stderr, " %d types total.\n", (int)Types.size()); 86 unsigned NumBuiltin = 0, NumPointer = 0, NumArray = 0, NumFunctionP = 0; 87 unsigned NumVector = 0, NumComplex = 0, NumBlockPointer = 0; 88 unsigned NumFunctionNP = 0, NumTypeName = 0, NumTagged = 0, NumReference = 0; 89 unsigned NumMemberPointer = 0; 90 91 unsigned NumTagStruct = 0, NumTagUnion = 0, NumTagEnum = 0, NumTagClass = 0; 92 unsigned NumObjCInterfaces = 0, NumObjCQualifiedInterfaces = 0; 93 unsigned NumObjCQualifiedIds = 0; 94 unsigned NumTypeOfTypes = 0, NumTypeOfExprs = 0; 95 96 for (unsigned i = 0, e = Types.size(); i != e; ++i) { 97 Type *T = Types[i]; 98 if (isa<BuiltinType>(T)) 99 ++NumBuiltin; 100 else if (isa<PointerType>(T)) 101 ++NumPointer; 102 else if (isa<BlockPointerType>(T)) 103 ++NumBlockPointer; 104 else if (isa<ReferenceType>(T)) 105 ++NumReference; 106 else if (isa<MemberPointerType>(T)) 107 ++NumMemberPointer; 108 else if (isa<ComplexType>(T)) 109 ++NumComplex; 110 else if (isa<ArrayType>(T)) 111 ++NumArray; 112 else if (isa<VectorType>(T)) 113 ++NumVector; 114 else if (isa<FunctionTypeNoProto>(T)) 115 ++NumFunctionNP; 116 else if (isa<FunctionTypeProto>(T)) 117 ++NumFunctionP; 118 else if (isa<TypedefType>(T)) 119 ++NumTypeName; 120 else if (TagType *TT = dyn_cast<TagType>(T)) { 121 ++NumTagged; 122 switch (TT->getDecl()->getTagKind()) { 123 default: assert(0 && "Unknown tagged type!"); 124 case TagDecl::TK_struct: ++NumTagStruct; break; 125 case TagDecl::TK_union: ++NumTagUnion; break; 126 case TagDecl::TK_class: ++NumTagClass; break; 127 case TagDecl::TK_enum: ++NumTagEnum; break; 128 } 129 } else if (isa<ObjCInterfaceType>(T)) 130 ++NumObjCInterfaces; 131 else if (isa<ObjCQualifiedInterfaceType>(T)) 132 ++NumObjCQualifiedInterfaces; 133 else if (isa<ObjCQualifiedIdType>(T)) 134 ++NumObjCQualifiedIds; 135 else if (isa<TypeOfType>(T)) 136 ++NumTypeOfTypes; 137 else if (isa<TypeOfExpr>(T)) 138 ++NumTypeOfExprs; 139 else { 140 QualType(T, 0).dump(); 141 assert(0 && "Unknown type!"); 142 } 143 } 144 145 fprintf(stderr, " %d builtin types\n", NumBuiltin); 146 fprintf(stderr, " %d pointer types\n", NumPointer); 147 fprintf(stderr, " %d block pointer types\n", NumBlockPointer); 148 fprintf(stderr, " %d reference types\n", NumReference); 149 fprintf(stderr, " %d member pointer types\n", NumMemberPointer); 150 fprintf(stderr, " %d complex types\n", NumComplex); 151 fprintf(stderr, " %d array types\n", NumArray); 152 fprintf(stderr, " %d vector types\n", NumVector); 153 fprintf(stderr, " %d function types with proto\n", NumFunctionP); 154 fprintf(stderr, " %d function types with no proto\n", NumFunctionNP); 155 fprintf(stderr, " %d typename (typedef) types\n", NumTypeName); 156 fprintf(stderr, " %d tagged types\n", NumTagged); 157 fprintf(stderr, " %d struct types\n", NumTagStruct); 158 fprintf(stderr, " %d union types\n", NumTagUnion); 159 fprintf(stderr, " %d class types\n", NumTagClass); 160 fprintf(stderr, " %d enum types\n", NumTagEnum); 161 fprintf(stderr, " %d interface types\n", NumObjCInterfaces); 162 fprintf(stderr, " %d protocol qualified interface types\n", 163 NumObjCQualifiedInterfaces); 164 fprintf(stderr, " %d protocol qualified id types\n", 165 NumObjCQualifiedIds); 166 fprintf(stderr, " %d typeof types\n", NumTypeOfTypes); 167 fprintf(stderr, " %d typeof exprs\n", NumTypeOfExprs); 168 169 fprintf(stderr, "Total bytes = %d\n", int(NumBuiltin*sizeof(BuiltinType)+ 170 NumPointer*sizeof(PointerType)+NumArray*sizeof(ArrayType)+ 171 NumComplex*sizeof(ComplexType)+NumVector*sizeof(VectorType)+ 172 NumMemberPointer*sizeof(MemberPointerType)+ 173 NumFunctionP*sizeof(FunctionTypeProto)+ 174 NumFunctionNP*sizeof(FunctionTypeNoProto)+ 175 NumTypeName*sizeof(TypedefType)+NumTagged*sizeof(TagType)+ 176 NumTypeOfTypes*sizeof(TypeOfType)+NumTypeOfExprs*sizeof(TypeOfExpr))); 177} 178 179 180void ASTContext::InitBuiltinType(QualType &R, BuiltinType::Kind K) { 181 Types.push_back((R = QualType(new (*this,8) BuiltinType(K),0)).getTypePtr()); 182} 183 184void ASTContext::InitBuiltinTypes() { 185 assert(VoidTy.isNull() && "Context reinitialized?"); 186 187 // C99 6.2.5p19. 188 InitBuiltinType(VoidTy, BuiltinType::Void); 189 190 // C99 6.2.5p2. 191 InitBuiltinType(BoolTy, BuiltinType::Bool); 192 // C99 6.2.5p3. 193 if (Target.isCharSigned()) 194 InitBuiltinType(CharTy, BuiltinType::Char_S); 195 else 196 InitBuiltinType(CharTy, BuiltinType::Char_U); 197 // C99 6.2.5p4. 198 InitBuiltinType(SignedCharTy, BuiltinType::SChar); 199 InitBuiltinType(ShortTy, BuiltinType::Short); 200 InitBuiltinType(IntTy, BuiltinType::Int); 201 InitBuiltinType(LongTy, BuiltinType::Long); 202 InitBuiltinType(LongLongTy, BuiltinType::LongLong); 203 204 // C99 6.2.5p6. 205 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar); 206 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort); 207 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt); 208 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong); 209 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong); 210 211 // C99 6.2.5p10. 212 InitBuiltinType(FloatTy, BuiltinType::Float); 213 InitBuiltinType(DoubleTy, BuiltinType::Double); 214 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble); 215 216 // C++ 3.9.1p5 217 InitBuiltinType(WCharTy, BuiltinType::WChar); 218 219 // Placeholder type for functions. 220 InitBuiltinType(OverloadTy, BuiltinType::Overload); 221 222 // Placeholder type for type-dependent expressions whose type is 223 // completely unknown. No code should ever check a type against 224 // DependentTy and users should never see it; however, it is here to 225 // help diagnose failures to properly check for type-dependent 226 // expressions. 227 InitBuiltinType(DependentTy, BuiltinType::Dependent); 228 229 // C99 6.2.5p11. 230 FloatComplexTy = getComplexType(FloatTy); 231 DoubleComplexTy = getComplexType(DoubleTy); 232 LongDoubleComplexTy = getComplexType(LongDoubleTy); 233 234 BuiltinVaListType = QualType(); 235 ObjCIdType = QualType(); 236 IdStructType = 0; 237 ObjCClassType = QualType(); 238 ClassStructType = 0; 239 240 ObjCConstantStringType = QualType(); 241 242 // void * type 243 VoidPtrTy = getPointerType(VoidTy); 244} 245 246//===----------------------------------------------------------------------===// 247// Type Sizing and Analysis 248//===----------------------------------------------------------------------===// 249 250/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified 251/// scalar floating point type. 252const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const { 253 const BuiltinType *BT = T->getAsBuiltinType(); 254 assert(BT && "Not a floating point type!"); 255 switch (BT->getKind()) { 256 default: assert(0 && "Not a floating point type!"); 257 case BuiltinType::Float: return Target.getFloatFormat(); 258 case BuiltinType::Double: return Target.getDoubleFormat(); 259 case BuiltinType::LongDouble: return Target.getLongDoubleFormat(); 260 } 261} 262 263/// getDeclAlign - Return a conservative estimate of the alignment of the 264/// specified decl. Note that bitfields do not have a valid alignment, so 265/// this method will assert on them. 266unsigned ASTContext::getDeclAlignInBytes(const Decl *D) { 267 // FIXME: If attribute(align) is specified on the decl, round up to it. 268 269 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 270 QualType T = VD->getType(); 271 // Incomplete or function types default to 1. 272 if (T->isIncompleteType() || T->isFunctionType()) 273 return 1; 274 275 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T)) 276 T = cast<ArrayType>(T)->getElementType(); 277 278 return getTypeAlign(T) / Target.getCharWidth(); 279 } 280 281 return 1; 282} 283 284/// getTypeSize - Return the size of the specified type, in bits. This method 285/// does not work on incomplete types. 286std::pair<uint64_t, unsigned> 287ASTContext::getTypeInfo(const Type *T) { 288 T = getCanonicalType(T); 289 uint64_t Width; 290 unsigned Align; 291 switch (T->getTypeClass()) { 292 case Type::TypeName: assert(0 && "Not a canonical type!"); 293 case Type::FunctionNoProto: 294 case Type::FunctionProto: 295 default: 296 assert(0 && "Incomplete types have no size!"); 297 case Type::VariableArray: 298 assert(0 && "VLAs not implemented yet!"); 299 case Type::DependentSizedArray: 300 assert(0 && "Dependently-sized arrays don't have a known size"); 301 case Type::ConstantArray: { 302 const ConstantArrayType *CAT = cast<ConstantArrayType>(T); 303 304 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType()); 305 Width = EltInfo.first*CAT->getSize().getZExtValue(); 306 Align = EltInfo.second; 307 break; 308 } 309 case Type::ExtVector: 310 case Type::Vector: { 311 std::pair<uint64_t, unsigned> EltInfo = 312 getTypeInfo(cast<VectorType>(T)->getElementType()); 313 Width = EltInfo.first*cast<VectorType>(T)->getNumElements(); 314 Align = Width; 315 // If the alignment is not a power of 2, round up to the next power of 2. 316 // This happens for non-power-of-2 length vectors. 317 // FIXME: this should probably be a target property. 318 Align = 1 << llvm::Log2_32_Ceil(Align); 319 break; 320 } 321 322 case Type::Builtin: 323 switch (cast<BuiltinType>(T)->getKind()) { 324 default: assert(0 && "Unknown builtin type!"); 325 case BuiltinType::Void: 326 assert(0 && "Incomplete types have no size!"); 327 case BuiltinType::Bool: 328 Width = Target.getBoolWidth(); 329 Align = Target.getBoolAlign(); 330 break; 331 case BuiltinType::Char_S: 332 case BuiltinType::Char_U: 333 case BuiltinType::UChar: 334 case BuiltinType::SChar: 335 Width = Target.getCharWidth(); 336 Align = Target.getCharAlign(); 337 break; 338 case BuiltinType::WChar: 339 Width = Target.getWCharWidth(); 340 Align = Target.getWCharAlign(); 341 break; 342 case BuiltinType::UShort: 343 case BuiltinType::Short: 344 Width = Target.getShortWidth(); 345 Align = Target.getShortAlign(); 346 break; 347 case BuiltinType::UInt: 348 case BuiltinType::Int: 349 Width = Target.getIntWidth(); 350 Align = Target.getIntAlign(); 351 break; 352 case BuiltinType::ULong: 353 case BuiltinType::Long: 354 Width = Target.getLongWidth(); 355 Align = Target.getLongAlign(); 356 break; 357 case BuiltinType::ULongLong: 358 case BuiltinType::LongLong: 359 Width = Target.getLongLongWidth(); 360 Align = Target.getLongLongAlign(); 361 break; 362 case BuiltinType::Float: 363 Width = Target.getFloatWidth(); 364 Align = Target.getFloatAlign(); 365 break; 366 case BuiltinType::Double: 367 Width = Target.getDoubleWidth(); 368 Align = Target.getDoubleAlign(); 369 break; 370 case BuiltinType::LongDouble: 371 Width = Target.getLongDoubleWidth(); 372 Align = Target.getLongDoubleAlign(); 373 break; 374 } 375 break; 376 case Type::FixedWidthInt: 377 // FIXME: This isn't precisely correct; the width/alignment should depend 378 // on the available types for the target 379 Width = cast<FixedWidthIntType>(T)->getWidth(); 380 Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8); 381 Align = Width; 382 break; 383 case Type::ExtQual: 384 // FIXME: Pointers into different addr spaces could have different sizes and 385 // alignment requirements: getPointerInfo should take an AddrSpace. 386 return getTypeInfo(QualType(cast<ExtQualType>(T)->getBaseType(), 0)); 387 case Type::ObjCQualifiedId: 388 Width = Target.getPointerWidth(0); 389 Align = Target.getPointerAlign(0); 390 break; 391 case Type::BlockPointer: { 392 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace(); 393 Width = Target.getPointerWidth(AS); 394 Align = Target.getPointerAlign(AS); 395 break; 396 } 397 case Type::Pointer: { 398 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace(); 399 Width = Target.getPointerWidth(AS); 400 Align = Target.getPointerAlign(AS); 401 break; 402 } 403 case Type::Reference: 404 // "When applied to a reference or a reference type, the result is the size 405 // of the referenced type." C++98 5.3.3p2: expr.sizeof. 406 // FIXME: This is wrong for struct layout: a reference in a struct has 407 // pointer size. 408 return getTypeInfo(cast<ReferenceType>(T)->getPointeeType()); 409 case Type::MemberPointer: { 410 // FIXME: This is not only platform- but also ABI-dependent. We follow 411 // the GCC ABI, where pointers to data are one pointer large, pointers to 412 // functions two pointers. But if we want to support ABI compatibility with 413 // other compilers too, we need to delegate this completely to TargetInfo 414 // or some ABI abstraction layer. 415 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType(); 416 unsigned AS = Pointee.getAddressSpace(); 417 Width = Target.getPointerWidth(AS); 418 if (Pointee->isFunctionType()) 419 Width *= 2; 420 Align = Target.getPointerAlign(AS); 421 // GCC aligns at single pointer width. 422 } 423 case Type::Complex: { 424 // Complex types have the same alignment as their elements, but twice the 425 // size. 426 std::pair<uint64_t, unsigned> EltInfo = 427 getTypeInfo(cast<ComplexType>(T)->getElementType()); 428 Width = EltInfo.first*2; 429 Align = EltInfo.second; 430 break; 431 } 432 case Type::ObjCInterface: { 433 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T); 434 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 435 Width = Layout.getSize(); 436 Align = Layout.getAlignment(); 437 break; 438 } 439 case Type::Tagged: { 440 const TagType *TT = cast<TagType>(T); 441 442 if (TT->getDecl()->isInvalidDecl()) { 443 Width = 1; 444 Align = 1; 445 break; 446 } 447 448 if (const EnumType *ET = dyn_cast<EnumType>(TT)) 449 return getTypeInfo(ET->getDecl()->getIntegerType()); 450 451 const RecordType *RT = cast<RecordType>(TT); 452 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl()); 453 Width = Layout.getSize(); 454 Align = Layout.getAlignment(); 455 break; 456 } 457 } 458 459 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2"); 460 return std::make_pair(Width, Align); 461} 462 463/// getPreferredTypeAlign - Return the "preferred" alignment of the specified 464/// type for the current target in bits. This can be different than the ABI 465/// alignment in cases where it is beneficial for performance to overalign 466/// a data type. 467unsigned ASTContext::getPreferredTypeAlign(const Type *T) { 468 unsigned ABIAlign = getTypeAlign(T); 469 470 // Doubles should be naturally aligned if possible. 471 if (const BuiltinType *BT = dyn_cast<BuiltinType>(getCanonicalType(T))) 472 if (BT->getKind() == BuiltinType::Double) 473 return std::max(ABIAlign, 64U); 474 475 return ABIAlign; 476} 477 478 479/// LayoutField - Field layout. 480void ASTRecordLayout::LayoutField(const FieldDecl *FD, unsigned FieldNo, 481 bool IsUnion, unsigned StructPacking, 482 ASTContext &Context) { 483 unsigned FieldPacking = StructPacking; 484 uint64_t FieldOffset = IsUnion ? 0 : Size; 485 uint64_t FieldSize; 486 unsigned FieldAlign; 487 488 // FIXME: Should this override struct packing? Probably we want to 489 // take the minimum? 490 if (const PackedAttr *PA = FD->getAttr<PackedAttr>()) 491 FieldPacking = PA->getAlignment(); 492 493 if (const Expr *BitWidthExpr = FD->getBitWidth()) { 494 // TODO: Need to check this algorithm on other targets! 495 // (tested on Linux-X86) 496 FieldSize = 497 BitWidthExpr->getIntegerConstantExprValue(Context).getZExtValue(); 498 499 std::pair<uint64_t, unsigned> FieldInfo = 500 Context.getTypeInfo(FD->getType()); 501 uint64_t TypeSize = FieldInfo.first; 502 503 // Determine the alignment of this bitfield. The packing 504 // attributes define a maximum and the alignment attribute defines 505 // a minimum. 506 // FIXME: What is the right behavior when the specified alignment 507 // is smaller than the specified packing? 508 FieldAlign = FieldInfo.second; 509 if (FieldPacking) 510 FieldAlign = std::min(FieldAlign, FieldPacking); 511 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>()) 512 FieldAlign = std::max(FieldAlign, AA->getAlignment()); 513 514 // Check if we need to add padding to give the field the correct 515 // alignment. 516 if (FieldSize == 0 || (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize) 517 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1); 518 519 // Padding members don't affect overall alignment 520 if (!FD->getIdentifier()) 521 FieldAlign = 1; 522 } else { 523 if (FD->getType()->isIncompleteArrayType()) { 524 // This is a flexible array member; we can't directly 525 // query getTypeInfo about these, so we figure it out here. 526 // Flexible array members don't have any size, but they 527 // have to be aligned appropriately for their element type. 528 FieldSize = 0; 529 const ArrayType* ATy = Context.getAsArrayType(FD->getType()); 530 FieldAlign = Context.getTypeAlign(ATy->getElementType()); 531 } else { 532 std::pair<uint64_t, unsigned> FieldInfo = 533 Context.getTypeInfo(FD->getType()); 534 FieldSize = FieldInfo.first; 535 FieldAlign = FieldInfo.second; 536 } 537 538 // Determine the alignment of this bitfield. The packing 539 // attributes define a maximum and the alignment attribute defines 540 // a minimum. Additionally, the packing alignment must be at least 541 // a byte for non-bitfields. 542 // 543 // FIXME: What is the right behavior when the specified alignment 544 // is smaller than the specified packing? 545 if (FieldPacking) 546 FieldAlign = std::min(FieldAlign, std::max(8U, FieldPacking)); 547 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>()) 548 FieldAlign = std::max(FieldAlign, AA->getAlignment()); 549 550 // Round up the current record size to the field's alignment boundary. 551 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1); 552 } 553 554 // Place this field at the current location. 555 FieldOffsets[FieldNo] = FieldOffset; 556 557 // Reserve space for this field. 558 if (IsUnion) { 559 Size = std::max(Size, FieldSize); 560 } else { 561 Size = FieldOffset + FieldSize; 562 } 563 564 // Remember max struct/class alignment. 565 Alignment = std::max(Alignment, FieldAlign); 566} 567 568static void CollectObjCIvars(const ObjCInterfaceDecl *OI, 569 std::vector<FieldDecl*> &Fields) { 570 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass(); 571 if (SuperClass) 572 CollectObjCIvars(SuperClass, Fields); 573 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(), 574 E = OI->ivar_end(); I != E; ++I) { 575 ObjCIvarDecl *IVDecl = (*I); 576 if (!IVDecl->isInvalidDecl()) 577 Fields.push_back(cast<FieldDecl>(IVDecl)); 578 } 579} 580 581/// addRecordToClass - produces record info. for the class for its 582/// ivars and all those inherited. 583/// 584const RecordDecl *ASTContext::addRecordToClass(const ObjCInterfaceDecl *D) 585{ 586 const RecordDecl *&RD = ASTRecordForInterface[D]; 587 if (RD) 588 return RD; 589 std::vector<FieldDecl*> RecFields; 590 CollectObjCIvars(D, RecFields); 591 RecordDecl *NewRD = RecordDecl::Create(*this, TagDecl::TK_struct, 0, 592 D->getLocation(), 593 D->getIdentifier()); 594 /// FIXME! Can do collection of ivars and adding to the record while 595 /// doing it. 596 for (unsigned int i = 0; i != RecFields.size(); i++) { 597 FieldDecl *Field = FieldDecl::Create(*this, NewRD, 598 RecFields[i]->getLocation(), 599 RecFields[i]->getIdentifier(), 600 RecFields[i]->getType(), 601 RecFields[i]->getBitWidth(), false); 602 NewRD->addDecl(Field); 603 } 604 NewRD->completeDefinition(*this); 605 RD = NewRD; 606 return RD; 607} 608 609/// setFieldDecl - maps a field for the given Ivar reference node. 610// 611void ASTContext::setFieldDecl(const ObjCInterfaceDecl *OI, 612 const ObjCIvarDecl *Ivar, 613 const ObjCIvarRefExpr *MRef) { 614 FieldDecl *FD = (const_cast<ObjCInterfaceDecl *>(OI))-> 615 lookupFieldDeclForIvar(*this, Ivar); 616 ASTFieldForIvarRef[MRef] = FD; 617} 618 619/// getASTObjcInterfaceLayout - Get or compute information about the layout of 620/// the specified Objective C, which indicates its size and ivar 621/// position information. 622const ASTRecordLayout & 623ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) { 624 // Look up this layout, if already laid out, return what we have. 625 const ASTRecordLayout *&Entry = ASTObjCInterfaces[D]; 626 if (Entry) return *Entry; 627 628 // Allocate and assign into ASTRecordLayouts here. The "Entry" reference can 629 // be invalidated (dangle) if the ASTRecordLayouts hashtable is inserted into. 630 ASTRecordLayout *NewEntry = NULL; 631 unsigned FieldCount = D->ivar_size(); 632 if (ObjCInterfaceDecl *SD = D->getSuperClass()) { 633 FieldCount++; 634 const ASTRecordLayout &SL = getASTObjCInterfaceLayout(SD); 635 unsigned Alignment = SL.getAlignment(); 636 uint64_t Size = SL.getSize(); 637 NewEntry = new ASTRecordLayout(Size, Alignment); 638 NewEntry->InitializeLayout(FieldCount); 639 // Super class is at the beginning of the layout. 640 NewEntry->SetFieldOffset(0, 0); 641 } else { 642 NewEntry = new ASTRecordLayout(); 643 NewEntry->InitializeLayout(FieldCount); 644 } 645 Entry = NewEntry; 646 647 unsigned StructPacking = 0; 648 if (const PackedAttr *PA = D->getAttr<PackedAttr>()) 649 StructPacking = PA->getAlignment(); 650 651 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>()) 652 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(), 653 AA->getAlignment())); 654 655 // Layout each ivar sequentially. 656 unsigned i = 0; 657 for (ObjCInterfaceDecl::ivar_iterator IVI = D->ivar_begin(), 658 IVE = D->ivar_end(); IVI != IVE; ++IVI) { 659 const ObjCIvarDecl* Ivar = (*IVI); 660 NewEntry->LayoutField(Ivar, i++, false, StructPacking, *this); 661 } 662 663 // Finally, round the size of the total struct up to the alignment of the 664 // struct itself. 665 NewEntry->FinalizeLayout(); 666 return *NewEntry; 667} 668 669/// getASTRecordLayout - Get or compute information about the layout of the 670/// specified record (struct/union/class), which indicates its size and field 671/// position information. 672const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) { 673 D = D->getDefinition(*this); 674 assert(D && "Cannot get layout of forward declarations!"); 675 676 // Look up this layout, if already laid out, return what we have. 677 const ASTRecordLayout *&Entry = ASTRecordLayouts[D]; 678 if (Entry) return *Entry; 679 680 // Allocate and assign into ASTRecordLayouts here. The "Entry" reference can 681 // be invalidated (dangle) if the ASTRecordLayouts hashtable is inserted into. 682 ASTRecordLayout *NewEntry = new ASTRecordLayout(); 683 Entry = NewEntry; 684 685 // FIXME: Avoid linear walk through the fields, if possible. 686 NewEntry->InitializeLayout(std::distance(D->field_begin(), D->field_end())); 687 bool IsUnion = D->isUnion(); 688 689 unsigned StructPacking = 0; 690 if (const PackedAttr *PA = D->getAttr<PackedAttr>()) 691 StructPacking = PA->getAlignment(); 692 693 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>()) 694 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(), 695 AA->getAlignment())); 696 697 // Layout each field, for now, just sequentially, respecting alignment. In 698 // the future, this will need to be tweakable by targets. 699 unsigned FieldIdx = 0; 700 for (RecordDecl::field_iterator Field = D->field_begin(), 701 FieldEnd = D->field_end(); 702 Field != FieldEnd; (void)++Field, ++FieldIdx) 703 NewEntry->LayoutField(*Field, FieldIdx, IsUnion, StructPacking, *this); 704 705 // Finally, round the size of the total struct up to the alignment of the 706 // struct itself. 707 NewEntry->FinalizeLayout(); 708 return *NewEntry; 709} 710 711//===----------------------------------------------------------------------===// 712// Type creation/memoization methods 713//===----------------------------------------------------------------------===// 714 715QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) { 716 QualType CanT = getCanonicalType(T); 717 if (CanT.getAddressSpace() == AddressSpace) 718 return T; 719 720 // Type's cannot have multiple ExtQuals, therefore we know we only have to deal 721 // with CVR qualifiers from here on out. 722 assert(CanT.getAddressSpace() == 0 && 723 "Type is already address space qualified"); 724 725 // Check if we've already instantiated an address space qual'd type of this 726 // type. 727 llvm::FoldingSetNodeID ID; 728 ExtQualType::Profile(ID, T.getTypePtr(), AddressSpace, ExtQualType::GCNone); 729 void *InsertPos = 0; 730 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos)) 731 return QualType(EXTQy, 0); 732 733 // If the base type isn't canonical, this won't be a canonical type either, 734 // so fill in the canonical type field. 735 QualType Canonical; 736 if (!T->isCanonical()) { 737 Canonical = getAddrSpaceQualType(CanT, AddressSpace); 738 739 // Get the new insert position for the node we care about. 740 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos); 741 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 742 } 743 ExtQualType *New = new (*this, 8) ExtQualType(T.getTypePtr(), Canonical, 744 AddressSpace, ExtQualType::GCNone); 745 ExtQualTypes.InsertNode(New, InsertPos); 746 Types.push_back(New); 747 return QualType(New, T.getCVRQualifiers()); 748} 749 750 751/// getComplexType - Return the uniqued reference to the type for a complex 752/// number with the specified element type. 753QualType ASTContext::getComplexType(QualType T) { 754 // Unique pointers, to guarantee there is only one pointer of a particular 755 // structure. 756 llvm::FoldingSetNodeID ID; 757 ComplexType::Profile(ID, T); 758 759 void *InsertPos = 0; 760 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos)) 761 return QualType(CT, 0); 762 763 // If the pointee type isn't canonical, this won't be a canonical type either, 764 // so fill in the canonical type field. 765 QualType Canonical; 766 if (!T->isCanonical()) { 767 Canonical = getComplexType(getCanonicalType(T)); 768 769 // Get the new insert position for the node we care about. 770 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos); 771 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 772 } 773 ComplexType *New = new (*this,8) ComplexType(T, Canonical); 774 Types.push_back(New); 775 ComplexTypes.InsertNode(New, InsertPos); 776 return QualType(New, 0); 777} 778 779QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) { 780 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ? 781 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes; 782 FixedWidthIntType *&Entry = Map[Width]; 783 if (!Entry) 784 Entry = new FixedWidthIntType(Width, Signed); 785 return QualType(Entry, 0); 786} 787 788/// getPointerType - Return the uniqued reference to the type for a pointer to 789/// the specified type. 790QualType ASTContext::getPointerType(QualType T) { 791 // Unique pointers, to guarantee there is only one pointer of a particular 792 // structure. 793 llvm::FoldingSetNodeID ID; 794 PointerType::Profile(ID, T); 795 796 void *InsertPos = 0; 797 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 798 return QualType(PT, 0); 799 800 // If the pointee type isn't canonical, this won't be a canonical type either, 801 // so fill in the canonical type field. 802 QualType Canonical; 803 if (!T->isCanonical()) { 804 Canonical = getPointerType(getCanonicalType(T)); 805 806 // Get the new insert position for the node we care about. 807 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos); 808 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 809 } 810 PointerType *New = new (*this,8) PointerType(T, Canonical); 811 Types.push_back(New); 812 PointerTypes.InsertNode(New, InsertPos); 813 return QualType(New, 0); 814} 815 816/// getBlockPointerType - Return the uniqued reference to the type for 817/// a pointer to the specified block. 818QualType ASTContext::getBlockPointerType(QualType T) { 819 assert(T->isFunctionType() && "block of function types only"); 820 // Unique pointers, to guarantee there is only one block of a particular 821 // structure. 822 llvm::FoldingSetNodeID ID; 823 BlockPointerType::Profile(ID, T); 824 825 void *InsertPos = 0; 826 if (BlockPointerType *PT = 827 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 828 return QualType(PT, 0); 829 830 // If the block pointee type isn't canonical, this won't be a canonical 831 // type either so fill in the canonical type field. 832 QualType Canonical; 833 if (!T->isCanonical()) { 834 Canonical = getBlockPointerType(getCanonicalType(T)); 835 836 // Get the new insert position for the node we care about. 837 BlockPointerType *NewIP = 838 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 839 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 840 } 841 BlockPointerType *New = new (*this,8) BlockPointerType(T, Canonical); 842 Types.push_back(New); 843 BlockPointerTypes.InsertNode(New, InsertPos); 844 return QualType(New, 0); 845} 846 847/// getReferenceType - Return the uniqued reference to the type for a reference 848/// to the specified type. 849QualType ASTContext::getReferenceType(QualType T) { 850 // Unique pointers, to guarantee there is only one pointer of a particular 851 // structure. 852 llvm::FoldingSetNodeID ID; 853 ReferenceType::Profile(ID, T); 854 855 void *InsertPos = 0; 856 if (ReferenceType *RT = ReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 857 return QualType(RT, 0); 858 859 // If the referencee type isn't canonical, this won't be a canonical type 860 // either, so fill in the canonical type field. 861 QualType Canonical; 862 if (!T->isCanonical()) { 863 Canonical = getReferenceType(getCanonicalType(T)); 864 865 // Get the new insert position for the node we care about. 866 ReferenceType *NewIP = ReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 867 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 868 } 869 870 ReferenceType *New = new (*this,8) ReferenceType(T, Canonical); 871 Types.push_back(New); 872 ReferenceTypes.InsertNode(New, InsertPos); 873 return QualType(New, 0); 874} 875 876/// getMemberPointerType - Return the uniqued reference to the type for a 877/// member pointer to the specified type, in the specified class. 878QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) 879{ 880 // Unique pointers, to guarantee there is only one pointer of a particular 881 // structure. 882 llvm::FoldingSetNodeID ID; 883 MemberPointerType::Profile(ID, T, Cls); 884 885 void *InsertPos = 0; 886 if (MemberPointerType *PT = 887 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 888 return QualType(PT, 0); 889 890 // If the pointee or class type isn't canonical, this won't be a canonical 891 // type either, so fill in the canonical type field. 892 QualType Canonical; 893 if (!T->isCanonical()) { 894 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls)); 895 896 // Get the new insert position for the node we care about. 897 MemberPointerType *NewIP = 898 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 899 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 900 } 901 MemberPointerType *New = new (*this,8) MemberPointerType(T, Cls, Canonical); 902 Types.push_back(New); 903 MemberPointerTypes.InsertNode(New, InsertPos); 904 return QualType(New, 0); 905} 906 907/// getConstantArrayType - Return the unique reference to the type for an 908/// array of the specified element type. 909QualType ASTContext::getConstantArrayType(QualType EltTy, 910 const llvm::APInt &ArySize, 911 ArrayType::ArraySizeModifier ASM, 912 unsigned EltTypeQuals) { 913 llvm::FoldingSetNodeID ID; 914 ConstantArrayType::Profile(ID, EltTy, ArySize); 915 916 void *InsertPos = 0; 917 if (ConstantArrayType *ATP = 918 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 919 return QualType(ATP, 0); 920 921 // If the element type isn't canonical, this won't be a canonical type either, 922 // so fill in the canonical type field. 923 QualType Canonical; 924 if (!EltTy->isCanonical()) { 925 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize, 926 ASM, EltTypeQuals); 927 // Get the new insert position for the node we care about. 928 ConstantArrayType *NewIP = 929 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 930 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 931 } 932 933 ConstantArrayType *New = 934 new(*this,8)ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals); 935 ConstantArrayTypes.InsertNode(New, InsertPos); 936 Types.push_back(New); 937 return QualType(New, 0); 938} 939 940/// getVariableArrayType - Returns a non-unique reference to the type for a 941/// variable array of the specified element type. 942QualType ASTContext::getVariableArrayType(QualType EltTy, Expr *NumElts, 943 ArrayType::ArraySizeModifier ASM, 944 unsigned EltTypeQuals) { 945 // Since we don't unique expressions, it isn't possible to unique VLA's 946 // that have an expression provided for their size. 947 948 VariableArrayType *New = 949 new(*this,8)VariableArrayType(EltTy,QualType(), NumElts, ASM, EltTypeQuals); 950 951 VariableArrayTypes.push_back(New); 952 Types.push_back(New); 953 return QualType(New, 0); 954} 955 956/// getDependentSizedArrayType - Returns a non-unique reference to 957/// the type for a dependently-sized array of the specified element 958/// type. FIXME: We will need these to be uniqued, or at least 959/// comparable, at some point. 960QualType ASTContext::getDependentSizedArrayType(QualType EltTy, Expr *NumElts, 961 ArrayType::ArraySizeModifier ASM, 962 unsigned EltTypeQuals) { 963 assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) && 964 "Size must be type- or value-dependent!"); 965 966 // Since we don't unique expressions, it isn't possible to unique 967 // dependently-sized array types. 968 969 DependentSizedArrayType *New = 970 new (*this,8) DependentSizedArrayType(EltTy, QualType(), NumElts, 971 ASM, EltTypeQuals); 972 973 DependentSizedArrayTypes.push_back(New); 974 Types.push_back(New); 975 return QualType(New, 0); 976} 977 978QualType ASTContext::getIncompleteArrayType(QualType EltTy, 979 ArrayType::ArraySizeModifier ASM, 980 unsigned EltTypeQuals) { 981 llvm::FoldingSetNodeID ID; 982 IncompleteArrayType::Profile(ID, EltTy); 983 984 void *InsertPos = 0; 985 if (IncompleteArrayType *ATP = 986 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 987 return QualType(ATP, 0); 988 989 // If the element type isn't canonical, this won't be a canonical type 990 // either, so fill in the canonical type field. 991 QualType Canonical; 992 993 if (!EltTy->isCanonical()) { 994 Canonical = getIncompleteArrayType(getCanonicalType(EltTy), 995 ASM, EltTypeQuals); 996 997 // Get the new insert position for the node we care about. 998 IncompleteArrayType *NewIP = 999 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 1000 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1001 } 1002 1003 IncompleteArrayType *New = new (*this,8) IncompleteArrayType(EltTy, Canonical, 1004 ASM, EltTypeQuals); 1005 1006 IncompleteArrayTypes.InsertNode(New, InsertPos); 1007 Types.push_back(New); 1008 return QualType(New, 0); 1009} 1010 1011/// getVectorType - Return the unique reference to a vector type of 1012/// the specified element type and size. VectorType must be a built-in type. 1013QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) { 1014 BuiltinType *baseType; 1015 1016 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr()); 1017 assert(baseType != 0 && "getVectorType(): Expecting a built-in type"); 1018 1019 // Check if we've already instantiated a vector of this type. 1020 llvm::FoldingSetNodeID ID; 1021 VectorType::Profile(ID, vecType, NumElts, Type::Vector); 1022 void *InsertPos = 0; 1023 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 1024 return QualType(VTP, 0); 1025 1026 // If the element type isn't canonical, this won't be a canonical type either, 1027 // so fill in the canonical type field. 1028 QualType Canonical; 1029 if (!vecType->isCanonical()) { 1030 Canonical = getVectorType(getCanonicalType(vecType), NumElts); 1031 1032 // Get the new insert position for the node we care about. 1033 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 1034 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1035 } 1036 VectorType *New = new (*this,8) VectorType(vecType, NumElts, Canonical); 1037 VectorTypes.InsertNode(New, InsertPos); 1038 Types.push_back(New); 1039 return QualType(New, 0); 1040} 1041 1042/// getExtVectorType - Return the unique reference to an extended vector type of 1043/// the specified element type and size. VectorType must be a built-in type. 1044QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) { 1045 BuiltinType *baseType; 1046 1047 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr()); 1048 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type"); 1049 1050 // Check if we've already instantiated a vector of this type. 1051 llvm::FoldingSetNodeID ID; 1052 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector); 1053 void *InsertPos = 0; 1054 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 1055 return QualType(VTP, 0); 1056 1057 // If the element type isn't canonical, this won't be a canonical type either, 1058 // so fill in the canonical type field. 1059 QualType Canonical; 1060 if (!vecType->isCanonical()) { 1061 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts); 1062 1063 // Get the new insert position for the node we care about. 1064 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 1065 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1066 } 1067 ExtVectorType *New = new (*this,8) ExtVectorType(vecType, NumElts, Canonical); 1068 VectorTypes.InsertNode(New, InsertPos); 1069 Types.push_back(New); 1070 return QualType(New, 0); 1071} 1072 1073/// getFunctionTypeNoProto - Return a K&R style C function type like 'int()'. 1074/// 1075QualType ASTContext::getFunctionTypeNoProto(QualType ResultTy) { 1076 // Unique functions, to guarantee there is only one function of a particular 1077 // structure. 1078 llvm::FoldingSetNodeID ID; 1079 FunctionTypeNoProto::Profile(ID, ResultTy); 1080 1081 void *InsertPos = 0; 1082 if (FunctionTypeNoProto *FT = 1083 FunctionTypeNoProtos.FindNodeOrInsertPos(ID, InsertPos)) 1084 return QualType(FT, 0); 1085 1086 QualType Canonical; 1087 if (!ResultTy->isCanonical()) { 1088 Canonical = getFunctionTypeNoProto(getCanonicalType(ResultTy)); 1089 1090 // Get the new insert position for the node we care about. 1091 FunctionTypeNoProto *NewIP = 1092 FunctionTypeNoProtos.FindNodeOrInsertPos(ID, InsertPos); 1093 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1094 } 1095 1096 FunctionTypeNoProto *New =new(*this,8)FunctionTypeNoProto(ResultTy,Canonical); 1097 Types.push_back(New); 1098 FunctionTypeNoProtos.InsertNode(New, InsertPos); 1099 return QualType(New, 0); 1100} 1101 1102/// getFunctionType - Return a normal function type with a typed argument 1103/// list. isVariadic indicates whether the argument list includes '...'. 1104QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray, 1105 unsigned NumArgs, bool isVariadic, 1106 unsigned TypeQuals) { 1107 // Unique functions, to guarantee there is only one function of a particular 1108 // structure. 1109 llvm::FoldingSetNodeID ID; 1110 FunctionTypeProto::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic, 1111 TypeQuals); 1112 1113 void *InsertPos = 0; 1114 if (FunctionTypeProto *FTP = 1115 FunctionTypeProtos.FindNodeOrInsertPos(ID, InsertPos)) 1116 return QualType(FTP, 0); 1117 1118 // Determine whether the type being created is already canonical or not. 1119 bool isCanonical = ResultTy->isCanonical(); 1120 for (unsigned i = 0; i != NumArgs && isCanonical; ++i) 1121 if (!ArgArray[i]->isCanonical()) 1122 isCanonical = false; 1123 1124 // If this type isn't canonical, get the canonical version of it. 1125 QualType Canonical; 1126 if (!isCanonical) { 1127 llvm::SmallVector<QualType, 16> CanonicalArgs; 1128 CanonicalArgs.reserve(NumArgs); 1129 for (unsigned i = 0; i != NumArgs; ++i) 1130 CanonicalArgs.push_back(getCanonicalType(ArgArray[i])); 1131 1132 Canonical = getFunctionType(getCanonicalType(ResultTy), 1133 &CanonicalArgs[0], NumArgs, 1134 isVariadic, TypeQuals); 1135 1136 // Get the new insert position for the node we care about. 1137 FunctionTypeProto *NewIP = 1138 FunctionTypeProtos.FindNodeOrInsertPos(ID, InsertPos); 1139 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1140 } 1141 1142 // FunctionTypeProto objects are allocated with extra bytes after them 1143 // for a variable size array (for parameter types) at the end of them. 1144 FunctionTypeProto *FTP = 1145 (FunctionTypeProto*)Allocate(sizeof(FunctionTypeProto) + 1146 NumArgs*sizeof(QualType), 8); 1147 new (FTP) FunctionTypeProto(ResultTy, ArgArray, NumArgs, isVariadic, 1148 TypeQuals, Canonical); 1149 Types.push_back(FTP); 1150 FunctionTypeProtos.InsertNode(FTP, InsertPos); 1151 return QualType(FTP, 0); 1152} 1153 1154/// getTypeDeclType - Return the unique reference to the type for the 1155/// specified type declaration. 1156QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) { 1157 assert(Decl && "Passed null for Decl param"); 1158 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 1159 1160 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl)) 1161 return getTypedefType(Typedef); 1162 else if (isa<TemplateTypeParmDecl>(Decl)) { 1163 assert(false && "Template type parameter types are always available."); 1164 } else if (ObjCInterfaceDecl *ObjCInterface = dyn_cast<ObjCInterfaceDecl>(Decl)) 1165 return getObjCInterfaceType(ObjCInterface); 1166 1167 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Decl)) { 1168 if (PrevDecl) 1169 Decl->TypeForDecl = PrevDecl->TypeForDecl; 1170 else 1171 Decl->TypeForDecl = new (*this,8) CXXRecordType(CXXRecord); 1172 } 1173 else if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) { 1174 if (PrevDecl) 1175 Decl->TypeForDecl = PrevDecl->TypeForDecl; 1176 else 1177 Decl->TypeForDecl = new (*this,8) RecordType(Record); 1178 } 1179 else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) { 1180 if (PrevDecl) 1181 Decl->TypeForDecl = PrevDecl->TypeForDecl; 1182 else 1183 Decl->TypeForDecl = new (*this,8) EnumType(Enum); 1184 } 1185 else 1186 assert(false && "TypeDecl without a type?"); 1187 1188 if (!PrevDecl) Types.push_back(Decl->TypeForDecl); 1189 return QualType(Decl->TypeForDecl, 0); 1190} 1191 1192/// getTypedefType - Return the unique reference to the type for the 1193/// specified typename decl. 1194QualType ASTContext::getTypedefType(TypedefDecl *Decl) { 1195 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 1196 1197 QualType Canonical = getCanonicalType(Decl->getUnderlyingType()); 1198 Decl->TypeForDecl = new(*this,8) TypedefType(Type::TypeName, Decl, Canonical); 1199 Types.push_back(Decl->TypeForDecl); 1200 return QualType(Decl->TypeForDecl, 0); 1201} 1202 1203/// getObjCInterfaceType - Return the unique reference to the type for the 1204/// specified ObjC interface decl. 1205QualType ASTContext::getObjCInterfaceType(ObjCInterfaceDecl *Decl) { 1206 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 1207 1208 Decl->TypeForDecl = new(*this,8) ObjCInterfaceType(Type::ObjCInterface, Decl); 1209 Types.push_back(Decl->TypeForDecl); 1210 return QualType(Decl->TypeForDecl, 0); 1211} 1212 1213/// buildObjCInterfaceType - Returns a new type for the interface 1214/// declaration, regardless. It also removes any previously built 1215/// record declaration so caller can rebuild it. 1216QualType ASTContext::buildObjCInterfaceType(ObjCInterfaceDecl *Decl) { 1217 const RecordDecl *&RD = ASTRecordForInterface[Decl]; 1218 if (RD) 1219 RD = 0; 1220 Decl->TypeForDecl = new(*this,8) ObjCInterfaceType(Type::ObjCInterface, Decl); 1221 Types.push_back(Decl->TypeForDecl); 1222 return QualType(Decl->TypeForDecl, 0); 1223} 1224 1225/// \brief Retrieve the template type parameter type for a template 1226/// parameter with the given depth, index, and (optionally) name. 1227QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index, 1228 IdentifierInfo *Name) { 1229 llvm::FoldingSetNodeID ID; 1230 TemplateTypeParmType::Profile(ID, Depth, Index, Name); 1231 void *InsertPos = 0; 1232 TemplateTypeParmType *TypeParm 1233 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 1234 1235 if (TypeParm) 1236 return QualType(TypeParm, 0); 1237 1238 if (Name) 1239 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, Name, 1240 getTemplateTypeParmType(Depth, Index)); 1241 else 1242 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index); 1243 1244 Types.push_back(TypeParm); 1245 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos); 1246 1247 return QualType(TypeParm, 0); 1248} 1249 1250QualType 1251ASTContext::getClassTemplateSpecializationType(TemplateDecl *Template, 1252 unsigned NumArgs, 1253 uintptr_t *Args, bool *ArgIsType, 1254 QualType Canon) { 1255 llvm::FoldingSetNodeID ID; 1256 ClassTemplateSpecializationType::Profile(ID, Template, NumArgs, Args, 1257 ArgIsType); 1258 void *InsertPos = 0; 1259 ClassTemplateSpecializationType *Spec 1260 = ClassTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 1261 1262 if (Spec) 1263 return QualType(Spec, 0); 1264 1265 void *Mem = Allocate(sizeof(ClassTemplateSpecializationType) + 1266 (sizeof(uintptr_t) * 1267 (ClassTemplateSpecializationType:: 1268 getNumPackedWords(NumArgs) + 1269 NumArgs)), 8); 1270 Spec = new (Mem) ClassTemplateSpecializationType(Template, NumArgs, Args, 1271 ArgIsType, Canon); 1272 Types.push_back(Spec); 1273 ClassTemplateSpecializationTypes.InsertNode(Spec, InsertPos); 1274 1275 return QualType(Spec, 0); 1276} 1277 1278/// CmpProtocolNames - Comparison predicate for sorting protocols 1279/// alphabetically. 1280static bool CmpProtocolNames(const ObjCProtocolDecl *LHS, 1281 const ObjCProtocolDecl *RHS) { 1282 return LHS->getDeclName() < RHS->getDeclName(); 1283} 1284 1285static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols, 1286 unsigned &NumProtocols) { 1287 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols; 1288 1289 // Sort protocols, keyed by name. 1290 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames); 1291 1292 // Remove duplicates. 1293 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd); 1294 NumProtocols = ProtocolsEnd-Protocols; 1295} 1296 1297 1298/// getObjCQualifiedInterfaceType - Return a ObjCQualifiedInterfaceType type for 1299/// the given interface decl and the conforming protocol list. 1300QualType ASTContext::getObjCQualifiedInterfaceType(ObjCInterfaceDecl *Decl, 1301 ObjCProtocolDecl **Protocols, unsigned NumProtocols) { 1302 // Sort the protocol list alphabetically to canonicalize it. 1303 SortAndUniqueProtocols(Protocols, NumProtocols); 1304 1305 llvm::FoldingSetNodeID ID; 1306 ObjCQualifiedInterfaceType::Profile(ID, Decl, Protocols, NumProtocols); 1307 1308 void *InsertPos = 0; 1309 if (ObjCQualifiedInterfaceType *QT = 1310 ObjCQualifiedInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos)) 1311 return QualType(QT, 0); 1312 1313 // No Match; 1314 ObjCQualifiedInterfaceType *QType = 1315 new (*this,8) ObjCQualifiedInterfaceType(Decl, Protocols, NumProtocols); 1316 1317 Types.push_back(QType); 1318 ObjCQualifiedInterfaceTypes.InsertNode(QType, InsertPos); 1319 return QualType(QType, 0); 1320} 1321 1322/// getObjCQualifiedIdType - Return an ObjCQualifiedIdType for the 'id' decl 1323/// and the conforming protocol list. 1324QualType ASTContext::getObjCQualifiedIdType(ObjCProtocolDecl **Protocols, 1325 unsigned NumProtocols) { 1326 // Sort the protocol list alphabetically to canonicalize it. 1327 SortAndUniqueProtocols(Protocols, NumProtocols); 1328 1329 llvm::FoldingSetNodeID ID; 1330 ObjCQualifiedIdType::Profile(ID, Protocols, NumProtocols); 1331 1332 void *InsertPos = 0; 1333 if (ObjCQualifiedIdType *QT = 1334 ObjCQualifiedIdTypes.FindNodeOrInsertPos(ID, InsertPos)) 1335 return QualType(QT, 0); 1336 1337 // No Match; 1338 ObjCQualifiedIdType *QType = 1339 new (*this,8) ObjCQualifiedIdType(Protocols, NumProtocols); 1340 Types.push_back(QType); 1341 ObjCQualifiedIdTypes.InsertNode(QType, InsertPos); 1342 return QualType(QType, 0); 1343} 1344 1345/// getTypeOfExpr - Unlike many "get<Type>" functions, we can't unique 1346/// TypeOfExpr AST's (since expression's are never shared). For example, 1347/// multiple declarations that refer to "typeof(x)" all contain different 1348/// DeclRefExpr's. This doesn't effect the type checker, since it operates 1349/// on canonical type's (which are always unique). 1350QualType ASTContext::getTypeOfExpr(Expr *tofExpr) { 1351 QualType Canonical = getCanonicalType(tofExpr->getType()); 1352 TypeOfExpr *toe = new (*this,8) TypeOfExpr(tofExpr, Canonical); 1353 Types.push_back(toe); 1354 return QualType(toe, 0); 1355} 1356 1357/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique 1358/// TypeOfType AST's. The only motivation to unique these nodes would be 1359/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be 1360/// an issue. This doesn't effect the type checker, since it operates 1361/// on canonical type's (which are always unique). 1362QualType ASTContext::getTypeOfType(QualType tofType) { 1363 QualType Canonical = getCanonicalType(tofType); 1364 TypeOfType *tot = new (*this,8) TypeOfType(tofType, Canonical); 1365 Types.push_back(tot); 1366 return QualType(tot, 0); 1367} 1368 1369/// getTagDeclType - Return the unique reference to the type for the 1370/// specified TagDecl (struct/union/class/enum) decl. 1371QualType ASTContext::getTagDeclType(TagDecl *Decl) { 1372 assert (Decl); 1373 return getTypeDeclType(Decl); 1374} 1375 1376/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result 1377/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and 1378/// needs to agree with the definition in <stddef.h>. 1379QualType ASTContext::getSizeType() const { 1380 return getFromTargetType(Target.getSizeType()); 1381} 1382 1383/// getWCharType - Return the unique type for "wchar_t" (C99 7.17), the 1384/// width of characters in wide strings, The value is target dependent and 1385/// needs to agree with the definition in <stddef.h>. 1386QualType ASTContext::getWCharType() const { 1387 if (LangOpts.CPlusPlus) 1388 return WCharTy; 1389 1390 // FIXME: In C, shouldn't WCharTy just be a typedef of the target's 1391 // wide-character type? 1392 return getFromTargetType(Target.getWCharType()); 1393} 1394 1395/// getSignedWCharType - Return the type of "signed wchar_t". 1396/// Used when in C++, as a GCC extension. 1397QualType ASTContext::getSignedWCharType() const { 1398 // FIXME: derive from "Target" ? 1399 return WCharTy; 1400} 1401 1402/// getUnsignedWCharType - Return the type of "unsigned wchar_t". 1403/// Used when in C++, as a GCC extension. 1404QualType ASTContext::getUnsignedWCharType() const { 1405 // FIXME: derive from "Target" ? 1406 return UnsignedIntTy; 1407} 1408 1409/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?) 1410/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9). 1411QualType ASTContext::getPointerDiffType() const { 1412 return getFromTargetType(Target.getPtrDiffType(0)); 1413} 1414 1415//===----------------------------------------------------------------------===// 1416// Type Operators 1417//===----------------------------------------------------------------------===// 1418 1419/// getCanonicalType - Return the canonical (structural) type corresponding to 1420/// the specified potentially non-canonical type. The non-canonical version 1421/// of a type may have many "decorated" versions of types. Decorators can 1422/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed 1423/// to be free of any of these, allowing two canonical types to be compared 1424/// for exact equality with a simple pointer comparison. 1425QualType ASTContext::getCanonicalType(QualType T) { 1426 QualType CanType = T.getTypePtr()->getCanonicalTypeInternal(); 1427 1428 // If the result has type qualifiers, make sure to canonicalize them as well. 1429 unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers(); 1430 if (TypeQuals == 0) return CanType; 1431 1432 // If the type qualifiers are on an array type, get the canonical type of the 1433 // array with the qualifiers applied to the element type. 1434 ArrayType *AT = dyn_cast<ArrayType>(CanType); 1435 if (!AT) 1436 return CanType.getQualifiedType(TypeQuals); 1437 1438 // Get the canonical version of the element with the extra qualifiers on it. 1439 // This can recursively sink qualifiers through multiple levels of arrays. 1440 QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals); 1441 NewEltTy = getCanonicalType(NewEltTy); 1442 1443 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) 1444 return getConstantArrayType(NewEltTy, CAT->getSize(),CAT->getSizeModifier(), 1445 CAT->getIndexTypeQualifier()); 1446 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) 1447 return getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(), 1448 IAT->getIndexTypeQualifier()); 1449 1450 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT)) 1451 return getDependentSizedArrayType(NewEltTy, DSAT->getSizeExpr(), 1452 DSAT->getSizeModifier(), 1453 DSAT->getIndexTypeQualifier()); 1454 1455 VariableArrayType *VAT = cast<VariableArrayType>(AT); 1456 return getVariableArrayType(NewEltTy, VAT->getSizeExpr(), 1457 VAT->getSizeModifier(), 1458 VAT->getIndexTypeQualifier()); 1459} 1460 1461 1462const ArrayType *ASTContext::getAsArrayType(QualType T) { 1463 // Handle the non-qualified case efficiently. 1464 if (T.getCVRQualifiers() == 0) { 1465 // Handle the common positive case fast. 1466 if (const ArrayType *AT = dyn_cast<ArrayType>(T)) 1467 return AT; 1468 } 1469 1470 // Handle the common negative case fast, ignoring CVR qualifiers. 1471 QualType CType = T->getCanonicalTypeInternal(); 1472 1473 // Make sure to look through type qualifiers (like ExtQuals) for the negative 1474 // test. 1475 if (!isa<ArrayType>(CType) && 1476 !isa<ArrayType>(CType.getUnqualifiedType())) 1477 return 0; 1478 1479 // Apply any CVR qualifiers from the array type to the element type. This 1480 // implements C99 6.7.3p8: "If the specification of an array type includes 1481 // any type qualifiers, the element type is so qualified, not the array type." 1482 1483 // If we get here, we either have type qualifiers on the type, or we have 1484 // sugar such as a typedef in the way. If we have type qualifiers on the type 1485 // we must propagate them down into the elemeng type. 1486 unsigned CVRQuals = T.getCVRQualifiers(); 1487 unsigned AddrSpace = 0; 1488 Type *Ty = T.getTypePtr(); 1489 1490 // Rip through ExtQualType's and typedefs to get to a concrete type. 1491 while (1) { 1492 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty)) { 1493 AddrSpace = EXTQT->getAddressSpace(); 1494 Ty = EXTQT->getBaseType(); 1495 } else { 1496 T = Ty->getDesugaredType(); 1497 if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0) 1498 break; 1499 CVRQuals |= T.getCVRQualifiers(); 1500 Ty = T.getTypePtr(); 1501 } 1502 } 1503 1504 // If we have a simple case, just return now. 1505 const ArrayType *ATy = dyn_cast<ArrayType>(Ty); 1506 if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0)) 1507 return ATy; 1508 1509 // Otherwise, we have an array and we have qualifiers on it. Push the 1510 // qualifiers into the array element type and return a new array type. 1511 // Get the canonical version of the element with the extra qualifiers on it. 1512 // This can recursively sink qualifiers through multiple levels of arrays. 1513 QualType NewEltTy = ATy->getElementType(); 1514 if (AddrSpace) 1515 NewEltTy = getAddrSpaceQualType(NewEltTy, AddrSpace); 1516 NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals); 1517 1518 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy)) 1519 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(), 1520 CAT->getSizeModifier(), 1521 CAT->getIndexTypeQualifier())); 1522 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy)) 1523 return cast<ArrayType>(getIncompleteArrayType(NewEltTy, 1524 IAT->getSizeModifier(), 1525 IAT->getIndexTypeQualifier())); 1526 1527 if (const DependentSizedArrayType *DSAT 1528 = dyn_cast<DependentSizedArrayType>(ATy)) 1529 return cast<ArrayType>( 1530 getDependentSizedArrayType(NewEltTy, 1531 DSAT->getSizeExpr(), 1532 DSAT->getSizeModifier(), 1533 DSAT->getIndexTypeQualifier())); 1534 1535 const VariableArrayType *VAT = cast<VariableArrayType>(ATy); 1536 return cast<ArrayType>(getVariableArrayType(NewEltTy, VAT->getSizeExpr(), 1537 VAT->getSizeModifier(), 1538 VAT->getIndexTypeQualifier())); 1539} 1540 1541 1542/// getArrayDecayedType - Return the properly qualified result of decaying the 1543/// specified array type to a pointer. This operation is non-trivial when 1544/// handling typedefs etc. The canonical type of "T" must be an array type, 1545/// this returns a pointer to a properly qualified element of the array. 1546/// 1547/// See C99 6.7.5.3p7 and C99 6.3.2.1p3. 1548QualType ASTContext::getArrayDecayedType(QualType Ty) { 1549 // Get the element type with 'getAsArrayType' so that we don't lose any 1550 // typedefs in the element type of the array. This also handles propagation 1551 // of type qualifiers from the array type into the element type if present 1552 // (C99 6.7.3p8). 1553 const ArrayType *PrettyArrayType = getAsArrayType(Ty); 1554 assert(PrettyArrayType && "Not an array type!"); 1555 1556 QualType PtrTy = getPointerType(PrettyArrayType->getElementType()); 1557 1558 // int x[restrict 4] -> int *restrict 1559 return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier()); 1560} 1561 1562QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) { 1563 QualType ElemTy = VAT->getElementType(); 1564 1565 if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy)) 1566 return getBaseElementType(VAT); 1567 1568 return ElemTy; 1569} 1570 1571/// getFloatingRank - Return a relative rank for floating point types. 1572/// This routine will assert if passed a built-in type that isn't a float. 1573static FloatingRank getFloatingRank(QualType T) { 1574 if (const ComplexType *CT = T->getAsComplexType()) 1575 return getFloatingRank(CT->getElementType()); 1576 1577 assert(T->getAsBuiltinType() && "getFloatingRank(): not a floating type"); 1578 switch (T->getAsBuiltinType()->getKind()) { 1579 default: assert(0 && "getFloatingRank(): not a floating type"); 1580 case BuiltinType::Float: return FloatRank; 1581 case BuiltinType::Double: return DoubleRank; 1582 case BuiltinType::LongDouble: return LongDoubleRank; 1583 } 1584} 1585 1586/// getFloatingTypeOfSizeWithinDomain - Returns a real floating 1587/// point or a complex type (based on typeDomain/typeSize). 1588/// 'typeDomain' is a real floating point or complex type. 1589/// 'typeSize' is a real floating point or complex type. 1590QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size, 1591 QualType Domain) const { 1592 FloatingRank EltRank = getFloatingRank(Size); 1593 if (Domain->isComplexType()) { 1594 switch (EltRank) { 1595 default: assert(0 && "getFloatingRank(): illegal value for rank"); 1596 case FloatRank: return FloatComplexTy; 1597 case DoubleRank: return DoubleComplexTy; 1598 case LongDoubleRank: return LongDoubleComplexTy; 1599 } 1600 } 1601 1602 assert(Domain->isRealFloatingType() && "Unknown domain!"); 1603 switch (EltRank) { 1604 default: assert(0 && "getFloatingRank(): illegal value for rank"); 1605 case FloatRank: return FloatTy; 1606 case DoubleRank: return DoubleTy; 1607 case LongDoubleRank: return LongDoubleTy; 1608 } 1609} 1610 1611/// getFloatingTypeOrder - Compare the rank of the two specified floating 1612/// point types, ignoring the domain of the type (i.e. 'double' == 1613/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If 1614/// LHS < RHS, return -1. 1615int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) { 1616 FloatingRank LHSR = getFloatingRank(LHS); 1617 FloatingRank RHSR = getFloatingRank(RHS); 1618 1619 if (LHSR == RHSR) 1620 return 0; 1621 if (LHSR > RHSR) 1622 return 1; 1623 return -1; 1624} 1625 1626/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This 1627/// routine will assert if passed a built-in type that isn't an integer or enum, 1628/// or if it is not canonicalized. 1629unsigned ASTContext::getIntegerRank(Type *T) { 1630 assert(T->isCanonical() && "T should be canonicalized"); 1631 if (EnumType* ET = dyn_cast<EnumType>(T)) 1632 T = ET->getDecl()->getIntegerType().getTypePtr(); 1633 1634 // There are two things which impact the integer rank: the width, and 1635 // the ordering of builtins. The builtin ordering is encoded in the 1636 // bottom three bits; the width is encoded in the bits above that. 1637 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) { 1638 return FWIT->getWidth() << 3; 1639 } 1640 1641 switch (cast<BuiltinType>(T)->getKind()) { 1642 default: assert(0 && "getIntegerRank(): not a built-in integer"); 1643 case BuiltinType::Bool: 1644 return 1 + (getIntWidth(BoolTy) << 3); 1645 case BuiltinType::Char_S: 1646 case BuiltinType::Char_U: 1647 case BuiltinType::SChar: 1648 case BuiltinType::UChar: 1649 return 2 + (getIntWidth(CharTy) << 3); 1650 case BuiltinType::Short: 1651 case BuiltinType::UShort: 1652 return 3 + (getIntWidth(ShortTy) << 3); 1653 case BuiltinType::Int: 1654 case BuiltinType::UInt: 1655 return 4 + (getIntWidth(IntTy) << 3); 1656 case BuiltinType::Long: 1657 case BuiltinType::ULong: 1658 return 5 + (getIntWidth(LongTy) << 3); 1659 case BuiltinType::LongLong: 1660 case BuiltinType::ULongLong: 1661 return 6 + (getIntWidth(LongLongTy) << 3); 1662 } 1663} 1664 1665/// getIntegerTypeOrder - Returns the highest ranked integer type: 1666/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If 1667/// LHS < RHS, return -1. 1668int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) { 1669 Type *LHSC = getCanonicalType(LHS).getTypePtr(); 1670 Type *RHSC = getCanonicalType(RHS).getTypePtr(); 1671 if (LHSC == RHSC) return 0; 1672 1673 bool LHSUnsigned = LHSC->isUnsignedIntegerType(); 1674 bool RHSUnsigned = RHSC->isUnsignedIntegerType(); 1675 1676 unsigned LHSRank = getIntegerRank(LHSC); 1677 unsigned RHSRank = getIntegerRank(RHSC); 1678 1679 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned. 1680 if (LHSRank == RHSRank) return 0; 1681 return LHSRank > RHSRank ? 1 : -1; 1682 } 1683 1684 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa. 1685 if (LHSUnsigned) { 1686 // If the unsigned [LHS] type is larger, return it. 1687 if (LHSRank >= RHSRank) 1688 return 1; 1689 1690 // If the signed type can represent all values of the unsigned type, it 1691 // wins. Because we are dealing with 2's complement and types that are 1692 // powers of two larger than each other, this is always safe. 1693 return -1; 1694 } 1695 1696 // If the unsigned [RHS] type is larger, return it. 1697 if (RHSRank >= LHSRank) 1698 return -1; 1699 1700 // If the signed type can represent all values of the unsigned type, it 1701 // wins. Because we are dealing with 2's complement and types that are 1702 // powers of two larger than each other, this is always safe. 1703 return 1; 1704} 1705 1706// getCFConstantStringType - Return the type used for constant CFStrings. 1707QualType ASTContext::getCFConstantStringType() { 1708 if (!CFConstantStringTypeDecl) { 1709 CFConstantStringTypeDecl = 1710 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(), 1711 &Idents.get("NSConstantString")); 1712 QualType FieldTypes[4]; 1713 1714 // const int *isa; 1715 FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const)); 1716 // int flags; 1717 FieldTypes[1] = IntTy; 1718 // const char *str; 1719 FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const)); 1720 // long length; 1721 FieldTypes[3] = LongTy; 1722 1723 // Create fields 1724 for (unsigned i = 0; i < 4; ++i) { 1725 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl, 1726 SourceLocation(), 0, 1727 FieldTypes[i], /*BitWidth=*/0, 1728 /*Mutable=*/false); 1729 CFConstantStringTypeDecl->addDecl(Field); 1730 } 1731 1732 CFConstantStringTypeDecl->completeDefinition(*this); 1733 } 1734 1735 return getTagDeclType(CFConstantStringTypeDecl); 1736} 1737 1738QualType ASTContext::getObjCFastEnumerationStateType() 1739{ 1740 if (!ObjCFastEnumerationStateTypeDecl) { 1741 ObjCFastEnumerationStateTypeDecl = 1742 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(), 1743 &Idents.get("__objcFastEnumerationState")); 1744 1745 QualType FieldTypes[] = { 1746 UnsignedLongTy, 1747 getPointerType(ObjCIdType), 1748 getPointerType(UnsignedLongTy), 1749 getConstantArrayType(UnsignedLongTy, 1750 llvm::APInt(32, 5), ArrayType::Normal, 0) 1751 }; 1752 1753 for (size_t i = 0; i < 4; ++i) { 1754 FieldDecl *Field = FieldDecl::Create(*this, 1755 ObjCFastEnumerationStateTypeDecl, 1756 SourceLocation(), 0, 1757 FieldTypes[i], /*BitWidth=*/0, 1758 /*Mutable=*/false); 1759 ObjCFastEnumerationStateTypeDecl->addDecl(Field); 1760 } 1761 1762 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this); 1763 } 1764 1765 return getTagDeclType(ObjCFastEnumerationStateTypeDecl); 1766} 1767 1768// This returns true if a type has been typedefed to BOOL: 1769// typedef <type> BOOL; 1770static bool isTypeTypedefedAsBOOL(QualType T) { 1771 if (const TypedefType *TT = dyn_cast<TypedefType>(T)) 1772 if (IdentifierInfo *II = TT->getDecl()->getIdentifier()) 1773 return II->isStr("BOOL"); 1774 1775 return false; 1776} 1777 1778/// getObjCEncodingTypeSize returns size of type for objective-c encoding 1779/// purpose. 1780int ASTContext::getObjCEncodingTypeSize(QualType type) { 1781 uint64_t sz = getTypeSize(type); 1782 1783 // Make all integer and enum types at least as large as an int 1784 if (sz > 0 && type->isIntegralType()) 1785 sz = std::max(sz, getTypeSize(IntTy)); 1786 // Treat arrays as pointers, since that's how they're passed in. 1787 else if (type->isArrayType()) 1788 sz = getTypeSize(VoidPtrTy); 1789 return sz / getTypeSize(CharTy); 1790} 1791 1792/// getObjCEncodingForMethodDecl - Return the encoded type for this method 1793/// declaration. 1794void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, 1795 std::string& S) { 1796 // FIXME: This is not very efficient. 1797 // Encode type qualifer, 'in', 'inout', etc. for the return type. 1798 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S); 1799 // Encode result type. 1800 getObjCEncodingForType(Decl->getResultType(), S); 1801 // Compute size of all parameters. 1802 // Start with computing size of a pointer in number of bytes. 1803 // FIXME: There might(should) be a better way of doing this computation! 1804 SourceLocation Loc; 1805 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy); 1806 // The first two arguments (self and _cmd) are pointers; account for 1807 // their size. 1808 int ParmOffset = 2 * PtrSize; 1809 int NumOfParams = Decl->getNumParams(); 1810 for (int i = 0; i < NumOfParams; i++) { 1811 QualType PType = Decl->getParamDecl(i)->getType(); 1812 int sz = getObjCEncodingTypeSize (PType); 1813 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type"); 1814 ParmOffset += sz; 1815 } 1816 S += llvm::utostr(ParmOffset); 1817 S += "@0:"; 1818 S += llvm::utostr(PtrSize); 1819 1820 // Argument types. 1821 ParmOffset = 2 * PtrSize; 1822 for (int i = 0; i < NumOfParams; i++) { 1823 ParmVarDecl *PVDecl = Decl->getParamDecl(i); 1824 QualType PType = PVDecl->getOriginalType(); 1825 if (const ArrayType *AT = 1826 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) 1827 // Use array's original type only if it has known number of 1828 // elements. 1829 if (!dyn_cast<ConstantArrayType>(AT)) 1830 PType = PVDecl->getType(); 1831 // Process argument qualifiers for user supplied arguments; such as, 1832 // 'in', 'inout', etc. 1833 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S); 1834 getObjCEncodingForType(PType, S); 1835 S += llvm::utostr(ParmOffset); 1836 ParmOffset += getObjCEncodingTypeSize(PType); 1837 } 1838} 1839 1840/// getObjCEncodingForPropertyDecl - Return the encoded type for this 1841/// property declaration. If non-NULL, Container must be either an 1842/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be 1843/// NULL when getting encodings for protocol properties. 1844/// Property attributes are stored as a comma-delimited C string. The simple 1845/// attributes readonly and bycopy are encoded as single characters. The 1846/// parametrized attributes, getter=name, setter=name, and ivar=name, are 1847/// encoded as single characters, followed by an identifier. Property types 1848/// are also encoded as a parametrized attribute. The characters used to encode 1849/// these attributes are defined by the following enumeration: 1850/// @code 1851/// enum PropertyAttributes { 1852/// kPropertyReadOnly = 'R', // property is read-only. 1853/// kPropertyBycopy = 'C', // property is a copy of the value last assigned 1854/// kPropertyByref = '&', // property is a reference to the value last assigned 1855/// kPropertyDynamic = 'D', // property is dynamic 1856/// kPropertyGetter = 'G', // followed by getter selector name 1857/// kPropertySetter = 'S', // followed by setter selector name 1858/// kPropertyInstanceVariable = 'V' // followed by instance variable name 1859/// kPropertyType = 't' // followed by old-style type encoding. 1860/// kPropertyWeak = 'W' // 'weak' property 1861/// kPropertyStrong = 'P' // property GC'able 1862/// kPropertyNonAtomic = 'N' // property non-atomic 1863/// }; 1864/// @endcode 1865void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, 1866 const Decl *Container, 1867 std::string& S) { 1868 // Collect information from the property implementation decl(s). 1869 bool Dynamic = false; 1870 ObjCPropertyImplDecl *SynthesizePID = 0; 1871 1872 // FIXME: Duplicated code due to poor abstraction. 1873 if (Container) { 1874 if (const ObjCCategoryImplDecl *CID = 1875 dyn_cast<ObjCCategoryImplDecl>(Container)) { 1876 for (ObjCCategoryImplDecl::propimpl_iterator 1877 i = CID->propimpl_begin(), e = CID->propimpl_end(); i != e; ++i) { 1878 ObjCPropertyImplDecl *PID = *i; 1879 if (PID->getPropertyDecl() == PD) { 1880 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) { 1881 Dynamic = true; 1882 } else { 1883 SynthesizePID = PID; 1884 } 1885 } 1886 } 1887 } else { 1888 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container); 1889 for (ObjCCategoryImplDecl::propimpl_iterator 1890 i = OID->propimpl_begin(), e = OID->propimpl_end(); i != e; ++i) { 1891 ObjCPropertyImplDecl *PID = *i; 1892 if (PID->getPropertyDecl() == PD) { 1893 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) { 1894 Dynamic = true; 1895 } else { 1896 SynthesizePID = PID; 1897 } 1898 } 1899 } 1900 } 1901 } 1902 1903 // FIXME: This is not very efficient. 1904 S = "T"; 1905 1906 // Encode result type. 1907 // GCC has some special rules regarding encoding of properties which 1908 // closely resembles encoding of ivars. 1909 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, NULL, 1910 true /* outermost type */, 1911 true /* encoding for property */); 1912 1913 if (PD->isReadOnly()) { 1914 S += ",R"; 1915 } else { 1916 switch (PD->getSetterKind()) { 1917 case ObjCPropertyDecl::Assign: break; 1918 case ObjCPropertyDecl::Copy: S += ",C"; break; 1919 case ObjCPropertyDecl::Retain: S += ",&"; break; 1920 } 1921 } 1922 1923 // It really isn't clear at all what this means, since properties 1924 // are "dynamic by default". 1925 if (Dynamic) 1926 S += ",D"; 1927 1928 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic) 1929 S += ",N"; 1930 1931 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) { 1932 S += ",G"; 1933 S += PD->getGetterName().getAsString(); 1934 } 1935 1936 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) { 1937 S += ",S"; 1938 S += PD->getSetterName().getAsString(); 1939 } 1940 1941 if (SynthesizePID) { 1942 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl(); 1943 S += ",V"; 1944 S += OID->getNameAsString(); 1945 } 1946 1947 // FIXME: OBJCGC: weak & strong 1948} 1949 1950/// getLegacyIntegralTypeEncoding - 1951/// Another legacy compatibility encoding: 32-bit longs are encoded as 1952/// 'l' or 'L' , but not always. For typedefs, we need to use 1953/// 'i' or 'I' instead if encoding a struct field, or a pointer! 1954/// 1955void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const { 1956 if (dyn_cast<TypedefType>(PointeeTy.getTypePtr())) { 1957 if (const BuiltinType *BT = PointeeTy->getAsBuiltinType()) { 1958 if (BT->getKind() == BuiltinType::ULong && 1959 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32)) 1960 PointeeTy = UnsignedIntTy; 1961 else 1962 if (BT->getKind() == BuiltinType::Long && 1963 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32)) 1964 PointeeTy = IntTy; 1965 } 1966 } 1967} 1968 1969void ASTContext::getObjCEncodingForType(QualType T, std::string& S, 1970 FieldDecl *Field) const { 1971 // We follow the behavior of gcc, expanding structures which are 1972 // directly pointed to, and expanding embedded structures. Note that 1973 // these rules are sufficient to prevent recursive encoding of the 1974 // same type. 1975 getObjCEncodingForTypeImpl(T, S, true, true, Field, 1976 true /* outermost type */); 1977} 1978 1979static void EncodeBitField(const ASTContext *Context, std::string& S, 1980 FieldDecl *FD) { 1981 const Expr *E = FD->getBitWidth(); 1982 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl"); 1983 ASTContext *Ctx = const_cast<ASTContext*>(Context); 1984 unsigned N = E->getIntegerConstantExprValue(*Ctx).getZExtValue(); 1985 S += 'b'; 1986 S += llvm::utostr(N); 1987} 1988 1989void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, 1990 bool ExpandPointedToStructures, 1991 bool ExpandStructures, 1992 FieldDecl *FD, 1993 bool OutermostType, 1994 bool EncodingProperty) const { 1995 if (const BuiltinType *BT = T->getAsBuiltinType()) { 1996 if (FD && FD->isBitField()) { 1997 EncodeBitField(this, S, FD); 1998 } 1999 else { 2000 char encoding; 2001 switch (BT->getKind()) { 2002 default: assert(0 && "Unhandled builtin type kind"); 2003 case BuiltinType::Void: encoding = 'v'; break; 2004 case BuiltinType::Bool: encoding = 'B'; break; 2005 case BuiltinType::Char_U: 2006 case BuiltinType::UChar: encoding = 'C'; break; 2007 case BuiltinType::UShort: encoding = 'S'; break; 2008 case BuiltinType::UInt: encoding = 'I'; break; 2009 case BuiltinType::ULong: 2010 encoding = 2011 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q'; 2012 break; 2013 case BuiltinType::ULongLong: encoding = 'Q'; break; 2014 case BuiltinType::Char_S: 2015 case BuiltinType::SChar: encoding = 'c'; break; 2016 case BuiltinType::Short: encoding = 's'; break; 2017 case BuiltinType::Int: encoding = 'i'; break; 2018 case BuiltinType::Long: 2019 encoding = 2020 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q'; 2021 break; 2022 case BuiltinType::LongLong: encoding = 'q'; break; 2023 case BuiltinType::Float: encoding = 'f'; break; 2024 case BuiltinType::Double: encoding = 'd'; break; 2025 case BuiltinType::LongDouble: encoding = 'd'; break; 2026 } 2027 2028 S += encoding; 2029 } 2030 } 2031 else if (T->isObjCQualifiedIdType()) { 2032 getObjCEncodingForTypeImpl(getObjCIdType(), S, 2033 ExpandPointedToStructures, 2034 ExpandStructures, FD); 2035 if (FD || EncodingProperty) { 2036 // Note that we do extended encoding of protocol qualifer list 2037 // Only when doing ivar or property encoding. 2038 const ObjCQualifiedIdType *QIDT = T->getAsObjCQualifiedIdType(); 2039 S += '"'; 2040 for (unsigned i =0; i < QIDT->getNumProtocols(); i++) { 2041 ObjCProtocolDecl *Proto = QIDT->getProtocols(i); 2042 S += '<'; 2043 S += Proto->getNameAsString(); 2044 S += '>'; 2045 } 2046 S += '"'; 2047 } 2048 return; 2049 } 2050 else if (const PointerType *PT = T->getAsPointerType()) { 2051 QualType PointeeTy = PT->getPointeeType(); 2052 bool isReadOnly = false; 2053 // For historical/compatibility reasons, the read-only qualifier of the 2054 // pointee gets emitted _before_ the '^'. The read-only qualifier of 2055 // the pointer itself gets ignored, _unless_ we are looking at a typedef! 2056 // Also, do not emit the 'r' for anything but the outermost type! 2057 if (dyn_cast<TypedefType>(T.getTypePtr())) { 2058 if (OutermostType && T.isConstQualified()) { 2059 isReadOnly = true; 2060 S += 'r'; 2061 } 2062 } 2063 else if (OutermostType) { 2064 QualType P = PointeeTy; 2065 while (P->getAsPointerType()) 2066 P = P->getAsPointerType()->getPointeeType(); 2067 if (P.isConstQualified()) { 2068 isReadOnly = true; 2069 S += 'r'; 2070 } 2071 } 2072 if (isReadOnly) { 2073 // Another legacy compatibility encoding. Some ObjC qualifier and type 2074 // combinations need to be rearranged. 2075 // Rewrite "in const" from "nr" to "rn" 2076 const char * s = S.c_str(); 2077 int len = S.length(); 2078 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') { 2079 std::string replace = "rn"; 2080 S.replace(S.end()-2, S.end(), replace); 2081 } 2082 } 2083 if (isObjCIdStructType(PointeeTy)) { 2084 S += '@'; 2085 return; 2086 } 2087 else if (PointeeTy->isObjCInterfaceType()) { 2088 if (!EncodingProperty && 2089 isa<TypedefType>(PointeeTy.getTypePtr())) { 2090 // Another historical/compatibility reason. 2091 // We encode the underlying type which comes out as 2092 // {...}; 2093 S += '^'; 2094 getObjCEncodingForTypeImpl(PointeeTy, S, 2095 false, ExpandPointedToStructures, 2096 NULL); 2097 return; 2098 } 2099 S += '@'; 2100 if (FD || EncodingProperty) { 2101 const ObjCInterfaceType *OIT = PointeeTy->getAsObjCInterfaceType(); 2102 ObjCInterfaceDecl *OI = OIT->getDecl(); 2103 S += '"'; 2104 S += OI->getNameAsCString(); 2105 for (unsigned i =0; i < OIT->getNumProtocols(); i++) { 2106 ObjCProtocolDecl *Proto = OIT->getProtocol(i); 2107 S += '<'; 2108 S += Proto->getNameAsString(); 2109 S += '>'; 2110 } 2111 S += '"'; 2112 } 2113 return; 2114 } else if (isObjCClassStructType(PointeeTy)) { 2115 S += '#'; 2116 return; 2117 } else if (isObjCSelType(PointeeTy)) { 2118 S += ':'; 2119 return; 2120 } 2121 2122 if (PointeeTy->isCharType()) { 2123 // char pointer types should be encoded as '*' unless it is a 2124 // type that has been typedef'd to 'BOOL'. 2125 if (!isTypeTypedefedAsBOOL(PointeeTy)) { 2126 S += '*'; 2127 return; 2128 } 2129 } 2130 2131 S += '^'; 2132 getLegacyIntegralTypeEncoding(PointeeTy); 2133 2134 getObjCEncodingForTypeImpl(PointeeTy, S, 2135 false, ExpandPointedToStructures, 2136 NULL); 2137 } else if (const ArrayType *AT = 2138 // Ignore type qualifiers etc. 2139 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) { 2140 S += '['; 2141 2142 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) 2143 S += llvm::utostr(CAT->getSize().getZExtValue()); 2144 else 2145 assert(0 && "Unhandled array type!"); 2146 2147 getObjCEncodingForTypeImpl(AT->getElementType(), S, 2148 false, ExpandStructures, FD); 2149 S += ']'; 2150 } else if (T->getAsFunctionType()) { 2151 S += '?'; 2152 } else if (const RecordType *RTy = T->getAsRecordType()) { 2153 RecordDecl *RDecl = RTy->getDecl(); 2154 S += RDecl->isUnion() ? '(' : '{'; 2155 // Anonymous structures print as '?' 2156 if (const IdentifierInfo *II = RDecl->getIdentifier()) { 2157 S += II->getName(); 2158 } else { 2159 S += '?'; 2160 } 2161 if (ExpandStructures) { 2162 S += '='; 2163 for (RecordDecl::field_iterator Field = RDecl->field_begin(), 2164 FieldEnd = RDecl->field_end(); 2165 Field != FieldEnd; ++Field) { 2166 if (FD) { 2167 S += '"'; 2168 S += Field->getNameAsString(); 2169 S += '"'; 2170 } 2171 2172 // Special case bit-fields. 2173 if (Field->isBitField()) { 2174 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, 2175 (*Field)); 2176 } else { 2177 QualType qt = Field->getType(); 2178 getLegacyIntegralTypeEncoding(qt); 2179 getObjCEncodingForTypeImpl(qt, S, false, true, 2180 FD); 2181 } 2182 } 2183 } 2184 S += RDecl->isUnion() ? ')' : '}'; 2185 } else if (T->isEnumeralType()) { 2186 if (FD && FD->isBitField()) 2187 EncodeBitField(this, S, FD); 2188 else 2189 S += 'i'; 2190 } else if (T->isBlockPointerType()) { 2191 S += "@?"; // Unlike a pointer-to-function, which is "^?". 2192 } else if (T->isObjCInterfaceType()) { 2193 // @encode(class_name) 2194 ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl(); 2195 S += '{'; 2196 const IdentifierInfo *II = OI->getIdentifier(); 2197 S += II->getName(); 2198 S += '='; 2199 std::vector<FieldDecl*> RecFields; 2200 CollectObjCIvars(OI, RecFields); 2201 for (unsigned int i = 0; i != RecFields.size(); i++) { 2202 if (RecFields[i]->isBitField()) 2203 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true, 2204 RecFields[i]); 2205 else 2206 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true, 2207 FD); 2208 } 2209 S += '}'; 2210 } 2211 else 2212 assert(0 && "@encode for type not implemented!"); 2213} 2214 2215void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, 2216 std::string& S) const { 2217 if (QT & Decl::OBJC_TQ_In) 2218 S += 'n'; 2219 if (QT & Decl::OBJC_TQ_Inout) 2220 S += 'N'; 2221 if (QT & Decl::OBJC_TQ_Out) 2222 S += 'o'; 2223 if (QT & Decl::OBJC_TQ_Bycopy) 2224 S += 'O'; 2225 if (QT & Decl::OBJC_TQ_Byref) 2226 S += 'R'; 2227 if (QT & Decl::OBJC_TQ_Oneway) 2228 S += 'V'; 2229} 2230 2231void ASTContext::setBuiltinVaListType(QualType T) 2232{ 2233 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!"); 2234 2235 BuiltinVaListType = T; 2236} 2237 2238void ASTContext::setObjCIdType(TypedefDecl *TD) 2239{ 2240 ObjCIdType = getTypedefType(TD); 2241 2242 // typedef struct objc_object *id; 2243 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType(); 2244 // User error - caller will issue diagnostics. 2245 if (!ptr) 2246 return; 2247 const RecordType *rec = ptr->getPointeeType()->getAsStructureType(); 2248 // User error - caller will issue diagnostics. 2249 if (!rec) 2250 return; 2251 IdStructType = rec; 2252} 2253 2254void ASTContext::setObjCSelType(TypedefDecl *TD) 2255{ 2256 ObjCSelType = getTypedefType(TD); 2257 2258 // typedef struct objc_selector *SEL; 2259 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType(); 2260 if (!ptr) 2261 return; 2262 const RecordType *rec = ptr->getPointeeType()->getAsStructureType(); 2263 if (!rec) 2264 return; 2265 SelStructType = rec; 2266} 2267 2268void ASTContext::setObjCProtoType(QualType QT) 2269{ 2270 ObjCProtoType = QT; 2271} 2272 2273void ASTContext::setObjCClassType(TypedefDecl *TD) 2274{ 2275 ObjCClassType = getTypedefType(TD); 2276 2277 // typedef struct objc_class *Class; 2278 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType(); 2279 assert(ptr && "'Class' incorrectly typed"); 2280 const RecordType *rec = ptr->getPointeeType()->getAsStructureType(); 2281 assert(rec && "'Class' incorrectly typed"); 2282 ClassStructType = rec; 2283} 2284 2285void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) { 2286 assert(ObjCConstantStringType.isNull() && 2287 "'NSConstantString' type already set!"); 2288 2289 ObjCConstantStringType = getObjCInterfaceType(Decl); 2290} 2291 2292/// getFromTargetType - Given one of the integer types provided by 2293/// TargetInfo, produce the corresponding type. The unsigned @p Type 2294/// is actually a value of type @c TargetInfo::IntType. 2295QualType ASTContext::getFromTargetType(unsigned Type) const { 2296 switch (Type) { 2297 case TargetInfo::NoInt: return QualType(); 2298 case TargetInfo::SignedShort: return ShortTy; 2299 case TargetInfo::UnsignedShort: return UnsignedShortTy; 2300 case TargetInfo::SignedInt: return IntTy; 2301 case TargetInfo::UnsignedInt: return UnsignedIntTy; 2302 case TargetInfo::SignedLong: return LongTy; 2303 case TargetInfo::UnsignedLong: return UnsignedLongTy; 2304 case TargetInfo::SignedLongLong: return LongLongTy; 2305 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy; 2306 } 2307 2308 assert(false && "Unhandled TargetInfo::IntType value"); 2309 return QualType(); 2310} 2311 2312//===----------------------------------------------------------------------===// 2313// Type Predicates. 2314//===----------------------------------------------------------------------===// 2315 2316/// isObjCNSObjectType - Return true if this is an NSObject object using 2317/// NSObject attribute on a c-style pointer type. 2318/// FIXME - Make it work directly on types. 2319/// 2320bool ASTContext::isObjCNSObjectType(QualType Ty) const { 2321 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) { 2322 if (TypedefDecl *TD = TDT->getDecl()) 2323 if (TD->getAttr<ObjCNSObjectAttr>()) 2324 return true; 2325 } 2326 return false; 2327} 2328 2329/// isObjCObjectPointerType - Returns true if type is an Objective-C pointer 2330/// to an object type. This includes "id" and "Class" (two 'special' pointers 2331/// to struct), Interface* (pointer to ObjCInterfaceType) and id<P> (qualified 2332/// ID type). 2333bool ASTContext::isObjCObjectPointerType(QualType Ty) const { 2334 if (Ty->isObjCQualifiedIdType()) 2335 return true; 2336 2337 // Blocks are objects. 2338 if (Ty->isBlockPointerType()) 2339 return true; 2340 2341 // All other object types are pointers. 2342 if (!Ty->isPointerType()) 2343 return false; 2344 2345 // Check to see if this is 'id' or 'Class', both of which are typedefs for 2346 // pointer types. This looks for the typedef specifically, not for the 2347 // underlying type. 2348 if (Ty == getObjCIdType() || Ty == getObjCClassType()) 2349 return true; 2350 2351 // If this a pointer to an interface (e.g. NSString*), it is ok. 2352 if (Ty->getAsPointerType()->getPointeeType()->isObjCInterfaceType()) 2353 return true; 2354 2355 // If is has NSObject attribute, OK as well. 2356 return isObjCNSObjectType(Ty); 2357} 2358 2359//===----------------------------------------------------------------------===// 2360// Type Compatibility Testing 2361//===----------------------------------------------------------------------===// 2362 2363/// typesAreBlockCompatible - This routine is called when comparing two 2364/// block types. Types must be strictly compatible here. For example, 2365/// C unfortunately doesn't produce an error for the following: 2366/// 2367/// int (*emptyArgFunc)(); 2368/// int (*intArgList)(int) = emptyArgFunc; 2369/// 2370/// For blocks, we will produce an error for the following (similar to C++): 2371/// 2372/// int (^emptyArgBlock)(); 2373/// int (^intArgBlock)(int) = emptyArgBlock; 2374/// 2375/// FIXME: When the dust settles on this integration, fold this into mergeTypes. 2376/// 2377bool ASTContext::typesAreBlockCompatible(QualType lhs, QualType rhs) { 2378 const FunctionType *lbase = lhs->getAsFunctionType(); 2379 const FunctionType *rbase = rhs->getAsFunctionType(); 2380 const FunctionTypeProto *lproto = dyn_cast<FunctionTypeProto>(lbase); 2381 const FunctionTypeProto *rproto = dyn_cast<FunctionTypeProto>(rbase); 2382 if (lproto && rproto) 2383 return !mergeTypes(lhs, rhs).isNull(); 2384 return false; 2385} 2386 2387/// areCompatVectorTypes - Return true if the two specified vector types are 2388/// compatible. 2389static bool areCompatVectorTypes(const VectorType *LHS, 2390 const VectorType *RHS) { 2391 assert(LHS->isCanonical() && RHS->isCanonical()); 2392 return LHS->getElementType() == RHS->getElementType() && 2393 LHS->getNumElements() == RHS->getNumElements(); 2394} 2395 2396/// canAssignObjCInterfaces - Return true if the two interface types are 2397/// compatible for assignment from RHS to LHS. This handles validation of any 2398/// protocol qualifiers on the LHS or RHS. 2399/// 2400bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS, 2401 const ObjCInterfaceType *RHS) { 2402 // Verify that the base decls are compatible: the RHS must be a subclass of 2403 // the LHS. 2404 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl())) 2405 return false; 2406 2407 // RHS must have a superset of the protocols in the LHS. If the LHS is not 2408 // protocol qualified at all, then we are good. 2409 if (!isa<ObjCQualifiedInterfaceType>(LHS)) 2410 return true; 2411 2412 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it 2413 // isn't a superset. 2414 if (!isa<ObjCQualifiedInterfaceType>(RHS)) 2415 return true; // FIXME: should return false! 2416 2417 // Finally, we must have two protocol-qualified interfaces. 2418 const ObjCQualifiedInterfaceType *LHSP =cast<ObjCQualifiedInterfaceType>(LHS); 2419 const ObjCQualifiedInterfaceType *RHSP =cast<ObjCQualifiedInterfaceType>(RHS); 2420 ObjCQualifiedInterfaceType::qual_iterator LHSPI = LHSP->qual_begin(); 2421 ObjCQualifiedInterfaceType::qual_iterator LHSPE = LHSP->qual_end(); 2422 ObjCQualifiedInterfaceType::qual_iterator RHSPI = RHSP->qual_begin(); 2423 ObjCQualifiedInterfaceType::qual_iterator RHSPE = RHSP->qual_end(); 2424 2425 // All protocols in LHS must have a presence in RHS. Since the protocol lists 2426 // are both sorted alphabetically and have no duplicates, we can scan RHS and 2427 // LHS in a single parallel scan until we run out of elements in LHS. 2428 assert(LHSPI != LHSPE && "Empty LHS protocol list?"); 2429 ObjCProtocolDecl *LHSProto = *LHSPI; 2430 2431 while (RHSPI != RHSPE) { 2432 ObjCProtocolDecl *RHSProto = *RHSPI++; 2433 // If the RHS has a protocol that the LHS doesn't, ignore it. 2434 if (RHSProto != LHSProto) 2435 continue; 2436 2437 // Otherwise, the RHS does have this element. 2438 ++LHSPI; 2439 if (LHSPI == LHSPE) 2440 return true; // All protocols in LHS exist in RHS. 2441 2442 LHSProto = *LHSPI; 2443 } 2444 2445 // If we got here, we didn't find one of the LHS's protocols in the RHS list. 2446 return false; 2447} 2448 2449bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) { 2450 // get the "pointed to" types 2451 const PointerType *LHSPT = LHS->getAsPointerType(); 2452 const PointerType *RHSPT = RHS->getAsPointerType(); 2453 2454 if (!LHSPT || !RHSPT) 2455 return false; 2456 2457 QualType lhptee = LHSPT->getPointeeType(); 2458 QualType rhptee = RHSPT->getPointeeType(); 2459 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType(); 2460 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType(); 2461 // ID acts sort of like void* for ObjC interfaces 2462 if (LHSIface && isObjCIdStructType(rhptee)) 2463 return true; 2464 if (RHSIface && isObjCIdStructType(lhptee)) 2465 return true; 2466 if (!LHSIface || !RHSIface) 2467 return false; 2468 return canAssignObjCInterfaces(LHSIface, RHSIface) || 2469 canAssignObjCInterfaces(RHSIface, LHSIface); 2470} 2471 2472/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible, 2473/// both shall have the identically qualified version of a compatible type. 2474/// C99 6.2.7p1: Two types have compatible types if their types are the 2475/// same. See 6.7.[2,3,5] for additional rules. 2476bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) { 2477 return !mergeTypes(LHS, RHS).isNull(); 2478} 2479 2480QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) { 2481 const FunctionType *lbase = lhs->getAsFunctionType(); 2482 const FunctionType *rbase = rhs->getAsFunctionType(); 2483 const FunctionTypeProto *lproto = dyn_cast<FunctionTypeProto>(lbase); 2484 const FunctionTypeProto *rproto = dyn_cast<FunctionTypeProto>(rbase); 2485 bool allLTypes = true; 2486 bool allRTypes = true; 2487 2488 // Check return type 2489 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType()); 2490 if (retType.isNull()) return QualType(); 2491 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType())) 2492 allLTypes = false; 2493 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType())) 2494 allRTypes = false; 2495 2496 if (lproto && rproto) { // two C99 style function prototypes 2497 unsigned lproto_nargs = lproto->getNumArgs(); 2498 unsigned rproto_nargs = rproto->getNumArgs(); 2499 2500 // Compatible functions must have the same number of arguments 2501 if (lproto_nargs != rproto_nargs) 2502 return QualType(); 2503 2504 // Variadic and non-variadic functions aren't compatible 2505 if (lproto->isVariadic() != rproto->isVariadic()) 2506 return QualType(); 2507 2508 if (lproto->getTypeQuals() != rproto->getTypeQuals()) 2509 return QualType(); 2510 2511 // Check argument compatibility 2512 llvm::SmallVector<QualType, 10> types; 2513 for (unsigned i = 0; i < lproto_nargs; i++) { 2514 QualType largtype = lproto->getArgType(i).getUnqualifiedType(); 2515 QualType rargtype = rproto->getArgType(i).getUnqualifiedType(); 2516 QualType argtype = mergeTypes(largtype, rargtype); 2517 if (argtype.isNull()) return QualType(); 2518 types.push_back(argtype); 2519 if (getCanonicalType(argtype) != getCanonicalType(largtype)) 2520 allLTypes = false; 2521 if (getCanonicalType(argtype) != getCanonicalType(rargtype)) 2522 allRTypes = false; 2523 } 2524 if (allLTypes) return lhs; 2525 if (allRTypes) return rhs; 2526 return getFunctionType(retType, types.begin(), types.size(), 2527 lproto->isVariadic(), lproto->getTypeQuals()); 2528 } 2529 2530 if (lproto) allRTypes = false; 2531 if (rproto) allLTypes = false; 2532 2533 const FunctionTypeProto *proto = lproto ? lproto : rproto; 2534 if (proto) { 2535 if (proto->isVariadic()) return QualType(); 2536 // Check that the types are compatible with the types that 2537 // would result from default argument promotions (C99 6.7.5.3p15). 2538 // The only types actually affected are promotable integer 2539 // types and floats, which would be passed as a different 2540 // type depending on whether the prototype is visible. 2541 unsigned proto_nargs = proto->getNumArgs(); 2542 for (unsigned i = 0; i < proto_nargs; ++i) { 2543 QualType argTy = proto->getArgType(i); 2544 if (argTy->isPromotableIntegerType() || 2545 getCanonicalType(argTy).getUnqualifiedType() == FloatTy) 2546 return QualType(); 2547 } 2548 2549 if (allLTypes) return lhs; 2550 if (allRTypes) return rhs; 2551 return getFunctionType(retType, proto->arg_type_begin(), 2552 proto->getNumArgs(), lproto->isVariadic(), 2553 lproto->getTypeQuals()); 2554 } 2555 2556 if (allLTypes) return lhs; 2557 if (allRTypes) return rhs; 2558 return getFunctionTypeNoProto(retType); 2559} 2560 2561QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) { 2562 // C++ [expr]: If an expression initially has the type "reference to T", the 2563 // type is adjusted to "T" prior to any further analysis, the expression 2564 // designates the object or function denoted by the reference, and the 2565 // expression is an lvalue. 2566 // FIXME: C++ shouldn't be going through here! The rules are different 2567 // enough that they should be handled separately. 2568 if (const ReferenceType *RT = LHS->getAsReferenceType()) 2569 LHS = RT->getPointeeType(); 2570 if (const ReferenceType *RT = RHS->getAsReferenceType()) 2571 RHS = RT->getPointeeType(); 2572 2573 QualType LHSCan = getCanonicalType(LHS), 2574 RHSCan = getCanonicalType(RHS); 2575 2576 // If two types are identical, they are compatible. 2577 if (LHSCan == RHSCan) 2578 return LHS; 2579 2580 // If the qualifiers are different, the types aren't compatible 2581 if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers() || 2582 LHSCan.getAddressSpace() != RHSCan.getAddressSpace()) 2583 return QualType(); 2584 2585 Type::TypeClass LHSClass = LHSCan->getTypeClass(); 2586 Type::TypeClass RHSClass = RHSCan->getTypeClass(); 2587 2588 // We want to consider the two function types to be the same for these 2589 // comparisons, just force one to the other. 2590 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto; 2591 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto; 2592 2593 // Same as above for arrays 2594 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray) 2595 LHSClass = Type::ConstantArray; 2596 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray) 2597 RHSClass = Type::ConstantArray; 2598 2599 // Canonicalize ExtVector -> Vector. 2600 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector; 2601 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector; 2602 2603 // Consider qualified interfaces and interfaces the same. 2604 if (LHSClass == Type::ObjCQualifiedInterface) LHSClass = Type::ObjCInterface; 2605 if (RHSClass == Type::ObjCQualifiedInterface) RHSClass = Type::ObjCInterface; 2606 2607 // If the canonical type classes don't match. 2608 if (LHSClass != RHSClass) { 2609 // ID is compatible with all qualified id types. 2610 if (LHS->isObjCQualifiedIdType()) { 2611 if (const PointerType *PT = RHS->getAsPointerType()) { 2612 QualType pType = PT->getPointeeType(); 2613 if (isObjCIdStructType(pType)) 2614 return LHS; 2615 // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true). 2616 // Unfortunately, this API is part of Sema (which we don't have access 2617 // to. Need to refactor. The following check is insufficient, since we 2618 // need to make sure the class implements the protocol. 2619 if (pType->isObjCInterfaceType()) 2620 return LHS; 2621 } 2622 } 2623 if (RHS->isObjCQualifiedIdType()) { 2624 if (const PointerType *PT = LHS->getAsPointerType()) { 2625 QualType pType = PT->getPointeeType(); 2626 if (isObjCIdStructType(pType)) 2627 return RHS; 2628 // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true). 2629 // Unfortunately, this API is part of Sema (which we don't have access 2630 // to. Need to refactor. The following check is insufficient, since we 2631 // need to make sure the class implements the protocol. 2632 if (pType->isObjCInterfaceType()) 2633 return RHS; 2634 } 2635 } 2636 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char, 2637 // a signed integer type, or an unsigned integer type. 2638 if (const EnumType* ETy = LHS->getAsEnumType()) { 2639 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType()) 2640 return RHS; 2641 } 2642 if (const EnumType* ETy = RHS->getAsEnumType()) { 2643 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType()) 2644 return LHS; 2645 } 2646 2647 return QualType(); 2648 } 2649 2650 // The canonical type classes match. 2651 switch (LHSClass) { 2652 case Type::Pointer: 2653 { 2654 // Merge two pointer types, while trying to preserve typedef info 2655 QualType LHSPointee = LHS->getAsPointerType()->getPointeeType(); 2656 QualType RHSPointee = RHS->getAsPointerType()->getPointeeType(); 2657 QualType ResultType = mergeTypes(LHSPointee, RHSPointee); 2658 if (ResultType.isNull()) return QualType(); 2659 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 2660 return LHS; 2661 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 2662 return RHS; 2663 return getPointerType(ResultType); 2664 } 2665 case Type::BlockPointer: 2666 { 2667 // Merge two block pointer types, while trying to preserve typedef info 2668 QualType LHSPointee = LHS->getAsBlockPointerType()->getPointeeType(); 2669 QualType RHSPointee = RHS->getAsBlockPointerType()->getPointeeType(); 2670 QualType ResultType = mergeTypes(LHSPointee, RHSPointee); 2671 if (ResultType.isNull()) return QualType(); 2672 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 2673 return LHS; 2674 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 2675 return RHS; 2676 return getBlockPointerType(ResultType); 2677 } 2678 case Type::ConstantArray: 2679 { 2680 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS); 2681 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS); 2682 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize()) 2683 return QualType(); 2684 2685 QualType LHSElem = getAsArrayType(LHS)->getElementType(); 2686 QualType RHSElem = getAsArrayType(RHS)->getElementType(); 2687 QualType ResultType = mergeTypes(LHSElem, RHSElem); 2688 if (ResultType.isNull()) return QualType(); 2689 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 2690 return LHS; 2691 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 2692 return RHS; 2693 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(), 2694 ArrayType::ArraySizeModifier(), 0); 2695 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(), 2696 ArrayType::ArraySizeModifier(), 0); 2697 const VariableArrayType* LVAT = getAsVariableArrayType(LHS); 2698 const VariableArrayType* RVAT = getAsVariableArrayType(RHS); 2699 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 2700 return LHS; 2701 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 2702 return RHS; 2703 if (LVAT) { 2704 // FIXME: This isn't correct! But tricky to implement because 2705 // the array's size has to be the size of LHS, but the type 2706 // has to be different. 2707 return LHS; 2708 } 2709 if (RVAT) { 2710 // FIXME: This isn't correct! But tricky to implement because 2711 // the array's size has to be the size of RHS, but the type 2712 // has to be different. 2713 return RHS; 2714 } 2715 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS; 2716 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS; 2717 return getIncompleteArrayType(ResultType, ArrayType::ArraySizeModifier(),0); 2718 } 2719 case Type::FunctionNoProto: 2720 return mergeFunctionTypes(LHS, RHS); 2721 case Type::Tagged: 2722 // FIXME: Why are these compatible? 2723 if (isObjCIdStructType(LHS) && isObjCClassStructType(RHS)) return LHS; 2724 if (isObjCClassStructType(LHS) && isObjCIdStructType(RHS)) return LHS; 2725 return QualType(); 2726 case Type::Builtin: 2727 // Only exactly equal builtin types are compatible, which is tested above. 2728 return QualType(); 2729 case Type::Complex: 2730 // Distinct complex types are incompatible. 2731 return QualType(); 2732 case Type::Vector: 2733 if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType())) 2734 return LHS; 2735 return QualType(); 2736 case Type::ObjCInterface: 2737 // Distinct ObjC interfaces are not compatible; see canAssignObjCInterfaces 2738 // for checking assignment/comparison safety 2739 return QualType(); 2740 case Type::ObjCQualifiedId: 2741 // Distinct qualified id's are not compatible. 2742 return QualType(); 2743 default: 2744 assert(0 && "unexpected type"); 2745 return QualType(); 2746 } 2747} 2748 2749//===----------------------------------------------------------------------===// 2750// Integer Predicates 2751//===----------------------------------------------------------------------===// 2752 2753unsigned ASTContext::getIntWidth(QualType T) { 2754 if (T == BoolTy) 2755 return 1; 2756 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) { 2757 return FWIT->getWidth(); 2758 } 2759 // For builtin types, just use the standard type sizing method 2760 return (unsigned)getTypeSize(T); 2761} 2762 2763QualType ASTContext::getCorrespondingUnsignedType(QualType T) { 2764 assert(T->isSignedIntegerType() && "Unexpected type"); 2765 if (const EnumType* ETy = T->getAsEnumType()) 2766 T = ETy->getDecl()->getIntegerType(); 2767 const BuiltinType* BTy = T->getAsBuiltinType(); 2768 assert (BTy && "Unexpected signed integer type"); 2769 switch (BTy->getKind()) { 2770 case BuiltinType::Char_S: 2771 case BuiltinType::SChar: 2772 return UnsignedCharTy; 2773 case BuiltinType::Short: 2774 return UnsignedShortTy; 2775 case BuiltinType::Int: 2776 return UnsignedIntTy; 2777 case BuiltinType::Long: 2778 return UnsignedLongTy; 2779 case BuiltinType::LongLong: 2780 return UnsignedLongLongTy; 2781 default: 2782 assert(0 && "Unexpected signed integer type"); 2783 return QualType(); 2784 } 2785} 2786 2787 2788//===----------------------------------------------------------------------===// 2789// Serialization Support 2790//===----------------------------------------------------------------------===// 2791 2792/// Emit - Serialize an ASTContext object to Bitcode. 2793void ASTContext::Emit(llvm::Serializer& S) const { 2794 S.Emit(LangOpts); 2795 S.EmitRef(SourceMgr); 2796 S.EmitRef(Target); 2797 S.EmitRef(Idents); 2798 S.EmitRef(Selectors); 2799 2800 // Emit the size of the type vector so that we can reserve that size 2801 // when we reconstitute the ASTContext object. 2802 S.EmitInt(Types.size()); 2803 2804 for (std::vector<Type*>::const_iterator I=Types.begin(), E=Types.end(); 2805 I!=E;++I) 2806 (*I)->Emit(S); 2807 2808 S.EmitOwnedPtr(TUDecl); 2809 2810 // FIXME: S.EmitOwnedPtr(CFConstantStringTypeDecl); 2811} 2812 2813ASTContext* ASTContext::Create(llvm::Deserializer& D) { 2814 2815 // Read the language options. 2816 LangOptions LOpts; 2817 LOpts.Read(D); 2818 2819 SourceManager &SM = D.ReadRef<SourceManager>(); 2820 TargetInfo &t = D.ReadRef<TargetInfo>(); 2821 IdentifierTable &idents = D.ReadRef<IdentifierTable>(); 2822 SelectorTable &sels = D.ReadRef<SelectorTable>(); 2823 2824 unsigned size_reserve = D.ReadInt(); 2825 2826 ASTContext* A = new ASTContext(LOpts, SM, t, idents, sels, 2827 size_reserve); 2828 2829 for (unsigned i = 0; i < size_reserve; ++i) 2830 Type::Create(*A,i,D); 2831 2832 A->TUDecl = cast<TranslationUnitDecl>(D.ReadOwnedPtr<Decl>(*A)); 2833 2834 // FIXME: A->CFConstantStringTypeDecl = D.ReadOwnedPtr<RecordDecl>(); 2835 2836 return A; 2837} 2838