ASTContext.cpp revision 2e22253e03e175144aeb9d13350a12fd83f858be
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/ExternalASTSource.h" 20#include "clang/AST/RecordLayout.h" 21#include "clang/Basic/Builtins.h" 22#include "clang/Basic/SourceManager.h" 23#include "clang/Basic/TargetInfo.h" 24#include "llvm/ADT/StringExtras.h" 25#include "llvm/Support/MathExtras.h" 26#include "llvm/Support/MemoryBuffer.h" 27using namespace clang; 28 29enum FloatingRank { 30 FloatRank, DoubleRank, LongDoubleRank 31}; 32 33ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM, 34 TargetInfo &t, 35 IdentifierTable &idents, SelectorTable &sels, 36 Builtin::Context &builtins, 37 bool FreeMem, unsigned size_reserve) : 38 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0), 39 ObjCFastEnumerationStateTypeDecl(0), SourceMgr(SM), LangOpts(LOpts), 40 LoadedExternalComments(false), FreeMemory(FreeMem), Target(t), 41 Idents(idents), Selectors(sels), 42 BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts) { 43 if (size_reserve > 0) Types.reserve(size_reserve); 44 InitBuiltinTypes(); 45 TUDecl = TranslationUnitDecl::Create(*this); 46} 47 48ASTContext::~ASTContext() { 49 // Deallocate all the types. 50 while (!Types.empty()) { 51 Types.back()->Destroy(*this); 52 Types.pop_back(); 53 } 54 55 { 56 llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator 57 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); 58 while (I != E) { 59 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second); 60 delete R; 61 } 62 } 63 64 { 65 llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>::iterator 66 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); 67 while (I != E) { 68 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second); 69 delete R; 70 } 71 } 72 73 // Destroy nested-name-specifiers. 74 for (llvm::FoldingSet<NestedNameSpecifier>::iterator 75 NNS = NestedNameSpecifiers.begin(), 76 NNSEnd = NestedNameSpecifiers.end(); 77 NNS != NNSEnd; 78 /* Increment in loop */) 79 (*NNS++).Destroy(*this); 80 81 if (GlobalNestedNameSpecifier) 82 GlobalNestedNameSpecifier->Destroy(*this); 83 84 TUDecl->Destroy(*this); 85} 86 87void 88ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) { 89 ExternalSource.reset(Source.take()); 90} 91 92void ASTContext::PrintStats() const { 93 fprintf(stderr, "*** AST Context Stats:\n"); 94 fprintf(stderr, " %d types total.\n", (int)Types.size()); 95 96 unsigned counts[] = { 97#define TYPE(Name, Parent) 0, 98#define ABSTRACT_TYPE(Name, Parent) 99#include "clang/AST/TypeNodes.def" 100 0 // Extra 101 }; 102 103 for (unsigned i = 0, e = Types.size(); i != e; ++i) { 104 Type *T = Types[i]; 105 counts[(unsigned)T->getTypeClass()]++; 106 } 107 108 unsigned Idx = 0; 109 unsigned TotalBytes = 0; 110#define TYPE(Name, Parent) \ 111 if (counts[Idx]) \ 112 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \ 113 TotalBytes += counts[Idx] * sizeof(Name##Type); \ 114 ++Idx; 115#define ABSTRACT_TYPE(Name, Parent) 116#include "clang/AST/TypeNodes.def" 117 118 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes)); 119 120 if (ExternalSource.get()) { 121 fprintf(stderr, "\n"); 122 ExternalSource->PrintStats(); 123 } 124} 125 126 127void ASTContext::InitBuiltinType(QualType &R, BuiltinType::Kind K) { 128 Types.push_back((R = QualType(new (*this,8) BuiltinType(K),0)).getTypePtr()); 129} 130 131void ASTContext::InitBuiltinTypes() { 132 assert(VoidTy.isNull() && "Context reinitialized?"); 133 134 // C99 6.2.5p19. 135 InitBuiltinType(VoidTy, BuiltinType::Void); 136 137 // C99 6.2.5p2. 138 InitBuiltinType(BoolTy, BuiltinType::Bool); 139 // C99 6.2.5p3. 140 if (LangOpts.CharIsSigned) 141 InitBuiltinType(CharTy, BuiltinType::Char_S); 142 else 143 InitBuiltinType(CharTy, BuiltinType::Char_U); 144 // C99 6.2.5p4. 145 InitBuiltinType(SignedCharTy, BuiltinType::SChar); 146 InitBuiltinType(ShortTy, BuiltinType::Short); 147 InitBuiltinType(IntTy, BuiltinType::Int); 148 InitBuiltinType(LongTy, BuiltinType::Long); 149 InitBuiltinType(LongLongTy, BuiltinType::LongLong); 150 151 // C99 6.2.5p6. 152 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar); 153 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort); 154 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt); 155 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong); 156 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong); 157 158 // C99 6.2.5p10. 159 InitBuiltinType(FloatTy, BuiltinType::Float); 160 InitBuiltinType(DoubleTy, BuiltinType::Double); 161 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble); 162 163 // GNU extension, 128-bit integers. 164 InitBuiltinType(Int128Ty, BuiltinType::Int128); 165 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128); 166 167 if (LangOpts.CPlusPlus) // C++ 3.9.1p5 168 InitBuiltinType(WCharTy, BuiltinType::WChar); 169 else // C99 170 WCharTy = getFromTargetType(Target.getWCharType()); 171 172 // Placeholder type for functions. 173 InitBuiltinType(OverloadTy, BuiltinType::Overload); 174 175 // Placeholder type for type-dependent expressions whose type is 176 // completely unknown. No code should ever check a type against 177 // DependentTy and users should never see it; however, it is here to 178 // help diagnose failures to properly check for type-dependent 179 // expressions. 180 InitBuiltinType(DependentTy, BuiltinType::Dependent); 181 182 // Placeholder type for C++0x auto declarations whose real type has 183 // not yet been deduced. 184 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto); 185 186 // C99 6.2.5p11. 187 FloatComplexTy = getComplexType(FloatTy); 188 DoubleComplexTy = getComplexType(DoubleTy); 189 LongDoubleComplexTy = getComplexType(LongDoubleTy); 190 191 BuiltinVaListType = QualType(); 192 ObjCIdType = QualType(); 193 IdStructType = 0; 194 ObjCClassType = QualType(); 195 ClassStructType = 0; 196 197 ObjCConstantStringType = QualType(); 198 199 // void * type 200 VoidPtrTy = getPointerType(VoidTy); 201 202 // nullptr type (C++0x 2.14.7) 203 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr); 204} 205 206namespace { 207 class BeforeInTranslationUnit 208 : std::binary_function<SourceRange, SourceRange, bool> { 209 SourceManager *SourceMgr; 210 211 public: 212 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { } 213 214 bool operator()(SourceRange X, SourceRange Y) { 215 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin()); 216 } 217 }; 218} 219 220/// \brief Determine whether the given comment is a Doxygen-style comment. 221/// 222/// \param Start the start of the comment text. 223/// 224/// \param End the end of the comment text. 225/// 226/// \param Member whether we want to check whether this is a member comment 227/// (which requires a < after the Doxygen-comment delimiter). Otherwise, 228/// we only return true when we find a non-member comment. 229static bool 230isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment, 231 bool Member = false) { 232 const char *BufferStart 233 = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first; 234 const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin()); 235 const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd()); 236 237 if (End - Start < 4) 238 return false; 239 240 assert(Start[0] == '/' && "Not a comment?"); 241 if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*')) 242 return false; 243 if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/')) 244 return false; 245 246 return (Start[3] == '<') == Member; 247} 248 249/// \brief Retrieve the comment associated with the given declaration, if 250/// it has one. 251const char *ASTContext::getCommentForDecl(const Decl *D) { 252 if (!D) 253 return 0; 254 255 // Check whether we have cached a comment string for this declaration 256 // already. 257 llvm::DenseMap<const Decl *, std::string>::iterator Pos 258 = DeclComments.find(D); 259 if (Pos != DeclComments.end()) 260 return Pos->second.c_str(); 261 262 // If we have an external AST source and have not yet loaded comments from 263 // that source, do so now. 264 if (ExternalSource && !LoadedExternalComments) { 265 std::vector<SourceRange> LoadedComments; 266 ExternalSource->ReadComments(LoadedComments); 267 268 if (!LoadedComments.empty()) 269 Comments.insert(Comments.begin(), LoadedComments.begin(), 270 LoadedComments.end()); 271 272 LoadedExternalComments = true; 273 } 274 275 // If there are no comments anywhere, we won't find anything. 276 if (Comments.empty()) 277 return 0; 278 279 // If the declaration doesn't map directly to a location in a file, we 280 // can't find the comment. 281 SourceLocation DeclStartLoc = D->getLocStart(); 282 if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID()) 283 return 0; 284 285 // Find the comment that occurs just before this declaration. 286 std::vector<SourceRange>::iterator LastComment 287 = std::lower_bound(Comments.begin(), Comments.end(), 288 SourceRange(DeclStartLoc), 289 BeforeInTranslationUnit(&SourceMgr)); 290 291 // Decompose the location for the start of the declaration and find the 292 // beginning of the file buffer. 293 std::pair<FileID, unsigned> DeclStartDecomp 294 = SourceMgr.getDecomposedLoc(DeclStartLoc); 295 const char *FileBufferStart 296 = SourceMgr.getBufferData(DeclStartDecomp.first).first; 297 298 // First check whether we have a comment for a member. 299 if (LastComment != Comments.end() && 300 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) && 301 isDoxygenComment(SourceMgr, *LastComment, true)) { 302 std::pair<FileID, unsigned> LastCommentEndDecomp 303 = SourceMgr.getDecomposedLoc(LastComment->getEnd()); 304 if (DeclStartDecomp.first == LastCommentEndDecomp.first && 305 SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second) 306 == SourceMgr.getLineNumber(LastCommentEndDecomp.first, 307 LastCommentEndDecomp.second)) { 308 // The Doxygen member comment comes after the declaration starts and 309 // is on the same line and in the same file as the declaration. This 310 // is the comment we want. 311 std::string &Result = DeclComments[D]; 312 Result.append(FileBufferStart + 313 SourceMgr.getFileOffset(LastComment->getBegin()), 314 FileBufferStart + LastCommentEndDecomp.second + 1); 315 return Result.c_str(); 316 } 317 } 318 319 if (LastComment == Comments.begin()) 320 return 0; 321 --LastComment; 322 323 // Decompose the end of the comment. 324 std::pair<FileID, unsigned> LastCommentEndDecomp 325 = SourceMgr.getDecomposedLoc(LastComment->getEnd()); 326 327 // If the comment and the declaration aren't in the same file, then they 328 // aren't related. 329 if (DeclStartDecomp.first != LastCommentEndDecomp.first) 330 return 0; 331 332 // Check that we actually have a Doxygen comment. 333 if (!isDoxygenComment(SourceMgr, *LastComment)) 334 return 0; 335 336 // Compute the starting line for the declaration and for the end of the 337 // comment (this is expensive). 338 unsigned DeclStartLine 339 = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second); 340 unsigned CommentEndLine 341 = SourceMgr.getLineNumber(LastCommentEndDecomp.first, 342 LastCommentEndDecomp.second); 343 344 // If the comment does not end on the line prior to the declaration, then 345 // the comment is not associated with the declaration at all. 346 if (CommentEndLine + 1 != DeclStartLine) 347 return 0; 348 349 // We have a comment, but there may be more comments on the previous lines. 350 // Keep looking so long as the comments are still Doxygen comments and are 351 // still adjacent. 352 unsigned ExpectedLine 353 = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1; 354 std::vector<SourceRange>::iterator FirstComment = LastComment; 355 while (FirstComment != Comments.begin()) { 356 // Look at the previous comment 357 --FirstComment; 358 std::pair<FileID, unsigned> Decomp 359 = SourceMgr.getDecomposedLoc(FirstComment->getEnd()); 360 361 // If this previous comment is in a different file, we're done. 362 if (Decomp.first != DeclStartDecomp.first) { 363 ++FirstComment; 364 break; 365 } 366 367 // If this comment is not a Doxygen comment, we're done. 368 if (!isDoxygenComment(SourceMgr, *FirstComment)) { 369 ++FirstComment; 370 break; 371 } 372 373 // If the line number is not what we expected, we're done. 374 unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second); 375 if (Line != ExpectedLine) { 376 ++FirstComment; 377 break; 378 } 379 380 // Set the next expected line number. 381 ExpectedLine 382 = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1; 383 } 384 385 // The iterator range [FirstComment, LastComment] contains all of the 386 // BCPL comments that, together, are associated with this declaration. 387 // Form a single comment block string for this declaration that concatenates 388 // all of these comments. 389 std::string &Result = DeclComments[D]; 390 while (FirstComment != LastComment) { 391 std::pair<FileID, unsigned> DecompStart 392 = SourceMgr.getDecomposedLoc(FirstComment->getBegin()); 393 std::pair<FileID, unsigned> DecompEnd 394 = SourceMgr.getDecomposedLoc(FirstComment->getEnd()); 395 Result.append(FileBufferStart + DecompStart.second, 396 FileBufferStart + DecompEnd.second + 1); 397 ++FirstComment; 398 } 399 400 // Append the last comment line. 401 Result.append(FileBufferStart + 402 SourceMgr.getFileOffset(LastComment->getBegin()), 403 FileBufferStart + LastCommentEndDecomp.second + 1); 404 return Result.c_str(); 405} 406 407//===----------------------------------------------------------------------===// 408// Type Sizing and Analysis 409//===----------------------------------------------------------------------===// 410 411/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified 412/// scalar floating point type. 413const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const { 414 const BuiltinType *BT = T->getAsBuiltinType(); 415 assert(BT && "Not a floating point type!"); 416 switch (BT->getKind()) { 417 default: assert(0 && "Not a floating point type!"); 418 case BuiltinType::Float: return Target.getFloatFormat(); 419 case BuiltinType::Double: return Target.getDoubleFormat(); 420 case BuiltinType::LongDouble: return Target.getLongDoubleFormat(); 421 } 422} 423 424/// getDeclAlign - Return a conservative estimate of the alignment of the 425/// specified decl. Note that bitfields do not have a valid alignment, so 426/// this method will assert on them. 427unsigned ASTContext::getDeclAlignInBytes(const Decl *D) { 428 unsigned Align = Target.getCharWidth(); 429 430 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) 431 Align = std::max(Align, AA->getAlignment()); 432 433 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 434 QualType T = VD->getType(); 435 if (const ReferenceType* RT = T->getAsReferenceType()) { 436 unsigned AS = RT->getPointeeType().getAddressSpace(); 437 Align = Target.getPointerAlign(AS); 438 } else if (!T->isIncompleteType() && !T->isFunctionType()) { 439 // Incomplete or function types default to 1. 440 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T)) 441 T = cast<ArrayType>(T)->getElementType(); 442 443 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr())); 444 } 445 } 446 447 return Align / Target.getCharWidth(); 448} 449 450/// getTypeSize - Return the size of the specified type, in bits. This method 451/// does not work on incomplete types. 452std::pair<uint64_t, unsigned> 453ASTContext::getTypeInfo(const Type *T) { 454 uint64_t Width=0; 455 unsigned Align=8; 456 switch (T->getTypeClass()) { 457#define TYPE(Class, Base) 458#define ABSTRACT_TYPE(Class, Base) 459#define NON_CANONICAL_TYPE(Class, Base) 460#define DEPENDENT_TYPE(Class, Base) case Type::Class: 461#include "clang/AST/TypeNodes.def" 462 assert(false && "Should not see dependent types"); 463 break; 464 465 case Type::FunctionNoProto: 466 case Type::FunctionProto: 467 // GCC extension: alignof(function) = 32 bits 468 Width = 0; 469 Align = 32; 470 break; 471 472 case Type::IncompleteArray: 473 case Type::VariableArray: 474 Width = 0; 475 Align = getTypeAlign(cast<ArrayType>(T)->getElementType()); 476 break; 477 478 case Type::ConstantArray: { 479 const ConstantArrayType *CAT = cast<ConstantArrayType>(T); 480 481 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType()); 482 Width = EltInfo.first*CAT->getSize().getZExtValue(); 483 Align = EltInfo.second; 484 break; 485 } 486 case Type::ExtVector: 487 case Type::Vector: { 488 std::pair<uint64_t, unsigned> EltInfo = 489 getTypeInfo(cast<VectorType>(T)->getElementType()); 490 Width = EltInfo.first*cast<VectorType>(T)->getNumElements(); 491 Align = Width; 492 // If the alignment is not a power of 2, round up to the next power of 2. 493 // This happens for non-power-of-2 length vectors. 494 // FIXME: this should probably be a target property. 495 Align = 1 << llvm::Log2_32_Ceil(Align); 496 break; 497 } 498 499 case Type::Builtin: 500 switch (cast<BuiltinType>(T)->getKind()) { 501 default: assert(0 && "Unknown builtin type!"); 502 case BuiltinType::Void: 503 // GCC extension: alignof(void) = 8 bits. 504 Width = 0; 505 Align = 8; 506 break; 507 508 case BuiltinType::Bool: 509 Width = Target.getBoolWidth(); 510 Align = Target.getBoolAlign(); 511 break; 512 case BuiltinType::Char_S: 513 case BuiltinType::Char_U: 514 case BuiltinType::UChar: 515 case BuiltinType::SChar: 516 Width = Target.getCharWidth(); 517 Align = Target.getCharAlign(); 518 break; 519 case BuiltinType::WChar: 520 Width = Target.getWCharWidth(); 521 Align = Target.getWCharAlign(); 522 break; 523 case BuiltinType::UShort: 524 case BuiltinType::Short: 525 Width = Target.getShortWidth(); 526 Align = Target.getShortAlign(); 527 break; 528 case BuiltinType::UInt: 529 case BuiltinType::Int: 530 Width = Target.getIntWidth(); 531 Align = Target.getIntAlign(); 532 break; 533 case BuiltinType::ULong: 534 case BuiltinType::Long: 535 Width = Target.getLongWidth(); 536 Align = Target.getLongAlign(); 537 break; 538 case BuiltinType::ULongLong: 539 case BuiltinType::LongLong: 540 Width = Target.getLongLongWidth(); 541 Align = Target.getLongLongAlign(); 542 break; 543 case BuiltinType::Int128: 544 case BuiltinType::UInt128: 545 Width = 128; 546 Align = 128; // int128_t is 128-bit aligned on all targets. 547 break; 548 case BuiltinType::Float: 549 Width = Target.getFloatWidth(); 550 Align = Target.getFloatAlign(); 551 break; 552 case BuiltinType::Double: 553 Width = Target.getDoubleWidth(); 554 Align = Target.getDoubleAlign(); 555 break; 556 case BuiltinType::LongDouble: 557 Width = Target.getLongDoubleWidth(); 558 Align = Target.getLongDoubleAlign(); 559 break; 560 case BuiltinType::NullPtr: 561 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t) 562 Align = Target.getPointerAlign(0); // == sizeof(void*) 563 break; 564 } 565 break; 566 case Type::FixedWidthInt: 567 // FIXME: This isn't precisely correct; the width/alignment should depend 568 // on the available types for the target 569 Width = cast<FixedWidthIntType>(T)->getWidth(); 570 Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8); 571 Align = Width; 572 break; 573 case Type::ExtQual: 574 // FIXME: Pointers into different addr spaces could have different sizes and 575 // alignment requirements: getPointerInfo should take an AddrSpace. 576 return getTypeInfo(QualType(cast<ExtQualType>(T)->getBaseType(), 0)); 577 case Type::ObjCObjectPointer: 578 case Type::ObjCQualifiedInterface: 579 Width = Target.getPointerWidth(0); 580 Align = Target.getPointerAlign(0); 581 break; 582 case Type::BlockPointer: { 583 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace(); 584 Width = Target.getPointerWidth(AS); 585 Align = Target.getPointerAlign(AS); 586 break; 587 } 588 case Type::Pointer: { 589 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace(); 590 Width = Target.getPointerWidth(AS); 591 Align = Target.getPointerAlign(AS); 592 break; 593 } 594 case Type::LValueReference: 595 case Type::RValueReference: 596 // "When applied to a reference or a reference type, the result is the size 597 // of the referenced type." C++98 5.3.3p2: expr.sizeof. 598 // FIXME: This is wrong for struct layout: a reference in a struct has 599 // pointer size. 600 return getTypeInfo(cast<ReferenceType>(T)->getPointeeType()); 601 case Type::MemberPointer: { 602 // FIXME: This is ABI dependent. We use the Itanium C++ ABI. 603 // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers 604 // If we ever want to support other ABIs this needs to be abstracted. 605 606 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType(); 607 std::pair<uint64_t, unsigned> PtrDiffInfo = 608 getTypeInfo(getPointerDiffType()); 609 Width = PtrDiffInfo.first; 610 if (Pointee->isFunctionType()) 611 Width *= 2; 612 Align = PtrDiffInfo.second; 613 break; 614 } 615 case Type::Complex: { 616 // Complex types have the same alignment as their elements, but twice the 617 // size. 618 std::pair<uint64_t, unsigned> EltInfo = 619 getTypeInfo(cast<ComplexType>(T)->getElementType()); 620 Width = EltInfo.first*2; 621 Align = EltInfo.second; 622 break; 623 } 624 case Type::ObjCInterface: { 625 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T); 626 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 627 Width = Layout.getSize(); 628 Align = Layout.getAlignment(); 629 break; 630 } 631 case Type::Record: 632 case Type::Enum: { 633 const TagType *TT = cast<TagType>(T); 634 635 if (TT->getDecl()->isInvalidDecl()) { 636 Width = 1; 637 Align = 1; 638 break; 639 } 640 641 if (const EnumType *ET = dyn_cast<EnumType>(TT)) 642 return getTypeInfo(ET->getDecl()->getIntegerType()); 643 644 const RecordType *RT = cast<RecordType>(TT); 645 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl()); 646 Width = Layout.getSize(); 647 Align = Layout.getAlignment(); 648 break; 649 } 650 651 case Type::Typedef: { 652 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl(); 653 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) { 654 Align = Aligned->getAlignment(); 655 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr()); 656 } else 657 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr()); 658 break; 659 } 660 661 case Type::TypeOfExpr: 662 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType() 663 .getTypePtr()); 664 665 case Type::TypeOf: 666 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr()); 667 668 case Type::Decltype: 669 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType() 670 .getTypePtr()); 671 672 case Type::QualifiedName: 673 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr()); 674 675 case Type::TemplateSpecialization: 676 assert(getCanonicalType(T) != T && 677 "Cannot request the size of a dependent type"); 678 // FIXME: this is likely to be wrong once we support template 679 // aliases, since a template alias could refer to a typedef that 680 // has an __aligned__ attribute on it. 681 return getTypeInfo(getCanonicalType(T)); 682 } 683 684 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2"); 685 return std::make_pair(Width, Align); 686} 687 688/// getPreferredTypeAlign - Return the "preferred" alignment of the specified 689/// type for the current target in bits. This can be different than the ABI 690/// alignment in cases where it is beneficial for performance to overalign 691/// a data type. 692unsigned ASTContext::getPreferredTypeAlign(const Type *T) { 693 unsigned ABIAlign = getTypeAlign(T); 694 695 // Double and long long should be naturally aligned if possible. 696 if (const ComplexType* CT = T->getAsComplexType()) 697 T = CT->getElementType().getTypePtr(); 698 if (T->isSpecificBuiltinType(BuiltinType::Double) || 699 T->isSpecificBuiltinType(BuiltinType::LongLong)) 700 return std::max(ABIAlign, (unsigned)getTypeSize(T)); 701 702 return ABIAlign; 703} 704 705 706/// LayoutField - Field layout. 707void ASTRecordLayout::LayoutField(const FieldDecl *FD, unsigned FieldNo, 708 bool IsUnion, unsigned StructPacking, 709 ASTContext &Context) { 710 unsigned FieldPacking = StructPacking; 711 uint64_t FieldOffset = IsUnion ? 0 : Size; 712 uint64_t FieldSize; 713 unsigned FieldAlign; 714 715 // FIXME: Should this override struct packing? Probably we want to 716 // take the minimum? 717 if (const PackedAttr *PA = FD->getAttr<PackedAttr>()) 718 FieldPacking = PA->getAlignment(); 719 720 if (const Expr *BitWidthExpr = FD->getBitWidth()) { 721 // TODO: Need to check this algorithm on other targets! 722 // (tested on Linux-X86) 723 FieldSize = BitWidthExpr->EvaluateAsInt(Context).getZExtValue(); 724 725 std::pair<uint64_t, unsigned> FieldInfo = 726 Context.getTypeInfo(FD->getType()); 727 uint64_t TypeSize = FieldInfo.first; 728 729 // Determine the alignment of this bitfield. The packing 730 // attributes define a maximum and the alignment attribute defines 731 // a minimum. 732 // FIXME: What is the right behavior when the specified alignment 733 // is smaller than the specified packing? 734 FieldAlign = FieldInfo.second; 735 if (FieldPacking) 736 FieldAlign = std::min(FieldAlign, FieldPacking); 737 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>()) 738 FieldAlign = std::max(FieldAlign, AA->getAlignment()); 739 740 // Check if we need to add padding to give the field the correct 741 // alignment. 742 if (FieldSize == 0 || (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize) 743 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1); 744 745 // Padding members don't affect overall alignment 746 if (!FD->getIdentifier()) 747 FieldAlign = 1; 748 } else { 749 if (FD->getType()->isIncompleteArrayType()) { 750 // This is a flexible array member; we can't directly 751 // query getTypeInfo about these, so we figure it out here. 752 // Flexible array members don't have any size, but they 753 // have to be aligned appropriately for their element type. 754 FieldSize = 0; 755 const ArrayType* ATy = Context.getAsArrayType(FD->getType()); 756 FieldAlign = Context.getTypeAlign(ATy->getElementType()); 757 } else if (const ReferenceType *RT = FD->getType()->getAsReferenceType()) { 758 unsigned AS = RT->getPointeeType().getAddressSpace(); 759 FieldSize = Context.Target.getPointerWidth(AS); 760 FieldAlign = Context.Target.getPointerAlign(AS); 761 } else { 762 std::pair<uint64_t, unsigned> FieldInfo = 763 Context.getTypeInfo(FD->getType()); 764 FieldSize = FieldInfo.first; 765 FieldAlign = FieldInfo.second; 766 } 767 768 // Determine the alignment of this bitfield. The packing 769 // attributes define a maximum and the alignment attribute defines 770 // a minimum. Additionally, the packing alignment must be at least 771 // a byte for non-bitfields. 772 // 773 // FIXME: What is the right behavior when the specified alignment 774 // is smaller than the specified packing? 775 if (FieldPacking) 776 FieldAlign = std::min(FieldAlign, std::max(8U, FieldPacking)); 777 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>()) 778 FieldAlign = std::max(FieldAlign, AA->getAlignment()); 779 780 // Round up the current record size to the field's alignment boundary. 781 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1); 782 } 783 784 // Place this field at the current location. 785 FieldOffsets[FieldNo] = FieldOffset; 786 787 // Reserve space for this field. 788 if (IsUnion) { 789 Size = std::max(Size, FieldSize); 790 } else { 791 Size = FieldOffset + FieldSize; 792 } 793 794 // Remember the next available offset. 795 NextOffset = Size; 796 797 // Remember max struct/class alignment. 798 Alignment = std::max(Alignment, FieldAlign); 799} 800 801static void CollectLocalObjCIvars(ASTContext *Ctx, 802 const ObjCInterfaceDecl *OI, 803 llvm::SmallVectorImpl<FieldDecl*> &Fields) { 804 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(), 805 E = OI->ivar_end(); I != E; ++I) { 806 ObjCIvarDecl *IVDecl = *I; 807 if (!IVDecl->isInvalidDecl()) 808 Fields.push_back(cast<FieldDecl>(IVDecl)); 809 } 810} 811 812void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI, 813 llvm::SmallVectorImpl<FieldDecl*> &Fields) { 814 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass()) 815 CollectObjCIvars(SuperClass, Fields); 816 CollectLocalObjCIvars(this, OI, Fields); 817} 818 819/// ShallowCollectObjCIvars - 820/// Collect all ivars, including those synthesized, in the current class. 821/// 822void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI, 823 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars, 824 bool CollectSynthesized) { 825 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(), 826 E = OI->ivar_end(); I != E; ++I) { 827 Ivars.push_back(*I); 828 } 829 if (CollectSynthesized) 830 CollectSynthesizedIvars(OI, Ivars); 831} 832 833void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD, 834 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) { 835 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(), 836 E = PD->prop_end(); I != E; ++I) 837 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl()) 838 Ivars.push_back(Ivar); 839 840 // Also look into nested protocols. 841 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(), 842 E = PD->protocol_end(); P != E; ++P) 843 CollectProtocolSynthesizedIvars(*P, Ivars); 844} 845 846/// CollectSynthesizedIvars - 847/// This routine collect synthesized ivars for the designated class. 848/// 849void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI, 850 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) { 851 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(), 852 E = OI->prop_end(); I != E; ++I) { 853 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl()) 854 Ivars.push_back(Ivar); 855 } 856 // Also look into interface's protocol list for properties declared 857 // in the protocol and whose ivars are synthesized. 858 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(), 859 PE = OI->protocol_end(); P != PE; ++P) { 860 ObjCProtocolDecl *PD = (*P); 861 CollectProtocolSynthesizedIvars(PD, Ivars); 862 } 863} 864 865unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) { 866 unsigned count = 0; 867 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(), 868 E = PD->prop_end(); I != E; ++I) 869 if ((*I)->getPropertyIvarDecl()) 870 ++count; 871 872 // Also look into nested protocols. 873 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(), 874 E = PD->protocol_end(); P != E; ++P) 875 count += CountProtocolSynthesizedIvars(*P); 876 return count; 877} 878 879unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI) 880{ 881 unsigned count = 0; 882 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(), 883 E = OI->prop_end(); I != E; ++I) { 884 if ((*I)->getPropertyIvarDecl()) 885 ++count; 886 } 887 // Also look into interface's protocol list for properties declared 888 // in the protocol and whose ivars are synthesized. 889 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(), 890 PE = OI->protocol_end(); P != PE; ++P) { 891 ObjCProtocolDecl *PD = (*P); 892 count += CountProtocolSynthesizedIvars(PD); 893 } 894 return count; 895} 896 897/// getInterfaceLayoutImpl - Get or compute information about the 898/// layout of the given interface. 899/// 900/// \param Impl - If given, also include the layout of the interface's 901/// implementation. This may differ by including synthesized ivars. 902const ASTRecordLayout & 903ASTContext::getObjCLayout(const ObjCInterfaceDecl *D, 904 const ObjCImplementationDecl *Impl) { 905 assert(!D->isForwardDecl() && "Invalid interface decl!"); 906 907 // Look up this layout, if already laid out, return what we have. 908 ObjCContainerDecl *Key = 909 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D; 910 if (const ASTRecordLayout *Entry = ObjCLayouts[Key]) 911 return *Entry; 912 913 unsigned FieldCount = D->ivar_size(); 914 // Add in synthesized ivar count if laying out an implementation. 915 if (Impl) { 916 unsigned SynthCount = CountSynthesizedIvars(D); 917 FieldCount += SynthCount; 918 // If there aren't any sythesized ivars then reuse the interface 919 // entry. Note we can't cache this because we simply free all 920 // entries later; however we shouldn't look up implementations 921 // frequently. 922 if (SynthCount == 0) 923 return getObjCLayout(D, 0); 924 } 925 926 ASTRecordLayout *NewEntry = NULL; 927 if (ObjCInterfaceDecl *SD = D->getSuperClass()) { 928 const ASTRecordLayout &SL = getASTObjCInterfaceLayout(SD); 929 unsigned Alignment = SL.getAlignment(); 930 931 // We start laying out ivars not at the end of the superclass 932 // structure, but at the next byte following the last field. 933 uint64_t Size = llvm::RoundUpToAlignment(SL.NextOffset, 8); 934 935 ObjCLayouts[Key] = NewEntry = new ASTRecordLayout(Size, Alignment); 936 NewEntry->InitializeLayout(FieldCount); 937 } else { 938 ObjCLayouts[Key] = NewEntry = new ASTRecordLayout(); 939 NewEntry->InitializeLayout(FieldCount); 940 } 941 942 unsigned StructPacking = 0; 943 if (const PackedAttr *PA = D->getAttr<PackedAttr>()) 944 StructPacking = PA->getAlignment(); 945 946 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>()) 947 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(), 948 AA->getAlignment())); 949 950 // Layout each ivar sequentially. 951 unsigned i = 0; 952 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars; 953 ShallowCollectObjCIvars(D, Ivars, Impl); 954 for (unsigned k = 0, e = Ivars.size(); k != e; ++k) 955 NewEntry->LayoutField(Ivars[k], i++, false, StructPacking, *this); 956 957 // Finally, round the size of the total struct up to the alignment of the 958 // struct itself. 959 NewEntry->FinalizeLayout(); 960 return *NewEntry; 961} 962 963const ASTRecordLayout & 964ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) { 965 return getObjCLayout(D, 0); 966} 967 968const ASTRecordLayout & 969ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) { 970 return getObjCLayout(D->getClassInterface(), D); 971} 972 973/// getASTRecordLayout - Get or compute information about the layout of the 974/// specified record (struct/union/class), which indicates its size and field 975/// position information. 976const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) { 977 D = D->getDefinition(*this); 978 assert(D && "Cannot get layout of forward declarations!"); 979 980 // Look up this layout, if already laid out, return what we have. 981 const ASTRecordLayout *&Entry = ASTRecordLayouts[D]; 982 if (Entry) return *Entry; 983 984 // Allocate and assign into ASTRecordLayouts here. The "Entry" reference can 985 // be invalidated (dangle) if the ASTRecordLayouts hashtable is inserted into. 986 ASTRecordLayout *NewEntry = new ASTRecordLayout(); 987 Entry = NewEntry; 988 989 // FIXME: Avoid linear walk through the fields, if possible. 990 NewEntry->InitializeLayout(std::distance(D->field_begin(), D->field_end())); 991 bool IsUnion = D->isUnion(); 992 993 unsigned StructPacking = 0; 994 if (const PackedAttr *PA = D->getAttr<PackedAttr>()) 995 StructPacking = PA->getAlignment(); 996 997 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>()) 998 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(), 999 AA->getAlignment())); 1000 1001 // Layout each field, for now, just sequentially, respecting alignment. In 1002 // the future, this will need to be tweakable by targets. 1003 unsigned FieldIdx = 0; 1004 for (RecordDecl::field_iterator Field = D->field_begin(), 1005 FieldEnd = D->field_end(); 1006 Field != FieldEnd; (void)++Field, ++FieldIdx) 1007 NewEntry->LayoutField(*Field, FieldIdx, IsUnion, StructPacking, *this); 1008 1009 // Finally, round the size of the total struct up to the alignment of the 1010 // struct itself. 1011 NewEntry->FinalizeLayout(getLangOptions().CPlusPlus); 1012 return *NewEntry; 1013} 1014 1015//===----------------------------------------------------------------------===// 1016// Type creation/memoization methods 1017//===----------------------------------------------------------------------===// 1018 1019QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) { 1020 QualType CanT = getCanonicalType(T); 1021 if (CanT.getAddressSpace() == AddressSpace) 1022 return T; 1023 1024 // If we are composing extended qualifiers together, merge together into one 1025 // ExtQualType node. 1026 unsigned CVRQuals = T.getCVRQualifiers(); 1027 QualType::GCAttrTypes GCAttr = QualType::GCNone; 1028 Type *TypeNode = T.getTypePtr(); 1029 1030 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) { 1031 // If this type already has an address space specified, it cannot get 1032 // another one. 1033 assert(EQT->getAddressSpace() == 0 && 1034 "Type cannot be in multiple addr spaces!"); 1035 GCAttr = EQT->getObjCGCAttr(); 1036 TypeNode = EQT->getBaseType(); 1037 } 1038 1039 // Check if we've already instantiated this type. 1040 llvm::FoldingSetNodeID ID; 1041 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr); 1042 void *InsertPos = 0; 1043 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos)) 1044 return QualType(EXTQy, CVRQuals); 1045 1046 // If the base type isn't canonical, this won't be a canonical type either, 1047 // so fill in the canonical type field. 1048 QualType Canonical; 1049 if (!TypeNode->isCanonical()) { 1050 Canonical = getAddrSpaceQualType(CanT, AddressSpace); 1051 1052 // Update InsertPos, the previous call could have invalidated it. 1053 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos); 1054 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1055 } 1056 ExtQualType *New = 1057 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr); 1058 ExtQualTypes.InsertNode(New, InsertPos); 1059 Types.push_back(New); 1060 return QualType(New, CVRQuals); 1061} 1062 1063QualType ASTContext::getObjCGCQualType(QualType T, 1064 QualType::GCAttrTypes GCAttr) { 1065 QualType CanT = getCanonicalType(T); 1066 if (CanT.getObjCGCAttr() == GCAttr) 1067 return T; 1068 1069 if (T->isPointerType()) { 1070 QualType Pointee = T->getAsPointerType()->getPointeeType(); 1071 if (Pointee->isPointerType()) { 1072 QualType ResultType = getObjCGCQualType(Pointee, GCAttr); 1073 return getPointerType(ResultType); 1074 } 1075 } 1076 // If we are composing extended qualifiers together, merge together into one 1077 // ExtQualType node. 1078 unsigned CVRQuals = T.getCVRQualifiers(); 1079 Type *TypeNode = T.getTypePtr(); 1080 unsigned AddressSpace = 0; 1081 1082 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) { 1083 // If this type already has an address space specified, it cannot get 1084 // another one. 1085 assert(EQT->getObjCGCAttr() == QualType::GCNone && 1086 "Type cannot be in multiple addr spaces!"); 1087 AddressSpace = EQT->getAddressSpace(); 1088 TypeNode = EQT->getBaseType(); 1089 } 1090 1091 // Check if we've already instantiated an gc qual'd type of this type. 1092 llvm::FoldingSetNodeID ID; 1093 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr); 1094 void *InsertPos = 0; 1095 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos)) 1096 return QualType(EXTQy, CVRQuals); 1097 1098 // If the base type isn't canonical, this won't be a canonical type either, 1099 // so fill in the canonical type field. 1100 // FIXME: Isn't this also not canonical if the base type is a array 1101 // or pointer type? I can't find any documentation for objc_gc, though... 1102 QualType Canonical; 1103 if (!T->isCanonical()) { 1104 Canonical = getObjCGCQualType(CanT, GCAttr); 1105 1106 // Update InsertPos, the previous call could have invalidated it. 1107 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos); 1108 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1109 } 1110 ExtQualType *New = 1111 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr); 1112 ExtQualTypes.InsertNode(New, InsertPos); 1113 Types.push_back(New); 1114 return QualType(New, CVRQuals); 1115} 1116 1117/// getComplexType - Return the uniqued reference to the type for a complex 1118/// number with the specified element type. 1119QualType ASTContext::getComplexType(QualType T) { 1120 // Unique pointers, to guarantee there is only one pointer of a particular 1121 // structure. 1122 llvm::FoldingSetNodeID ID; 1123 ComplexType::Profile(ID, T); 1124 1125 void *InsertPos = 0; 1126 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos)) 1127 return QualType(CT, 0); 1128 1129 // If the pointee type isn't canonical, this won't be a canonical type either, 1130 // so fill in the canonical type field. 1131 QualType Canonical; 1132 if (!T->isCanonical()) { 1133 Canonical = getComplexType(getCanonicalType(T)); 1134 1135 // Get the new insert position for the node we care about. 1136 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos); 1137 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1138 } 1139 ComplexType *New = new (*this,8) ComplexType(T, Canonical); 1140 Types.push_back(New); 1141 ComplexTypes.InsertNode(New, InsertPos); 1142 return QualType(New, 0); 1143} 1144 1145QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) { 1146 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ? 1147 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes; 1148 FixedWidthIntType *&Entry = Map[Width]; 1149 if (!Entry) 1150 Entry = new FixedWidthIntType(Width, Signed); 1151 return QualType(Entry, 0); 1152} 1153 1154/// getPointerType - Return the uniqued reference to the type for a pointer to 1155/// the specified type. 1156QualType ASTContext::getPointerType(QualType T) { 1157 // Unique pointers, to guarantee there is only one pointer of a particular 1158 // structure. 1159 llvm::FoldingSetNodeID ID; 1160 PointerType::Profile(ID, T); 1161 1162 void *InsertPos = 0; 1163 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 1164 return QualType(PT, 0); 1165 1166 // If the pointee type isn't canonical, this won't be a canonical type either, 1167 // so fill in the canonical type field. 1168 QualType Canonical; 1169 if (!T->isCanonical()) { 1170 Canonical = getPointerType(getCanonicalType(T)); 1171 1172 // Get the new insert position for the node we care about. 1173 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos); 1174 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1175 } 1176 PointerType *New = new (*this,8) PointerType(T, Canonical); 1177 Types.push_back(New); 1178 PointerTypes.InsertNode(New, InsertPos); 1179 return QualType(New, 0); 1180} 1181 1182/// getBlockPointerType - Return the uniqued reference to the type for 1183/// a pointer to the specified block. 1184QualType ASTContext::getBlockPointerType(QualType T) { 1185 assert(T->isFunctionType() && "block of function types only"); 1186 // Unique pointers, to guarantee there is only one block of a particular 1187 // structure. 1188 llvm::FoldingSetNodeID ID; 1189 BlockPointerType::Profile(ID, T); 1190 1191 void *InsertPos = 0; 1192 if (BlockPointerType *PT = 1193 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 1194 return QualType(PT, 0); 1195 1196 // If the block pointee type isn't canonical, this won't be a canonical 1197 // type either so fill in the canonical type field. 1198 QualType Canonical; 1199 if (!T->isCanonical()) { 1200 Canonical = getBlockPointerType(getCanonicalType(T)); 1201 1202 // Get the new insert position for the node we care about. 1203 BlockPointerType *NewIP = 1204 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 1205 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1206 } 1207 BlockPointerType *New = new (*this,8) BlockPointerType(T, Canonical); 1208 Types.push_back(New); 1209 BlockPointerTypes.InsertNode(New, InsertPos); 1210 return QualType(New, 0); 1211} 1212 1213/// getLValueReferenceType - Return the uniqued reference to the type for an 1214/// lvalue reference to the specified type. 1215QualType ASTContext::getLValueReferenceType(QualType T) { 1216 // Unique pointers, to guarantee there is only one pointer of a particular 1217 // structure. 1218 llvm::FoldingSetNodeID ID; 1219 ReferenceType::Profile(ID, T); 1220 1221 void *InsertPos = 0; 1222 if (LValueReferenceType *RT = 1223 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 1224 return QualType(RT, 0); 1225 1226 // If the referencee type isn't canonical, this won't be a canonical type 1227 // either, so fill in the canonical type field. 1228 QualType Canonical; 1229 if (!T->isCanonical()) { 1230 Canonical = getLValueReferenceType(getCanonicalType(T)); 1231 1232 // Get the new insert position for the node we care about. 1233 LValueReferenceType *NewIP = 1234 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 1235 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1236 } 1237 1238 LValueReferenceType *New = new (*this,8) LValueReferenceType(T, Canonical); 1239 Types.push_back(New); 1240 LValueReferenceTypes.InsertNode(New, InsertPos); 1241 return QualType(New, 0); 1242} 1243 1244/// getRValueReferenceType - Return the uniqued reference to the type for an 1245/// rvalue reference to the specified type. 1246QualType ASTContext::getRValueReferenceType(QualType T) { 1247 // Unique pointers, to guarantee there is only one pointer of a particular 1248 // structure. 1249 llvm::FoldingSetNodeID ID; 1250 ReferenceType::Profile(ID, T); 1251 1252 void *InsertPos = 0; 1253 if (RValueReferenceType *RT = 1254 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 1255 return QualType(RT, 0); 1256 1257 // If the referencee type isn't canonical, this won't be a canonical type 1258 // either, so fill in the canonical type field. 1259 QualType Canonical; 1260 if (!T->isCanonical()) { 1261 Canonical = getRValueReferenceType(getCanonicalType(T)); 1262 1263 // Get the new insert position for the node we care about. 1264 RValueReferenceType *NewIP = 1265 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 1266 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1267 } 1268 1269 RValueReferenceType *New = new (*this,8) RValueReferenceType(T, Canonical); 1270 Types.push_back(New); 1271 RValueReferenceTypes.InsertNode(New, InsertPos); 1272 return QualType(New, 0); 1273} 1274 1275/// getMemberPointerType - Return the uniqued reference to the type for a 1276/// member pointer to the specified type, in the specified class. 1277QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) 1278{ 1279 // Unique pointers, to guarantee there is only one pointer of a particular 1280 // structure. 1281 llvm::FoldingSetNodeID ID; 1282 MemberPointerType::Profile(ID, T, Cls); 1283 1284 void *InsertPos = 0; 1285 if (MemberPointerType *PT = 1286 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 1287 return QualType(PT, 0); 1288 1289 // If the pointee or class type isn't canonical, this won't be a canonical 1290 // type either, so fill in the canonical type field. 1291 QualType Canonical; 1292 if (!T->isCanonical()) { 1293 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls)); 1294 1295 // Get the new insert position for the node we care about. 1296 MemberPointerType *NewIP = 1297 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 1298 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1299 } 1300 MemberPointerType *New = new (*this,8) MemberPointerType(T, Cls, Canonical); 1301 Types.push_back(New); 1302 MemberPointerTypes.InsertNode(New, InsertPos); 1303 return QualType(New, 0); 1304} 1305 1306/// getConstantArrayType - Return the unique reference to the type for an 1307/// array of the specified element type. 1308QualType ASTContext::getConstantArrayType(QualType EltTy, 1309 const llvm::APInt &ArySizeIn, 1310 ArrayType::ArraySizeModifier ASM, 1311 unsigned EltTypeQuals) { 1312 assert((EltTy->isDependentType() || EltTy->isConstantSizeType()) && 1313 "Constant array of VLAs is illegal!"); 1314 1315 // Convert the array size into a canonical width matching the pointer size for 1316 // the target. 1317 llvm::APInt ArySize(ArySizeIn); 1318 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace())); 1319 1320 llvm::FoldingSetNodeID ID; 1321 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals); 1322 1323 void *InsertPos = 0; 1324 if (ConstantArrayType *ATP = 1325 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 1326 return QualType(ATP, 0); 1327 1328 // If the element type isn't canonical, this won't be a canonical type either, 1329 // so fill in the canonical type field. 1330 QualType Canonical; 1331 if (!EltTy->isCanonical()) { 1332 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize, 1333 ASM, EltTypeQuals); 1334 // Get the new insert position for the node we care about. 1335 ConstantArrayType *NewIP = 1336 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 1337 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1338 } 1339 1340 ConstantArrayType *New = 1341 new(*this,8)ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals); 1342 ConstantArrayTypes.InsertNode(New, InsertPos); 1343 Types.push_back(New); 1344 return QualType(New, 0); 1345} 1346 1347/// getVariableArrayType - Returns a non-unique reference to the type for a 1348/// variable array of the specified element type. 1349QualType ASTContext::getVariableArrayType(QualType EltTy, Expr *NumElts, 1350 ArrayType::ArraySizeModifier ASM, 1351 unsigned EltTypeQuals) { 1352 // Since we don't unique expressions, it isn't possible to unique VLA's 1353 // that have an expression provided for their size. 1354 1355 VariableArrayType *New = 1356 new(*this,8)VariableArrayType(EltTy,QualType(), NumElts, ASM, EltTypeQuals); 1357 1358 VariableArrayTypes.push_back(New); 1359 Types.push_back(New); 1360 return QualType(New, 0); 1361} 1362 1363/// getDependentSizedArrayType - Returns a non-unique reference to 1364/// the type for a dependently-sized array of the specified element 1365/// type. FIXME: We will need these to be uniqued, or at least 1366/// comparable, at some point. 1367QualType ASTContext::getDependentSizedArrayType(QualType EltTy, Expr *NumElts, 1368 ArrayType::ArraySizeModifier ASM, 1369 unsigned EltTypeQuals) { 1370 assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) && 1371 "Size must be type- or value-dependent!"); 1372 1373 // Since we don't unique expressions, it isn't possible to unique 1374 // dependently-sized array types. 1375 1376 DependentSizedArrayType *New = 1377 new (*this,8) DependentSizedArrayType(EltTy, QualType(), NumElts, 1378 ASM, EltTypeQuals); 1379 1380 DependentSizedArrayTypes.push_back(New); 1381 Types.push_back(New); 1382 return QualType(New, 0); 1383} 1384 1385QualType ASTContext::getIncompleteArrayType(QualType EltTy, 1386 ArrayType::ArraySizeModifier ASM, 1387 unsigned EltTypeQuals) { 1388 llvm::FoldingSetNodeID ID; 1389 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals); 1390 1391 void *InsertPos = 0; 1392 if (IncompleteArrayType *ATP = 1393 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 1394 return QualType(ATP, 0); 1395 1396 // If the element type isn't canonical, this won't be a canonical type 1397 // either, so fill in the canonical type field. 1398 QualType Canonical; 1399 1400 if (!EltTy->isCanonical()) { 1401 Canonical = getIncompleteArrayType(getCanonicalType(EltTy), 1402 ASM, EltTypeQuals); 1403 1404 // Get the new insert position for the node we care about. 1405 IncompleteArrayType *NewIP = 1406 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 1407 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1408 } 1409 1410 IncompleteArrayType *New = new (*this,8) IncompleteArrayType(EltTy, Canonical, 1411 ASM, EltTypeQuals); 1412 1413 IncompleteArrayTypes.InsertNode(New, InsertPos); 1414 Types.push_back(New); 1415 return QualType(New, 0); 1416} 1417 1418/// getVectorType - Return the unique reference to a vector type of 1419/// the specified element type and size. VectorType must be a built-in type. 1420QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) { 1421 BuiltinType *baseType; 1422 1423 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr()); 1424 assert(baseType != 0 && "getVectorType(): Expecting a built-in type"); 1425 1426 // Check if we've already instantiated a vector of this type. 1427 llvm::FoldingSetNodeID ID; 1428 VectorType::Profile(ID, vecType, NumElts, Type::Vector); 1429 void *InsertPos = 0; 1430 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 1431 return QualType(VTP, 0); 1432 1433 // If the element type isn't canonical, this won't be a canonical type either, 1434 // so fill in the canonical type field. 1435 QualType Canonical; 1436 if (!vecType->isCanonical()) { 1437 Canonical = getVectorType(getCanonicalType(vecType), NumElts); 1438 1439 // Get the new insert position for the node we care about. 1440 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 1441 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1442 } 1443 VectorType *New = new (*this,8) VectorType(vecType, NumElts, Canonical); 1444 VectorTypes.InsertNode(New, InsertPos); 1445 Types.push_back(New); 1446 return QualType(New, 0); 1447} 1448 1449/// getExtVectorType - Return the unique reference to an extended vector type of 1450/// the specified element type and size. VectorType must be a built-in type. 1451QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) { 1452 BuiltinType *baseType; 1453 1454 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr()); 1455 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type"); 1456 1457 // Check if we've already instantiated a vector of this type. 1458 llvm::FoldingSetNodeID ID; 1459 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector); 1460 void *InsertPos = 0; 1461 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 1462 return QualType(VTP, 0); 1463 1464 // If the element type isn't canonical, this won't be a canonical type either, 1465 // so fill in the canonical type field. 1466 QualType Canonical; 1467 if (!vecType->isCanonical()) { 1468 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts); 1469 1470 // Get the new insert position for the node we care about. 1471 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 1472 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1473 } 1474 ExtVectorType *New = new (*this,8) ExtVectorType(vecType, NumElts, Canonical); 1475 VectorTypes.InsertNode(New, InsertPos); 1476 Types.push_back(New); 1477 return QualType(New, 0); 1478} 1479 1480QualType ASTContext::getDependentSizedExtVectorType(QualType vecType, 1481 Expr *SizeExpr, 1482 SourceLocation AttrLoc) { 1483 DependentSizedExtVectorType *New = 1484 new (*this,8) DependentSizedExtVectorType(vecType, QualType(), 1485 SizeExpr, AttrLoc); 1486 1487 DependentSizedExtVectorTypes.push_back(New); 1488 Types.push_back(New); 1489 return QualType(New, 0); 1490} 1491 1492/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'. 1493/// 1494QualType ASTContext::getFunctionNoProtoType(QualType ResultTy) { 1495 // Unique functions, to guarantee there is only one function of a particular 1496 // structure. 1497 llvm::FoldingSetNodeID ID; 1498 FunctionNoProtoType::Profile(ID, ResultTy); 1499 1500 void *InsertPos = 0; 1501 if (FunctionNoProtoType *FT = 1502 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 1503 return QualType(FT, 0); 1504 1505 QualType Canonical; 1506 if (!ResultTy->isCanonical()) { 1507 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy)); 1508 1509 // Get the new insert position for the node we care about. 1510 FunctionNoProtoType *NewIP = 1511 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 1512 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1513 } 1514 1515 FunctionNoProtoType *New =new(*this,8)FunctionNoProtoType(ResultTy,Canonical); 1516 Types.push_back(New); 1517 FunctionNoProtoTypes.InsertNode(New, InsertPos); 1518 return QualType(New, 0); 1519} 1520 1521/// getFunctionType - Return a normal function type with a typed argument 1522/// list. isVariadic indicates whether the argument list includes '...'. 1523QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray, 1524 unsigned NumArgs, bool isVariadic, 1525 unsigned TypeQuals, bool hasExceptionSpec, 1526 bool hasAnyExceptionSpec, unsigned NumExs, 1527 const QualType *ExArray) { 1528 // Unique functions, to guarantee there is only one function of a particular 1529 // structure. 1530 llvm::FoldingSetNodeID ID; 1531 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic, 1532 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec, 1533 NumExs, ExArray); 1534 1535 void *InsertPos = 0; 1536 if (FunctionProtoType *FTP = 1537 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 1538 return QualType(FTP, 0); 1539 1540 // Determine whether the type being created is already canonical or not. 1541 bool isCanonical = ResultTy->isCanonical(); 1542 if (hasExceptionSpec) 1543 isCanonical = false; 1544 for (unsigned i = 0; i != NumArgs && isCanonical; ++i) 1545 if (!ArgArray[i]->isCanonical()) 1546 isCanonical = false; 1547 1548 // If this type isn't canonical, get the canonical version of it. 1549 // The exception spec is not part of the canonical type. 1550 QualType Canonical; 1551 if (!isCanonical) { 1552 llvm::SmallVector<QualType, 16> CanonicalArgs; 1553 CanonicalArgs.reserve(NumArgs); 1554 for (unsigned i = 0; i != NumArgs; ++i) 1555 CanonicalArgs.push_back(getCanonicalType(ArgArray[i])); 1556 1557 Canonical = getFunctionType(getCanonicalType(ResultTy), 1558 CanonicalArgs.data(), NumArgs, 1559 isVariadic, TypeQuals); 1560 1561 // Get the new insert position for the node we care about. 1562 FunctionProtoType *NewIP = 1563 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 1564 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1565 } 1566 1567 // FunctionProtoType objects are allocated with extra bytes after them 1568 // for two variable size arrays (for parameter and exception types) at the 1569 // end of them. 1570 FunctionProtoType *FTP = 1571 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) + 1572 NumArgs*sizeof(QualType) + 1573 NumExs*sizeof(QualType), 8); 1574 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic, 1575 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec, 1576 ExArray, NumExs, Canonical); 1577 Types.push_back(FTP); 1578 FunctionProtoTypes.InsertNode(FTP, InsertPos); 1579 return QualType(FTP, 0); 1580} 1581 1582/// getTypeDeclType - Return the unique reference to the type for the 1583/// specified type declaration. 1584QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) { 1585 assert(Decl && "Passed null for Decl param"); 1586 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 1587 1588 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl)) 1589 return getTypedefType(Typedef); 1590 else if (isa<TemplateTypeParmDecl>(Decl)) { 1591 assert(false && "Template type parameter types are always available."); 1592 } else if (ObjCInterfaceDecl *ObjCInterface = dyn_cast<ObjCInterfaceDecl>(Decl)) 1593 return getObjCInterfaceType(ObjCInterface); 1594 1595 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) { 1596 if (PrevDecl) 1597 Decl->TypeForDecl = PrevDecl->TypeForDecl; 1598 else 1599 Decl->TypeForDecl = new (*this,8) RecordType(Record); 1600 } 1601 else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) { 1602 if (PrevDecl) 1603 Decl->TypeForDecl = PrevDecl->TypeForDecl; 1604 else 1605 Decl->TypeForDecl = new (*this,8) EnumType(Enum); 1606 } 1607 else 1608 assert(false && "TypeDecl without a type?"); 1609 1610 if (!PrevDecl) Types.push_back(Decl->TypeForDecl); 1611 return QualType(Decl->TypeForDecl, 0); 1612} 1613 1614/// getTypedefType - Return the unique reference to the type for the 1615/// specified typename decl. 1616QualType ASTContext::getTypedefType(TypedefDecl *Decl) { 1617 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 1618 1619 QualType Canonical = getCanonicalType(Decl->getUnderlyingType()); 1620 Decl->TypeForDecl = new(*this,8) TypedefType(Type::Typedef, Decl, Canonical); 1621 Types.push_back(Decl->TypeForDecl); 1622 return QualType(Decl->TypeForDecl, 0); 1623} 1624 1625/// getObjCInterfaceType - Return the unique reference to the type for the 1626/// specified ObjC interface decl. 1627QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) { 1628 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 1629 1630 ObjCInterfaceDecl *OID = const_cast<ObjCInterfaceDecl*>(Decl); 1631 Decl->TypeForDecl = new(*this,8) ObjCInterfaceType(Type::ObjCInterface, OID); 1632 Types.push_back(Decl->TypeForDecl); 1633 return QualType(Decl->TypeForDecl, 0); 1634} 1635 1636/// \brief Retrieve the template type parameter type for a template 1637/// parameter or parameter pack with the given depth, index, and (optionally) 1638/// name. 1639QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index, 1640 bool ParameterPack, 1641 IdentifierInfo *Name) { 1642 llvm::FoldingSetNodeID ID; 1643 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name); 1644 void *InsertPos = 0; 1645 TemplateTypeParmType *TypeParm 1646 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 1647 1648 if (TypeParm) 1649 return QualType(TypeParm, 0); 1650 1651 if (Name) { 1652 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack); 1653 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack, 1654 Name, Canon); 1655 } else 1656 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack); 1657 1658 Types.push_back(TypeParm); 1659 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos); 1660 1661 return QualType(TypeParm, 0); 1662} 1663 1664QualType 1665ASTContext::getTemplateSpecializationType(TemplateName Template, 1666 const TemplateArgument *Args, 1667 unsigned NumArgs, 1668 QualType Canon) { 1669 if (!Canon.isNull()) 1670 Canon = getCanonicalType(Canon); 1671 1672 llvm::FoldingSetNodeID ID; 1673 TemplateSpecializationType::Profile(ID, Template, Args, NumArgs); 1674 1675 void *InsertPos = 0; 1676 TemplateSpecializationType *Spec 1677 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 1678 1679 if (Spec) 1680 return QualType(Spec, 0); 1681 1682 void *Mem = Allocate((sizeof(TemplateSpecializationType) + 1683 sizeof(TemplateArgument) * NumArgs), 1684 8); 1685 Spec = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, Canon); 1686 Types.push_back(Spec); 1687 TemplateSpecializationTypes.InsertNode(Spec, InsertPos); 1688 1689 return QualType(Spec, 0); 1690} 1691 1692QualType 1693ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS, 1694 QualType NamedType) { 1695 llvm::FoldingSetNodeID ID; 1696 QualifiedNameType::Profile(ID, NNS, NamedType); 1697 1698 void *InsertPos = 0; 1699 QualifiedNameType *T 1700 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos); 1701 if (T) 1702 return QualType(T, 0); 1703 1704 T = new (*this) QualifiedNameType(NNS, NamedType, 1705 getCanonicalType(NamedType)); 1706 Types.push_back(T); 1707 QualifiedNameTypes.InsertNode(T, InsertPos); 1708 return QualType(T, 0); 1709} 1710 1711QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS, 1712 const IdentifierInfo *Name, 1713 QualType Canon) { 1714 assert(NNS->isDependent() && "nested-name-specifier must be dependent"); 1715 1716 if (Canon.isNull()) { 1717 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 1718 if (CanonNNS != NNS) 1719 Canon = getTypenameType(CanonNNS, Name); 1720 } 1721 1722 llvm::FoldingSetNodeID ID; 1723 TypenameType::Profile(ID, NNS, Name); 1724 1725 void *InsertPos = 0; 1726 TypenameType *T 1727 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos); 1728 if (T) 1729 return QualType(T, 0); 1730 1731 T = new (*this) TypenameType(NNS, Name, Canon); 1732 Types.push_back(T); 1733 TypenameTypes.InsertNode(T, InsertPos); 1734 return QualType(T, 0); 1735} 1736 1737QualType 1738ASTContext::getTypenameType(NestedNameSpecifier *NNS, 1739 const TemplateSpecializationType *TemplateId, 1740 QualType Canon) { 1741 assert(NNS->isDependent() && "nested-name-specifier must be dependent"); 1742 1743 if (Canon.isNull()) { 1744 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 1745 QualType CanonType = getCanonicalType(QualType(TemplateId, 0)); 1746 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) { 1747 const TemplateSpecializationType *CanonTemplateId 1748 = CanonType->getAsTemplateSpecializationType(); 1749 assert(CanonTemplateId && 1750 "Canonical type must also be a template specialization type"); 1751 Canon = getTypenameType(CanonNNS, CanonTemplateId); 1752 } 1753 } 1754 1755 llvm::FoldingSetNodeID ID; 1756 TypenameType::Profile(ID, NNS, TemplateId); 1757 1758 void *InsertPos = 0; 1759 TypenameType *T 1760 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos); 1761 if (T) 1762 return QualType(T, 0); 1763 1764 T = new (*this) TypenameType(NNS, TemplateId, Canon); 1765 Types.push_back(T); 1766 TypenameTypes.InsertNode(T, InsertPos); 1767 return QualType(T, 0); 1768} 1769 1770/// CmpProtocolNames - Comparison predicate for sorting protocols 1771/// alphabetically. 1772static bool CmpProtocolNames(const ObjCProtocolDecl *LHS, 1773 const ObjCProtocolDecl *RHS) { 1774 return LHS->getDeclName() < RHS->getDeclName(); 1775} 1776 1777static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols, 1778 unsigned &NumProtocols) { 1779 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols; 1780 1781 // Sort protocols, keyed by name. 1782 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames); 1783 1784 // Remove duplicates. 1785 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd); 1786 NumProtocols = ProtocolsEnd-Protocols; 1787} 1788 1789/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for 1790/// the given interface decl and the conforming protocol list. 1791QualType ASTContext::getObjCObjectPointerType(ObjCInterfaceDecl *Decl, 1792 ObjCProtocolDecl **Protocols, 1793 unsigned NumProtocols) { 1794 // Sort the protocol list alphabetically to canonicalize it. 1795 if (NumProtocols) 1796 SortAndUniqueProtocols(Protocols, NumProtocols); 1797 1798 llvm::FoldingSetNodeID ID; 1799 ObjCObjectPointerType::Profile(ID, Decl, Protocols, NumProtocols); 1800 1801 void *InsertPos = 0; 1802 if (ObjCObjectPointerType *QT = 1803 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 1804 return QualType(QT, 0); 1805 1806 // No Match; 1807 ObjCObjectPointerType *QType = 1808 new (*this,8) ObjCObjectPointerType(Decl, Protocols, NumProtocols); 1809 1810 Types.push_back(QType); 1811 ObjCObjectPointerTypes.InsertNode(QType, InsertPos); 1812 return QualType(QType, 0); 1813} 1814 1815/// getObjCQualifiedInterfaceType - Return a ObjCQualifiedInterfaceType type for 1816/// the given interface decl and the conforming protocol list. 1817QualType ASTContext::getObjCQualifiedInterfaceType(ObjCInterfaceDecl *Decl, 1818 ObjCProtocolDecl **Protocols, unsigned NumProtocols) { 1819 // Sort the protocol list alphabetically to canonicalize it. 1820 SortAndUniqueProtocols(Protocols, NumProtocols); 1821 1822 llvm::FoldingSetNodeID ID; 1823 ObjCQualifiedInterfaceType::Profile(ID, Decl, Protocols, NumProtocols); 1824 1825 void *InsertPos = 0; 1826 if (ObjCQualifiedInterfaceType *QT = 1827 ObjCQualifiedInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos)) 1828 return QualType(QT, 0); 1829 1830 // No Match; 1831 ObjCQualifiedInterfaceType *QType = 1832 new (*this,8) ObjCQualifiedInterfaceType(Decl, Protocols, NumProtocols); 1833 1834 Types.push_back(QType); 1835 ObjCQualifiedInterfaceTypes.InsertNode(QType, InsertPos); 1836 return QualType(QType, 0); 1837} 1838 1839/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique 1840/// TypeOfExprType AST's (since expression's are never shared). For example, 1841/// multiple declarations that refer to "typeof(x)" all contain different 1842/// DeclRefExpr's. This doesn't effect the type checker, since it operates 1843/// on canonical type's (which are always unique). 1844QualType ASTContext::getTypeOfExprType(Expr *tofExpr) { 1845 QualType Canonical = getCanonicalType(tofExpr->getType()); 1846 TypeOfExprType *toe = new (*this,8) TypeOfExprType(tofExpr, Canonical); 1847 Types.push_back(toe); 1848 return QualType(toe, 0); 1849} 1850 1851/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique 1852/// TypeOfType AST's. The only motivation to unique these nodes would be 1853/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be 1854/// an issue. This doesn't effect the type checker, since it operates 1855/// on canonical type's (which are always unique). 1856QualType ASTContext::getTypeOfType(QualType tofType) { 1857 QualType Canonical = getCanonicalType(tofType); 1858 TypeOfType *tot = new (*this,8) TypeOfType(tofType, Canonical); 1859 Types.push_back(tot); 1860 return QualType(tot, 0); 1861} 1862 1863/// getDecltypeForExpr - Given an expr, will return the decltype for that 1864/// expression, according to the rules in C++0x [dcl.type.simple]p4 1865static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) { 1866 if (e->isTypeDependent()) 1867 return Context.DependentTy; 1868 1869 // If e is an id expression or a class member access, decltype(e) is defined 1870 // as the type of the entity named by e. 1871 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) { 1872 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) 1873 return VD->getType(); 1874 } 1875 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) { 1876 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 1877 return FD->getType(); 1878 } 1879 // If e is a function call or an invocation of an overloaded operator, 1880 // (parentheses around e are ignored), decltype(e) is defined as the 1881 // return type of that function. 1882 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens())) 1883 return CE->getCallReturnType(); 1884 1885 QualType T = e->getType(); 1886 1887 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is 1888 // defined as T&, otherwise decltype(e) is defined as T. 1889 if (e->isLvalue(Context) == Expr::LV_Valid) 1890 T = Context.getLValueReferenceType(T); 1891 1892 return T; 1893} 1894 1895/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique 1896/// DecltypeType AST's. The only motivation to unique these nodes would be 1897/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be 1898/// an issue. This doesn't effect the type checker, since it operates 1899/// on canonical type's (which are always unique). 1900QualType ASTContext::getDecltypeType(Expr *e) { 1901 QualType T = getDecltypeForExpr(e, *this); 1902 DecltypeType *dt = new (*this, 8) DecltypeType(e, getCanonicalType(T)); 1903 Types.push_back(dt); 1904 return QualType(dt, 0); 1905} 1906 1907/// getTagDeclType - Return the unique reference to the type for the 1908/// specified TagDecl (struct/union/class/enum) decl. 1909QualType ASTContext::getTagDeclType(TagDecl *Decl) { 1910 assert (Decl); 1911 return getTypeDeclType(Decl); 1912} 1913 1914/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result 1915/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and 1916/// needs to agree with the definition in <stddef.h>. 1917QualType ASTContext::getSizeType() const { 1918 return getFromTargetType(Target.getSizeType()); 1919} 1920 1921/// getSignedWCharType - Return the type of "signed wchar_t". 1922/// Used when in C++, as a GCC extension. 1923QualType ASTContext::getSignedWCharType() const { 1924 // FIXME: derive from "Target" ? 1925 return WCharTy; 1926} 1927 1928/// getUnsignedWCharType - Return the type of "unsigned wchar_t". 1929/// Used when in C++, as a GCC extension. 1930QualType ASTContext::getUnsignedWCharType() const { 1931 // FIXME: derive from "Target" ? 1932 return UnsignedIntTy; 1933} 1934 1935/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?) 1936/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9). 1937QualType ASTContext::getPointerDiffType() const { 1938 return getFromTargetType(Target.getPtrDiffType(0)); 1939} 1940 1941//===----------------------------------------------------------------------===// 1942// Type Operators 1943//===----------------------------------------------------------------------===// 1944 1945/// getCanonicalType - Return the canonical (structural) type corresponding to 1946/// the specified potentially non-canonical type. The non-canonical version 1947/// of a type may have many "decorated" versions of types. Decorators can 1948/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed 1949/// to be free of any of these, allowing two canonical types to be compared 1950/// for exact equality with a simple pointer comparison. 1951QualType ASTContext::getCanonicalType(QualType T) { 1952 QualType CanType = T.getTypePtr()->getCanonicalTypeInternal(); 1953 1954 // If the result has type qualifiers, make sure to canonicalize them as well. 1955 unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers(); 1956 if (TypeQuals == 0) return CanType; 1957 1958 // If the type qualifiers are on an array type, get the canonical type of the 1959 // array with the qualifiers applied to the element type. 1960 ArrayType *AT = dyn_cast<ArrayType>(CanType); 1961 if (!AT) 1962 return CanType.getQualifiedType(TypeQuals); 1963 1964 // Get the canonical version of the element with the extra qualifiers on it. 1965 // This can recursively sink qualifiers through multiple levels of arrays. 1966 QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals); 1967 NewEltTy = getCanonicalType(NewEltTy); 1968 1969 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) 1970 return getConstantArrayType(NewEltTy, CAT->getSize(),CAT->getSizeModifier(), 1971 CAT->getIndexTypeQualifier()); 1972 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) 1973 return getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(), 1974 IAT->getIndexTypeQualifier()); 1975 1976 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT)) 1977 return getDependentSizedArrayType(NewEltTy, DSAT->getSizeExpr(), 1978 DSAT->getSizeModifier(), 1979 DSAT->getIndexTypeQualifier()); 1980 1981 VariableArrayType *VAT = cast<VariableArrayType>(AT); 1982 return getVariableArrayType(NewEltTy, VAT->getSizeExpr(), 1983 VAT->getSizeModifier(), 1984 VAT->getIndexTypeQualifier()); 1985} 1986 1987Decl *ASTContext::getCanonicalDecl(Decl *D) { 1988 if (!D) 1989 return 0; 1990 1991 if (TagDecl *Tag = dyn_cast<TagDecl>(D)) { 1992 QualType T = getTagDeclType(Tag); 1993 return cast<TagDecl>(cast<TagType>(T.getTypePtr()->CanonicalType) 1994 ->getDecl()); 1995 } 1996 1997 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(D)) { 1998 while (Template->getPreviousDeclaration()) 1999 Template = Template->getPreviousDeclaration(); 2000 return Template; 2001 } 2002 2003 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 2004 while (Function->getPreviousDeclaration()) 2005 Function = Function->getPreviousDeclaration(); 2006 return const_cast<FunctionDecl *>(Function); 2007 } 2008 2009 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) { 2010 while (FunTmpl->getPreviousDeclaration()) 2011 FunTmpl = FunTmpl->getPreviousDeclaration(); 2012 return FunTmpl; 2013 } 2014 2015 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) { 2016 while (Var->getPreviousDeclaration()) 2017 Var = Var->getPreviousDeclaration(); 2018 return const_cast<VarDecl *>(Var); 2019 } 2020 2021 return D; 2022} 2023 2024TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) { 2025 // If this template name refers to a template, the canonical 2026 // template name merely stores the template itself. 2027 if (TemplateDecl *Template = Name.getAsTemplateDecl()) 2028 return TemplateName(cast<TemplateDecl>(getCanonicalDecl(Template))); 2029 2030 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 2031 assert(DTN && "Non-dependent template names must refer to template decls."); 2032 return DTN->CanonicalTemplateName; 2033} 2034 2035NestedNameSpecifier * 2036ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) { 2037 if (!NNS) 2038 return 0; 2039 2040 switch (NNS->getKind()) { 2041 case NestedNameSpecifier::Identifier: 2042 // Canonicalize the prefix but keep the identifier the same. 2043 return NestedNameSpecifier::Create(*this, 2044 getCanonicalNestedNameSpecifier(NNS->getPrefix()), 2045 NNS->getAsIdentifier()); 2046 2047 case NestedNameSpecifier::Namespace: 2048 // A namespace is canonical; build a nested-name-specifier with 2049 // this namespace and no prefix. 2050 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace()); 2051 2052 case NestedNameSpecifier::TypeSpec: 2053 case NestedNameSpecifier::TypeSpecWithTemplate: { 2054 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0)); 2055 NestedNameSpecifier *Prefix = 0; 2056 2057 // FIXME: This isn't the right check! 2058 if (T->isDependentType()) 2059 Prefix = getCanonicalNestedNameSpecifier(NNS->getPrefix()); 2060 2061 return NestedNameSpecifier::Create(*this, Prefix, 2062 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate, 2063 T.getTypePtr()); 2064 } 2065 2066 case NestedNameSpecifier::Global: 2067 // The global specifier is canonical and unique. 2068 return NNS; 2069 } 2070 2071 // Required to silence a GCC warning 2072 return 0; 2073} 2074 2075 2076const ArrayType *ASTContext::getAsArrayType(QualType T) { 2077 // Handle the non-qualified case efficiently. 2078 if (T.getCVRQualifiers() == 0) { 2079 // Handle the common positive case fast. 2080 if (const ArrayType *AT = dyn_cast<ArrayType>(T)) 2081 return AT; 2082 } 2083 2084 // Handle the common negative case fast, ignoring CVR qualifiers. 2085 QualType CType = T->getCanonicalTypeInternal(); 2086 2087 // Make sure to look through type qualifiers (like ExtQuals) for the negative 2088 // test. 2089 if (!isa<ArrayType>(CType) && 2090 !isa<ArrayType>(CType.getUnqualifiedType())) 2091 return 0; 2092 2093 // Apply any CVR qualifiers from the array type to the element type. This 2094 // implements C99 6.7.3p8: "If the specification of an array type includes 2095 // any type qualifiers, the element type is so qualified, not the array type." 2096 2097 // If we get here, we either have type qualifiers on the type, or we have 2098 // sugar such as a typedef in the way. If we have type qualifiers on the type 2099 // we must propagate them down into the elemeng type. 2100 unsigned CVRQuals = T.getCVRQualifiers(); 2101 unsigned AddrSpace = 0; 2102 Type *Ty = T.getTypePtr(); 2103 2104 // Rip through ExtQualType's and typedefs to get to a concrete type. 2105 while (1) { 2106 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty)) { 2107 AddrSpace = EXTQT->getAddressSpace(); 2108 Ty = EXTQT->getBaseType(); 2109 } else { 2110 T = Ty->getDesugaredType(); 2111 if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0) 2112 break; 2113 CVRQuals |= T.getCVRQualifiers(); 2114 Ty = T.getTypePtr(); 2115 } 2116 } 2117 2118 // If we have a simple case, just return now. 2119 const ArrayType *ATy = dyn_cast<ArrayType>(Ty); 2120 if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0)) 2121 return ATy; 2122 2123 // Otherwise, we have an array and we have qualifiers on it. Push the 2124 // qualifiers into the array element type and return a new array type. 2125 // Get the canonical version of the element with the extra qualifiers on it. 2126 // This can recursively sink qualifiers through multiple levels of arrays. 2127 QualType NewEltTy = ATy->getElementType(); 2128 if (AddrSpace) 2129 NewEltTy = getAddrSpaceQualType(NewEltTy, AddrSpace); 2130 NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals); 2131 2132 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy)) 2133 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(), 2134 CAT->getSizeModifier(), 2135 CAT->getIndexTypeQualifier())); 2136 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy)) 2137 return cast<ArrayType>(getIncompleteArrayType(NewEltTy, 2138 IAT->getSizeModifier(), 2139 IAT->getIndexTypeQualifier())); 2140 2141 if (const DependentSizedArrayType *DSAT 2142 = dyn_cast<DependentSizedArrayType>(ATy)) 2143 return cast<ArrayType>( 2144 getDependentSizedArrayType(NewEltTy, 2145 DSAT->getSizeExpr(), 2146 DSAT->getSizeModifier(), 2147 DSAT->getIndexTypeQualifier())); 2148 2149 const VariableArrayType *VAT = cast<VariableArrayType>(ATy); 2150 return cast<ArrayType>(getVariableArrayType(NewEltTy, VAT->getSizeExpr(), 2151 VAT->getSizeModifier(), 2152 VAT->getIndexTypeQualifier())); 2153} 2154 2155 2156/// getArrayDecayedType - Return the properly qualified result of decaying the 2157/// specified array type to a pointer. This operation is non-trivial when 2158/// handling typedefs etc. The canonical type of "T" must be an array type, 2159/// this returns a pointer to a properly qualified element of the array. 2160/// 2161/// See C99 6.7.5.3p7 and C99 6.3.2.1p3. 2162QualType ASTContext::getArrayDecayedType(QualType Ty) { 2163 // Get the element type with 'getAsArrayType' so that we don't lose any 2164 // typedefs in the element type of the array. This also handles propagation 2165 // of type qualifiers from the array type into the element type if present 2166 // (C99 6.7.3p8). 2167 const ArrayType *PrettyArrayType = getAsArrayType(Ty); 2168 assert(PrettyArrayType && "Not an array type!"); 2169 2170 QualType PtrTy = getPointerType(PrettyArrayType->getElementType()); 2171 2172 // int x[restrict 4] -> int *restrict 2173 return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier()); 2174} 2175 2176QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) { 2177 QualType ElemTy = VAT->getElementType(); 2178 2179 if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy)) 2180 return getBaseElementType(VAT); 2181 2182 return ElemTy; 2183} 2184 2185/// getFloatingRank - Return a relative rank for floating point types. 2186/// This routine will assert if passed a built-in type that isn't a float. 2187static FloatingRank getFloatingRank(QualType T) { 2188 if (const ComplexType *CT = T->getAsComplexType()) 2189 return getFloatingRank(CT->getElementType()); 2190 2191 assert(T->getAsBuiltinType() && "getFloatingRank(): not a floating type"); 2192 switch (T->getAsBuiltinType()->getKind()) { 2193 default: assert(0 && "getFloatingRank(): not a floating type"); 2194 case BuiltinType::Float: return FloatRank; 2195 case BuiltinType::Double: return DoubleRank; 2196 case BuiltinType::LongDouble: return LongDoubleRank; 2197 } 2198} 2199 2200/// getFloatingTypeOfSizeWithinDomain - Returns a real floating 2201/// point or a complex type (based on typeDomain/typeSize). 2202/// 'typeDomain' is a real floating point or complex type. 2203/// 'typeSize' is a real floating point or complex type. 2204QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size, 2205 QualType Domain) const { 2206 FloatingRank EltRank = getFloatingRank(Size); 2207 if (Domain->isComplexType()) { 2208 switch (EltRank) { 2209 default: assert(0 && "getFloatingRank(): illegal value for rank"); 2210 case FloatRank: return FloatComplexTy; 2211 case DoubleRank: return DoubleComplexTy; 2212 case LongDoubleRank: return LongDoubleComplexTy; 2213 } 2214 } 2215 2216 assert(Domain->isRealFloatingType() && "Unknown domain!"); 2217 switch (EltRank) { 2218 default: assert(0 && "getFloatingRank(): illegal value for rank"); 2219 case FloatRank: return FloatTy; 2220 case DoubleRank: return DoubleTy; 2221 case LongDoubleRank: return LongDoubleTy; 2222 } 2223} 2224 2225/// getFloatingTypeOrder - Compare the rank of the two specified floating 2226/// point types, ignoring the domain of the type (i.e. 'double' == 2227/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If 2228/// LHS < RHS, return -1. 2229int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) { 2230 FloatingRank LHSR = getFloatingRank(LHS); 2231 FloatingRank RHSR = getFloatingRank(RHS); 2232 2233 if (LHSR == RHSR) 2234 return 0; 2235 if (LHSR > RHSR) 2236 return 1; 2237 return -1; 2238} 2239 2240/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This 2241/// routine will assert if passed a built-in type that isn't an integer or enum, 2242/// or if it is not canonicalized. 2243unsigned ASTContext::getIntegerRank(Type *T) { 2244 assert(T->isCanonical() && "T should be canonicalized"); 2245 if (EnumType* ET = dyn_cast<EnumType>(T)) 2246 T = ET->getDecl()->getIntegerType().getTypePtr(); 2247 2248 // There are two things which impact the integer rank: the width, and 2249 // the ordering of builtins. The builtin ordering is encoded in the 2250 // bottom three bits; the width is encoded in the bits above that. 2251 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) 2252 return FWIT->getWidth() << 3; 2253 2254 switch (cast<BuiltinType>(T)->getKind()) { 2255 default: assert(0 && "getIntegerRank(): not a built-in integer"); 2256 case BuiltinType::Bool: 2257 return 1 + (getIntWidth(BoolTy) << 3); 2258 case BuiltinType::Char_S: 2259 case BuiltinType::Char_U: 2260 case BuiltinType::SChar: 2261 case BuiltinType::UChar: 2262 return 2 + (getIntWidth(CharTy) << 3); 2263 case BuiltinType::Short: 2264 case BuiltinType::UShort: 2265 return 3 + (getIntWidth(ShortTy) << 3); 2266 case BuiltinType::Int: 2267 case BuiltinType::UInt: 2268 return 4 + (getIntWidth(IntTy) << 3); 2269 case BuiltinType::Long: 2270 case BuiltinType::ULong: 2271 return 5 + (getIntWidth(LongTy) << 3); 2272 case BuiltinType::LongLong: 2273 case BuiltinType::ULongLong: 2274 return 6 + (getIntWidth(LongLongTy) << 3); 2275 case BuiltinType::Int128: 2276 case BuiltinType::UInt128: 2277 return 7 + (getIntWidth(Int128Ty) << 3); 2278 } 2279} 2280 2281/// getIntegerTypeOrder - Returns the highest ranked integer type: 2282/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If 2283/// LHS < RHS, return -1. 2284int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) { 2285 Type *LHSC = getCanonicalType(LHS).getTypePtr(); 2286 Type *RHSC = getCanonicalType(RHS).getTypePtr(); 2287 if (LHSC == RHSC) return 0; 2288 2289 bool LHSUnsigned = LHSC->isUnsignedIntegerType(); 2290 bool RHSUnsigned = RHSC->isUnsignedIntegerType(); 2291 2292 unsigned LHSRank = getIntegerRank(LHSC); 2293 unsigned RHSRank = getIntegerRank(RHSC); 2294 2295 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned. 2296 if (LHSRank == RHSRank) return 0; 2297 return LHSRank > RHSRank ? 1 : -1; 2298 } 2299 2300 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa. 2301 if (LHSUnsigned) { 2302 // If the unsigned [LHS] type is larger, return it. 2303 if (LHSRank >= RHSRank) 2304 return 1; 2305 2306 // If the signed type can represent all values of the unsigned type, it 2307 // wins. Because we are dealing with 2's complement and types that are 2308 // powers of two larger than each other, this is always safe. 2309 return -1; 2310 } 2311 2312 // If the unsigned [RHS] type is larger, return it. 2313 if (RHSRank >= LHSRank) 2314 return -1; 2315 2316 // If the signed type can represent all values of the unsigned type, it 2317 // wins. Because we are dealing with 2's complement and types that are 2318 // powers of two larger than each other, this is always safe. 2319 return 1; 2320} 2321 2322// getCFConstantStringType - Return the type used for constant CFStrings. 2323QualType ASTContext::getCFConstantStringType() { 2324 if (!CFConstantStringTypeDecl) { 2325 CFConstantStringTypeDecl = 2326 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(), 2327 &Idents.get("NSConstantString")); 2328 QualType FieldTypes[4]; 2329 2330 // const int *isa; 2331 FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const)); 2332 // int flags; 2333 FieldTypes[1] = IntTy; 2334 // const char *str; 2335 FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const)); 2336 // long length; 2337 FieldTypes[3] = LongTy; 2338 2339 // Create fields 2340 for (unsigned i = 0; i < 4; ++i) { 2341 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl, 2342 SourceLocation(), 0, 2343 FieldTypes[i], /*BitWidth=*/0, 2344 /*Mutable=*/false); 2345 CFConstantStringTypeDecl->addDecl(Field); 2346 } 2347 2348 CFConstantStringTypeDecl->completeDefinition(*this); 2349 } 2350 2351 return getTagDeclType(CFConstantStringTypeDecl); 2352} 2353 2354void ASTContext::setCFConstantStringType(QualType T) { 2355 const RecordType *Rec = T->getAsRecordType(); 2356 assert(Rec && "Invalid CFConstantStringType"); 2357 CFConstantStringTypeDecl = Rec->getDecl(); 2358} 2359 2360QualType ASTContext::getObjCFastEnumerationStateType() 2361{ 2362 if (!ObjCFastEnumerationStateTypeDecl) { 2363 ObjCFastEnumerationStateTypeDecl = 2364 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(), 2365 &Idents.get("__objcFastEnumerationState")); 2366 2367 QualType FieldTypes[] = { 2368 UnsignedLongTy, 2369 getPointerType(ObjCIdType), 2370 getPointerType(UnsignedLongTy), 2371 getConstantArrayType(UnsignedLongTy, 2372 llvm::APInt(32, 5), ArrayType::Normal, 0) 2373 }; 2374 2375 for (size_t i = 0; i < 4; ++i) { 2376 FieldDecl *Field = FieldDecl::Create(*this, 2377 ObjCFastEnumerationStateTypeDecl, 2378 SourceLocation(), 0, 2379 FieldTypes[i], /*BitWidth=*/0, 2380 /*Mutable=*/false); 2381 ObjCFastEnumerationStateTypeDecl->addDecl(Field); 2382 } 2383 2384 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this); 2385 } 2386 2387 return getTagDeclType(ObjCFastEnumerationStateTypeDecl); 2388} 2389 2390void ASTContext::setObjCFastEnumerationStateType(QualType T) { 2391 const RecordType *Rec = T->getAsRecordType(); 2392 assert(Rec && "Invalid ObjCFAstEnumerationStateType"); 2393 ObjCFastEnumerationStateTypeDecl = Rec->getDecl(); 2394} 2395 2396// This returns true if a type has been typedefed to BOOL: 2397// typedef <type> BOOL; 2398static bool isTypeTypedefedAsBOOL(QualType T) { 2399 if (const TypedefType *TT = dyn_cast<TypedefType>(T)) 2400 if (IdentifierInfo *II = TT->getDecl()->getIdentifier()) 2401 return II->isStr("BOOL"); 2402 2403 return false; 2404} 2405 2406/// getObjCEncodingTypeSize returns size of type for objective-c encoding 2407/// purpose. 2408int ASTContext::getObjCEncodingTypeSize(QualType type) { 2409 uint64_t sz = getTypeSize(type); 2410 2411 // Make all integer and enum types at least as large as an int 2412 if (sz > 0 && type->isIntegralType()) 2413 sz = std::max(sz, getTypeSize(IntTy)); 2414 // Treat arrays as pointers, since that's how they're passed in. 2415 else if (type->isArrayType()) 2416 sz = getTypeSize(VoidPtrTy); 2417 return sz / getTypeSize(CharTy); 2418} 2419 2420/// getObjCEncodingForMethodDecl - Return the encoded type for this method 2421/// declaration. 2422void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, 2423 std::string& S) { 2424 // FIXME: This is not very efficient. 2425 // Encode type qualifer, 'in', 'inout', etc. for the return type. 2426 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S); 2427 // Encode result type. 2428 getObjCEncodingForType(Decl->getResultType(), S); 2429 // Compute size of all parameters. 2430 // Start with computing size of a pointer in number of bytes. 2431 // FIXME: There might(should) be a better way of doing this computation! 2432 SourceLocation Loc; 2433 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy); 2434 // The first two arguments (self and _cmd) are pointers; account for 2435 // their size. 2436 int ParmOffset = 2 * PtrSize; 2437 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(), 2438 E = Decl->param_end(); PI != E; ++PI) { 2439 QualType PType = (*PI)->getType(); 2440 int sz = getObjCEncodingTypeSize(PType); 2441 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type"); 2442 ParmOffset += sz; 2443 } 2444 S += llvm::utostr(ParmOffset); 2445 S += "@0:"; 2446 S += llvm::utostr(PtrSize); 2447 2448 // Argument types. 2449 ParmOffset = 2 * PtrSize; 2450 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(), 2451 E = Decl->param_end(); PI != E; ++PI) { 2452 ParmVarDecl *PVDecl = *PI; 2453 QualType PType = PVDecl->getOriginalType(); 2454 if (const ArrayType *AT = 2455 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 2456 // Use array's original type only if it has known number of 2457 // elements. 2458 if (!isa<ConstantArrayType>(AT)) 2459 PType = PVDecl->getType(); 2460 } else if (PType->isFunctionType()) 2461 PType = PVDecl->getType(); 2462 // Process argument qualifiers for user supplied arguments; such as, 2463 // 'in', 'inout', etc. 2464 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S); 2465 getObjCEncodingForType(PType, S); 2466 S += llvm::utostr(ParmOffset); 2467 ParmOffset += getObjCEncodingTypeSize(PType); 2468 } 2469} 2470 2471/// getObjCEncodingForPropertyDecl - Return the encoded type for this 2472/// property declaration. If non-NULL, Container must be either an 2473/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be 2474/// NULL when getting encodings for protocol properties. 2475/// Property attributes are stored as a comma-delimited C string. The simple 2476/// attributes readonly and bycopy are encoded as single characters. The 2477/// parametrized attributes, getter=name, setter=name, and ivar=name, are 2478/// encoded as single characters, followed by an identifier. Property types 2479/// are also encoded as a parametrized attribute. The characters used to encode 2480/// these attributes are defined by the following enumeration: 2481/// @code 2482/// enum PropertyAttributes { 2483/// kPropertyReadOnly = 'R', // property is read-only. 2484/// kPropertyBycopy = 'C', // property is a copy of the value last assigned 2485/// kPropertyByref = '&', // property is a reference to the value last assigned 2486/// kPropertyDynamic = 'D', // property is dynamic 2487/// kPropertyGetter = 'G', // followed by getter selector name 2488/// kPropertySetter = 'S', // followed by setter selector name 2489/// kPropertyInstanceVariable = 'V' // followed by instance variable name 2490/// kPropertyType = 't' // followed by old-style type encoding. 2491/// kPropertyWeak = 'W' // 'weak' property 2492/// kPropertyStrong = 'P' // property GC'able 2493/// kPropertyNonAtomic = 'N' // property non-atomic 2494/// }; 2495/// @endcode 2496void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, 2497 const Decl *Container, 2498 std::string& S) { 2499 // Collect information from the property implementation decl(s). 2500 bool Dynamic = false; 2501 ObjCPropertyImplDecl *SynthesizePID = 0; 2502 2503 // FIXME: Duplicated code due to poor abstraction. 2504 if (Container) { 2505 if (const ObjCCategoryImplDecl *CID = 2506 dyn_cast<ObjCCategoryImplDecl>(Container)) { 2507 for (ObjCCategoryImplDecl::propimpl_iterator 2508 i = CID->propimpl_begin(), e = CID->propimpl_end(); 2509 i != e; ++i) { 2510 ObjCPropertyImplDecl *PID = *i; 2511 if (PID->getPropertyDecl() == PD) { 2512 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) { 2513 Dynamic = true; 2514 } else { 2515 SynthesizePID = PID; 2516 } 2517 } 2518 } 2519 } else { 2520 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container); 2521 for (ObjCCategoryImplDecl::propimpl_iterator 2522 i = OID->propimpl_begin(), e = OID->propimpl_end(); 2523 i != e; ++i) { 2524 ObjCPropertyImplDecl *PID = *i; 2525 if (PID->getPropertyDecl() == PD) { 2526 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) { 2527 Dynamic = true; 2528 } else { 2529 SynthesizePID = PID; 2530 } 2531 } 2532 } 2533 } 2534 } 2535 2536 // FIXME: This is not very efficient. 2537 S = "T"; 2538 2539 // Encode result type. 2540 // GCC has some special rules regarding encoding of properties which 2541 // closely resembles encoding of ivars. 2542 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0, 2543 true /* outermost type */, 2544 true /* encoding for property */); 2545 2546 if (PD->isReadOnly()) { 2547 S += ",R"; 2548 } else { 2549 switch (PD->getSetterKind()) { 2550 case ObjCPropertyDecl::Assign: break; 2551 case ObjCPropertyDecl::Copy: S += ",C"; break; 2552 case ObjCPropertyDecl::Retain: S += ",&"; break; 2553 } 2554 } 2555 2556 // It really isn't clear at all what this means, since properties 2557 // are "dynamic by default". 2558 if (Dynamic) 2559 S += ",D"; 2560 2561 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic) 2562 S += ",N"; 2563 2564 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) { 2565 S += ",G"; 2566 S += PD->getGetterName().getAsString(); 2567 } 2568 2569 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) { 2570 S += ",S"; 2571 S += PD->getSetterName().getAsString(); 2572 } 2573 2574 if (SynthesizePID) { 2575 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl(); 2576 S += ",V"; 2577 S += OID->getNameAsString(); 2578 } 2579 2580 // FIXME: OBJCGC: weak & strong 2581} 2582 2583/// getLegacyIntegralTypeEncoding - 2584/// Another legacy compatibility encoding: 32-bit longs are encoded as 2585/// 'l' or 'L' , but not always. For typedefs, we need to use 2586/// 'i' or 'I' instead if encoding a struct field, or a pointer! 2587/// 2588void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const { 2589 if (dyn_cast<TypedefType>(PointeeTy.getTypePtr())) { 2590 if (const BuiltinType *BT = PointeeTy->getAsBuiltinType()) { 2591 if (BT->getKind() == BuiltinType::ULong && 2592 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32)) 2593 PointeeTy = UnsignedIntTy; 2594 else 2595 if (BT->getKind() == BuiltinType::Long && 2596 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32)) 2597 PointeeTy = IntTy; 2598 } 2599 } 2600} 2601 2602void ASTContext::getObjCEncodingForType(QualType T, std::string& S, 2603 const FieldDecl *Field) { 2604 // We follow the behavior of gcc, expanding structures which are 2605 // directly pointed to, and expanding embedded structures. Note that 2606 // these rules are sufficient to prevent recursive encoding of the 2607 // same type. 2608 getObjCEncodingForTypeImpl(T, S, true, true, Field, 2609 true /* outermost type */); 2610} 2611 2612static void EncodeBitField(const ASTContext *Context, std::string& S, 2613 const FieldDecl *FD) { 2614 const Expr *E = FD->getBitWidth(); 2615 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl"); 2616 ASTContext *Ctx = const_cast<ASTContext*>(Context); 2617 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue(); 2618 S += 'b'; 2619 S += llvm::utostr(N); 2620} 2621 2622void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, 2623 bool ExpandPointedToStructures, 2624 bool ExpandStructures, 2625 const FieldDecl *FD, 2626 bool OutermostType, 2627 bool EncodingProperty) { 2628 if (const BuiltinType *BT = T->getAsBuiltinType()) { 2629 if (FD && FD->isBitField()) { 2630 EncodeBitField(this, S, FD); 2631 } 2632 else { 2633 char encoding; 2634 switch (BT->getKind()) { 2635 default: assert(0 && "Unhandled builtin type kind"); 2636 case BuiltinType::Void: encoding = 'v'; break; 2637 case BuiltinType::Bool: encoding = 'B'; break; 2638 case BuiltinType::Char_U: 2639 case BuiltinType::UChar: encoding = 'C'; break; 2640 case BuiltinType::UShort: encoding = 'S'; break; 2641 case BuiltinType::UInt: encoding = 'I'; break; 2642 case BuiltinType::ULong: 2643 encoding = 2644 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q'; 2645 break; 2646 case BuiltinType::UInt128: encoding = 'T'; break; 2647 case BuiltinType::ULongLong: encoding = 'Q'; break; 2648 case BuiltinType::Char_S: 2649 case BuiltinType::SChar: encoding = 'c'; break; 2650 case BuiltinType::Short: encoding = 's'; break; 2651 case BuiltinType::Int: encoding = 'i'; break; 2652 case BuiltinType::Long: 2653 encoding = 2654 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q'; 2655 break; 2656 case BuiltinType::LongLong: encoding = 'q'; break; 2657 case BuiltinType::Int128: encoding = 't'; break; 2658 case BuiltinType::Float: encoding = 'f'; break; 2659 case BuiltinType::Double: encoding = 'd'; break; 2660 case BuiltinType::LongDouble: encoding = 'd'; break; 2661 } 2662 2663 S += encoding; 2664 } 2665 } else if (const ComplexType *CT = T->getAsComplexType()) { 2666 S += 'j'; 2667 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false, 2668 false); 2669 } else if (T->isObjCQualifiedIdType()) { 2670 getObjCEncodingForTypeImpl(getObjCIdType(), S, 2671 ExpandPointedToStructures, 2672 ExpandStructures, FD); 2673 if (FD || EncodingProperty) { 2674 // Note that we do extended encoding of protocol qualifer list 2675 // Only when doing ivar or property encoding. 2676 const ObjCObjectPointerType *QIDT = T->getAsObjCQualifiedIdType(); 2677 S += '"'; 2678 for (ObjCObjectPointerType::qual_iterator I = QIDT->qual_begin(), 2679 E = QIDT->qual_end(); I != E; ++I) { 2680 S += '<'; 2681 S += (*I)->getNameAsString(); 2682 S += '>'; 2683 } 2684 S += '"'; 2685 } 2686 return; 2687 } 2688 else if (const PointerType *PT = T->getAsPointerType()) { 2689 QualType PointeeTy = PT->getPointeeType(); 2690 bool isReadOnly = false; 2691 // For historical/compatibility reasons, the read-only qualifier of the 2692 // pointee gets emitted _before_ the '^'. The read-only qualifier of 2693 // the pointer itself gets ignored, _unless_ we are looking at a typedef! 2694 // Also, do not emit the 'r' for anything but the outermost type! 2695 if (dyn_cast<TypedefType>(T.getTypePtr())) { 2696 if (OutermostType && T.isConstQualified()) { 2697 isReadOnly = true; 2698 S += 'r'; 2699 } 2700 } 2701 else if (OutermostType) { 2702 QualType P = PointeeTy; 2703 while (P->getAsPointerType()) 2704 P = P->getAsPointerType()->getPointeeType(); 2705 if (P.isConstQualified()) { 2706 isReadOnly = true; 2707 S += 'r'; 2708 } 2709 } 2710 if (isReadOnly) { 2711 // Another legacy compatibility encoding. Some ObjC qualifier and type 2712 // combinations need to be rearranged. 2713 // Rewrite "in const" from "nr" to "rn" 2714 const char * s = S.c_str(); 2715 int len = S.length(); 2716 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') { 2717 std::string replace = "rn"; 2718 S.replace(S.end()-2, S.end(), replace); 2719 } 2720 } 2721 if (isObjCIdStructType(PointeeTy)) { 2722 S += '@'; 2723 return; 2724 } 2725 else if (PointeeTy->isObjCInterfaceType()) { 2726 if (!EncodingProperty && 2727 isa<TypedefType>(PointeeTy.getTypePtr())) { 2728 // Another historical/compatibility reason. 2729 // We encode the underlying type which comes out as 2730 // {...}; 2731 S += '^'; 2732 getObjCEncodingForTypeImpl(PointeeTy, S, 2733 false, ExpandPointedToStructures, 2734 NULL); 2735 return; 2736 } 2737 S += '@'; 2738 if (FD || EncodingProperty) { 2739 const ObjCInterfaceType *OIT = 2740 PointeeTy.getUnqualifiedType()->getAsObjCInterfaceType(); 2741 ObjCInterfaceDecl *OI = OIT->getDecl(); 2742 S += '"'; 2743 S += OI->getNameAsCString(); 2744 for (ObjCInterfaceType::qual_iterator I = OIT->qual_begin(), 2745 E = OIT->qual_end(); I != E; ++I) { 2746 S += '<'; 2747 S += (*I)->getNameAsString(); 2748 S += '>'; 2749 } 2750 S += '"'; 2751 } 2752 return; 2753 } else if (isObjCClassStructType(PointeeTy)) { 2754 S += '#'; 2755 return; 2756 } else if (isObjCSelType(PointeeTy)) { 2757 S += ':'; 2758 return; 2759 } 2760 2761 if (PointeeTy->isCharType()) { 2762 // char pointer types should be encoded as '*' unless it is a 2763 // type that has been typedef'd to 'BOOL'. 2764 if (!isTypeTypedefedAsBOOL(PointeeTy)) { 2765 S += '*'; 2766 return; 2767 } 2768 } 2769 2770 S += '^'; 2771 getLegacyIntegralTypeEncoding(PointeeTy); 2772 2773 getObjCEncodingForTypeImpl(PointeeTy, S, 2774 false, ExpandPointedToStructures, 2775 NULL); 2776 } else if (const ArrayType *AT = 2777 // Ignore type qualifiers etc. 2778 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) { 2779 if (isa<IncompleteArrayType>(AT)) { 2780 // Incomplete arrays are encoded as a pointer to the array element. 2781 S += '^'; 2782 2783 getObjCEncodingForTypeImpl(AT->getElementType(), S, 2784 false, ExpandStructures, FD); 2785 } else { 2786 S += '['; 2787 2788 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) 2789 S += llvm::utostr(CAT->getSize().getZExtValue()); 2790 else { 2791 //Variable length arrays are encoded as a regular array with 0 elements. 2792 assert(isa<VariableArrayType>(AT) && "Unknown array type!"); 2793 S += '0'; 2794 } 2795 2796 getObjCEncodingForTypeImpl(AT->getElementType(), S, 2797 false, ExpandStructures, FD); 2798 S += ']'; 2799 } 2800 } else if (T->getAsFunctionType()) { 2801 S += '?'; 2802 } else if (const RecordType *RTy = T->getAsRecordType()) { 2803 RecordDecl *RDecl = RTy->getDecl(); 2804 S += RDecl->isUnion() ? '(' : '{'; 2805 // Anonymous structures print as '?' 2806 if (const IdentifierInfo *II = RDecl->getIdentifier()) { 2807 S += II->getName(); 2808 } else { 2809 S += '?'; 2810 } 2811 if (ExpandStructures) { 2812 S += '='; 2813 for (RecordDecl::field_iterator Field = RDecl->field_begin(), 2814 FieldEnd = RDecl->field_end(); 2815 Field != FieldEnd; ++Field) { 2816 if (FD) { 2817 S += '"'; 2818 S += Field->getNameAsString(); 2819 S += '"'; 2820 } 2821 2822 // Special case bit-fields. 2823 if (Field->isBitField()) { 2824 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, 2825 (*Field)); 2826 } else { 2827 QualType qt = Field->getType(); 2828 getLegacyIntegralTypeEncoding(qt); 2829 getObjCEncodingForTypeImpl(qt, S, false, true, 2830 FD); 2831 } 2832 } 2833 } 2834 S += RDecl->isUnion() ? ')' : '}'; 2835 } else if (T->isEnumeralType()) { 2836 if (FD && FD->isBitField()) 2837 EncodeBitField(this, S, FD); 2838 else 2839 S += 'i'; 2840 } else if (T->isBlockPointerType()) { 2841 S += "@?"; // Unlike a pointer-to-function, which is "^?". 2842 } else if (T->isObjCInterfaceType()) { 2843 // @encode(class_name) 2844 ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl(); 2845 S += '{'; 2846 const IdentifierInfo *II = OI->getIdentifier(); 2847 S += II->getName(); 2848 S += '='; 2849 llvm::SmallVector<FieldDecl*, 32> RecFields; 2850 CollectObjCIvars(OI, RecFields); 2851 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 2852 if (RecFields[i]->isBitField()) 2853 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true, 2854 RecFields[i]); 2855 else 2856 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true, 2857 FD); 2858 } 2859 S += '}'; 2860 } 2861 else 2862 assert(0 && "@encode for type not implemented!"); 2863} 2864 2865void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, 2866 std::string& S) const { 2867 if (QT & Decl::OBJC_TQ_In) 2868 S += 'n'; 2869 if (QT & Decl::OBJC_TQ_Inout) 2870 S += 'N'; 2871 if (QT & Decl::OBJC_TQ_Out) 2872 S += 'o'; 2873 if (QT & Decl::OBJC_TQ_Bycopy) 2874 S += 'O'; 2875 if (QT & Decl::OBJC_TQ_Byref) 2876 S += 'R'; 2877 if (QT & Decl::OBJC_TQ_Oneway) 2878 S += 'V'; 2879} 2880 2881void ASTContext::setBuiltinVaListType(QualType T) 2882{ 2883 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!"); 2884 2885 BuiltinVaListType = T; 2886} 2887 2888void ASTContext::setObjCIdType(QualType T) 2889{ 2890 ObjCIdType = T; 2891 2892 const TypedefType *TT = T->getAsTypedefType(); 2893 if (!TT) 2894 return; 2895 2896 TypedefDecl *TD = TT->getDecl(); 2897 2898 // typedef struct objc_object *id; 2899 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType(); 2900 // User error - caller will issue diagnostics. 2901 if (!ptr) 2902 return; 2903 const RecordType *rec = ptr->getPointeeType()->getAsStructureType(); 2904 // User error - caller will issue diagnostics. 2905 if (!rec) 2906 return; 2907 IdStructType = rec; 2908} 2909 2910void ASTContext::setObjCSelType(QualType T) 2911{ 2912 ObjCSelType = T; 2913 2914 const TypedefType *TT = T->getAsTypedefType(); 2915 if (!TT) 2916 return; 2917 TypedefDecl *TD = TT->getDecl(); 2918 2919 // typedef struct objc_selector *SEL; 2920 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType(); 2921 if (!ptr) 2922 return; 2923 const RecordType *rec = ptr->getPointeeType()->getAsStructureType(); 2924 if (!rec) 2925 return; 2926 SelStructType = rec; 2927} 2928 2929void ASTContext::setObjCProtoType(QualType QT) 2930{ 2931 ObjCProtoType = QT; 2932} 2933 2934void ASTContext::setObjCClassType(QualType T) 2935{ 2936 ObjCClassType = T; 2937 2938 const TypedefType *TT = T->getAsTypedefType(); 2939 if (!TT) 2940 return; 2941 TypedefDecl *TD = TT->getDecl(); 2942 2943 // typedef struct objc_class *Class; 2944 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType(); 2945 assert(ptr && "'Class' incorrectly typed"); 2946 const RecordType *rec = ptr->getPointeeType()->getAsStructureType(); 2947 assert(rec && "'Class' incorrectly typed"); 2948 ClassStructType = rec; 2949} 2950 2951void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) { 2952 assert(ObjCConstantStringType.isNull() && 2953 "'NSConstantString' type already set!"); 2954 2955 ObjCConstantStringType = getObjCInterfaceType(Decl); 2956} 2957 2958/// \brief Retrieve the template name that represents a qualified 2959/// template name such as \c std::vector. 2960TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, 2961 bool TemplateKeyword, 2962 TemplateDecl *Template) { 2963 llvm::FoldingSetNodeID ID; 2964 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template); 2965 2966 void *InsertPos = 0; 2967 QualifiedTemplateName *QTN = 2968 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 2969 if (!QTN) { 2970 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template); 2971 QualifiedTemplateNames.InsertNode(QTN, InsertPos); 2972 } 2973 2974 return TemplateName(QTN); 2975} 2976 2977/// \brief Retrieve the template name that represents a dependent 2978/// template name such as \c MetaFun::template apply. 2979TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 2980 const IdentifierInfo *Name) { 2981 assert(NNS->isDependent() && "Nested name specifier must be dependent"); 2982 2983 llvm::FoldingSetNodeID ID; 2984 DependentTemplateName::Profile(ID, NNS, Name); 2985 2986 void *InsertPos = 0; 2987 DependentTemplateName *QTN = 2988 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 2989 2990 if (QTN) 2991 return TemplateName(QTN); 2992 2993 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 2994 if (CanonNNS == NNS) { 2995 QTN = new (*this,4) DependentTemplateName(NNS, Name); 2996 } else { 2997 TemplateName Canon = getDependentTemplateName(CanonNNS, Name); 2998 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon); 2999 } 3000 3001 DependentTemplateNames.InsertNode(QTN, InsertPos); 3002 return TemplateName(QTN); 3003} 3004 3005/// getFromTargetType - Given one of the integer types provided by 3006/// TargetInfo, produce the corresponding type. The unsigned @p Type 3007/// is actually a value of type @c TargetInfo::IntType. 3008QualType ASTContext::getFromTargetType(unsigned Type) const { 3009 switch (Type) { 3010 case TargetInfo::NoInt: return QualType(); 3011 case TargetInfo::SignedShort: return ShortTy; 3012 case TargetInfo::UnsignedShort: return UnsignedShortTy; 3013 case TargetInfo::SignedInt: return IntTy; 3014 case TargetInfo::UnsignedInt: return UnsignedIntTy; 3015 case TargetInfo::SignedLong: return LongTy; 3016 case TargetInfo::UnsignedLong: return UnsignedLongTy; 3017 case TargetInfo::SignedLongLong: return LongLongTy; 3018 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy; 3019 } 3020 3021 assert(false && "Unhandled TargetInfo::IntType value"); 3022 return QualType(); 3023} 3024 3025//===----------------------------------------------------------------------===// 3026// Type Predicates. 3027//===----------------------------------------------------------------------===// 3028 3029/// isObjCNSObjectType - Return true if this is an NSObject object using 3030/// NSObject attribute on a c-style pointer type. 3031/// FIXME - Make it work directly on types. 3032/// 3033bool ASTContext::isObjCNSObjectType(QualType Ty) const { 3034 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) { 3035 if (TypedefDecl *TD = TDT->getDecl()) 3036 if (TD->getAttr<ObjCNSObjectAttr>()) 3037 return true; 3038 } 3039 return false; 3040} 3041 3042/// isObjCObjectPointerType - Returns true if type is an Objective-C pointer 3043/// to an object type. This includes "id" and "Class" (two 'special' pointers 3044/// to struct), Interface* (pointer to ObjCInterfaceType) and id<P> (qualified 3045/// ID type). 3046bool ASTContext::isObjCObjectPointerType(QualType Ty) const { 3047 if (Ty->isObjCQualifiedIdType()) 3048 return true; 3049 3050 // Blocks are objects. 3051 if (Ty->isBlockPointerType()) 3052 return true; 3053 3054 // All other object types are pointers. 3055 const PointerType *PT = Ty->getAsPointerType(); 3056 if (PT == 0) 3057 return false; 3058 3059 // If this a pointer to an interface (e.g. NSString*), it is ok. 3060 if (PT->getPointeeType()->isObjCInterfaceType() || 3061 // If is has NSObject attribute, OK as well. 3062 isObjCNSObjectType(Ty)) 3063 return true; 3064 3065 // Check to see if this is 'id' or 'Class', both of which are typedefs for 3066 // pointer types. This looks for the typedef specifically, not for the 3067 // underlying type. Iteratively strip off typedefs so that we can handle 3068 // typedefs of typedefs. 3069 while (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) { 3070 if (Ty.getUnqualifiedType() == getObjCIdType() || 3071 Ty.getUnqualifiedType() == getObjCClassType()) 3072 return true; 3073 3074 Ty = TDT->getDecl()->getUnderlyingType(); 3075 } 3076 3077 return false; 3078} 3079 3080/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's 3081/// garbage collection attribute. 3082/// 3083QualType::GCAttrTypes ASTContext::getObjCGCAttrKind(const QualType &Ty) const { 3084 QualType::GCAttrTypes GCAttrs = QualType::GCNone; 3085 if (getLangOptions().ObjC1 && 3086 getLangOptions().getGCMode() != LangOptions::NonGC) { 3087 GCAttrs = Ty.getObjCGCAttr(); 3088 // Default behavious under objective-c's gc is for objective-c pointers 3089 // (or pointers to them) be treated as though they were declared 3090 // as __strong. 3091 if (GCAttrs == QualType::GCNone) { 3092 if (isObjCObjectPointerType(Ty)) 3093 GCAttrs = QualType::Strong; 3094 else if (Ty->isPointerType()) 3095 return getObjCGCAttrKind(Ty->getAsPointerType()->getPointeeType()); 3096 } 3097 // Non-pointers have none gc'able attribute regardless of the attribute 3098 // set on them. 3099 else if (!Ty->isPointerType() && !isObjCObjectPointerType(Ty)) 3100 return QualType::GCNone; 3101 } 3102 return GCAttrs; 3103} 3104 3105//===----------------------------------------------------------------------===// 3106// Type Compatibility Testing 3107//===----------------------------------------------------------------------===// 3108 3109/// areCompatVectorTypes - Return true if the two specified vector types are 3110/// compatible. 3111static bool areCompatVectorTypes(const VectorType *LHS, 3112 const VectorType *RHS) { 3113 assert(LHS->isCanonical() && RHS->isCanonical()); 3114 return LHS->getElementType() == RHS->getElementType() && 3115 LHS->getNumElements() == RHS->getNumElements(); 3116} 3117 3118/// canAssignObjCInterfaces - Return true if the two interface types are 3119/// compatible for assignment from RHS to LHS. This handles validation of any 3120/// protocol qualifiers on the LHS or RHS. 3121/// 3122bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS, 3123 const ObjCInterfaceType *RHS) { 3124 // Verify that the base decls are compatible: the RHS must be a subclass of 3125 // the LHS. 3126 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl())) 3127 return false; 3128 3129 // RHS must have a superset of the protocols in the LHS. If the LHS is not 3130 // protocol qualified at all, then we are good. 3131 if (!isa<ObjCQualifiedInterfaceType>(LHS)) 3132 return true; 3133 3134 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it 3135 // isn't a superset. 3136 if (!isa<ObjCQualifiedInterfaceType>(RHS)) 3137 return true; // FIXME: should return false! 3138 3139 // Finally, we must have two protocol-qualified interfaces. 3140 const ObjCQualifiedInterfaceType *LHSP =cast<ObjCQualifiedInterfaceType>(LHS); 3141 const ObjCQualifiedInterfaceType *RHSP =cast<ObjCQualifiedInterfaceType>(RHS); 3142 3143 // All LHS protocols must have a presence on the RHS. 3144 assert(LHSP->qual_begin() != LHSP->qual_end() && "Empty LHS protocol list?"); 3145 3146 for (ObjCQualifiedInterfaceType::qual_iterator LHSPI = LHSP->qual_begin(), 3147 LHSPE = LHSP->qual_end(); 3148 LHSPI != LHSPE; LHSPI++) { 3149 bool RHSImplementsProtocol = false; 3150 3151 // If the RHS doesn't implement the protocol on the left, the types 3152 // are incompatible. 3153 for (ObjCQualifiedInterfaceType::qual_iterator RHSPI = RHSP->qual_begin(), 3154 RHSPE = RHSP->qual_end(); 3155 !RHSImplementsProtocol && (RHSPI != RHSPE); RHSPI++) { 3156 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) 3157 RHSImplementsProtocol = true; 3158 } 3159 // FIXME: For better diagnostics, consider passing back the protocol name. 3160 if (!RHSImplementsProtocol) 3161 return false; 3162 } 3163 // The RHS implements all protocols listed on the LHS. 3164 return true; 3165} 3166 3167bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) { 3168 // get the "pointed to" types 3169 const PointerType *LHSPT = LHS->getAsPointerType(); 3170 const PointerType *RHSPT = RHS->getAsPointerType(); 3171 3172 if (!LHSPT || !RHSPT) 3173 return false; 3174 3175 QualType lhptee = LHSPT->getPointeeType(); 3176 QualType rhptee = RHSPT->getPointeeType(); 3177 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType(); 3178 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType(); 3179 // ID acts sort of like void* for ObjC interfaces 3180 if (LHSIface && isObjCIdStructType(rhptee)) 3181 return true; 3182 if (RHSIface && isObjCIdStructType(lhptee)) 3183 return true; 3184 if (!LHSIface || !RHSIface) 3185 return false; 3186 return canAssignObjCInterfaces(LHSIface, RHSIface) || 3187 canAssignObjCInterfaces(RHSIface, LHSIface); 3188} 3189 3190/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible, 3191/// both shall have the identically qualified version of a compatible type. 3192/// C99 6.2.7p1: Two types have compatible types if their types are the 3193/// same. See 6.7.[2,3,5] for additional rules. 3194bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) { 3195 return !mergeTypes(LHS, RHS).isNull(); 3196} 3197 3198QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) { 3199 const FunctionType *lbase = lhs->getAsFunctionType(); 3200 const FunctionType *rbase = rhs->getAsFunctionType(); 3201 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase); 3202 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase); 3203 bool allLTypes = true; 3204 bool allRTypes = true; 3205 3206 // Check return type 3207 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType()); 3208 if (retType.isNull()) return QualType(); 3209 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType())) 3210 allLTypes = false; 3211 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType())) 3212 allRTypes = false; 3213 3214 if (lproto && rproto) { // two C99 style function prototypes 3215 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() && 3216 "C++ shouldn't be here"); 3217 unsigned lproto_nargs = lproto->getNumArgs(); 3218 unsigned rproto_nargs = rproto->getNumArgs(); 3219 3220 // Compatible functions must have the same number of arguments 3221 if (lproto_nargs != rproto_nargs) 3222 return QualType(); 3223 3224 // Variadic and non-variadic functions aren't compatible 3225 if (lproto->isVariadic() != rproto->isVariadic()) 3226 return QualType(); 3227 3228 if (lproto->getTypeQuals() != rproto->getTypeQuals()) 3229 return QualType(); 3230 3231 // Check argument compatibility 3232 llvm::SmallVector<QualType, 10> types; 3233 for (unsigned i = 0; i < lproto_nargs; i++) { 3234 QualType largtype = lproto->getArgType(i).getUnqualifiedType(); 3235 QualType rargtype = rproto->getArgType(i).getUnqualifiedType(); 3236 QualType argtype = mergeTypes(largtype, rargtype); 3237 if (argtype.isNull()) return QualType(); 3238 types.push_back(argtype); 3239 if (getCanonicalType(argtype) != getCanonicalType(largtype)) 3240 allLTypes = false; 3241 if (getCanonicalType(argtype) != getCanonicalType(rargtype)) 3242 allRTypes = false; 3243 } 3244 if (allLTypes) return lhs; 3245 if (allRTypes) return rhs; 3246 return getFunctionType(retType, types.begin(), types.size(), 3247 lproto->isVariadic(), lproto->getTypeQuals()); 3248 } 3249 3250 if (lproto) allRTypes = false; 3251 if (rproto) allLTypes = false; 3252 3253 const FunctionProtoType *proto = lproto ? lproto : rproto; 3254 if (proto) { 3255 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here"); 3256 if (proto->isVariadic()) return QualType(); 3257 // Check that the types are compatible with the types that 3258 // would result from default argument promotions (C99 6.7.5.3p15). 3259 // The only types actually affected are promotable integer 3260 // types and floats, which would be passed as a different 3261 // type depending on whether the prototype is visible. 3262 unsigned proto_nargs = proto->getNumArgs(); 3263 for (unsigned i = 0; i < proto_nargs; ++i) { 3264 QualType argTy = proto->getArgType(i); 3265 if (argTy->isPromotableIntegerType() || 3266 getCanonicalType(argTy).getUnqualifiedType() == FloatTy) 3267 return QualType(); 3268 } 3269 3270 if (allLTypes) return lhs; 3271 if (allRTypes) return rhs; 3272 return getFunctionType(retType, proto->arg_type_begin(), 3273 proto->getNumArgs(), lproto->isVariadic(), 3274 lproto->getTypeQuals()); 3275 } 3276 3277 if (allLTypes) return lhs; 3278 if (allRTypes) return rhs; 3279 return getFunctionNoProtoType(retType); 3280} 3281 3282QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) { 3283 // C++ [expr]: If an expression initially has the type "reference to T", the 3284 // type is adjusted to "T" prior to any further analysis, the expression 3285 // designates the object or function denoted by the reference, and the 3286 // expression is an lvalue unless the reference is an rvalue reference and 3287 // the expression is a function call (possibly inside parentheses). 3288 // FIXME: C++ shouldn't be going through here! The rules are different 3289 // enough that they should be handled separately. 3290 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really* 3291 // shouldn't be going through here! 3292 if (const ReferenceType *RT = LHS->getAsReferenceType()) 3293 LHS = RT->getPointeeType(); 3294 if (const ReferenceType *RT = RHS->getAsReferenceType()) 3295 RHS = RT->getPointeeType(); 3296 3297 QualType LHSCan = getCanonicalType(LHS), 3298 RHSCan = getCanonicalType(RHS); 3299 3300 // If two types are identical, they are compatible. 3301 if (LHSCan == RHSCan) 3302 return LHS; 3303 3304 // If the qualifiers are different, the types aren't compatible 3305 // Note that we handle extended qualifiers later, in the 3306 // case for ExtQualType. 3307 if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers()) 3308 return QualType(); 3309 3310 Type::TypeClass LHSClass = LHSCan->getTypeClass(); 3311 Type::TypeClass RHSClass = RHSCan->getTypeClass(); 3312 3313 // We want to consider the two function types to be the same for these 3314 // comparisons, just force one to the other. 3315 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto; 3316 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto; 3317 3318 // Strip off objc_gc attributes off the top level so they can be merged. 3319 // This is a complete mess, but the attribute itself doesn't make much sense. 3320 if (RHSClass == Type::ExtQual) { 3321 QualType::GCAttrTypes GCAttr = RHSCan.getObjCGCAttr(); 3322 if (GCAttr != QualType::GCNone) { 3323 QualType::GCAttrTypes GCLHSAttr = LHSCan.getObjCGCAttr(); 3324 // __weak attribute must appear on both declarations. 3325 // __strong attribue is redundant if other decl is an objective-c 3326 // object pointer (or decorated with __strong attribute); otherwise 3327 // issue error. 3328 if ((GCAttr == QualType::Weak && GCLHSAttr != GCAttr) || 3329 (GCAttr == QualType::Strong && GCLHSAttr != GCAttr && 3330 LHSCan->isPointerType() && !isObjCObjectPointerType(LHSCan) && 3331 !isObjCIdStructType(LHSCan->getAsPointerType()->getPointeeType()))) 3332 return QualType(); 3333 3334 RHS = QualType(cast<ExtQualType>(RHS.getDesugaredType())->getBaseType(), 3335 RHS.getCVRQualifiers()); 3336 QualType Result = mergeTypes(LHS, RHS); 3337 if (!Result.isNull()) { 3338 if (Result.getObjCGCAttr() == QualType::GCNone) 3339 Result = getObjCGCQualType(Result, GCAttr); 3340 else if (Result.getObjCGCAttr() != GCAttr) 3341 Result = QualType(); 3342 } 3343 return Result; 3344 } 3345 } 3346 if (LHSClass == Type::ExtQual) { 3347 QualType::GCAttrTypes GCAttr = LHSCan.getObjCGCAttr(); 3348 if (GCAttr != QualType::GCNone) { 3349 QualType::GCAttrTypes GCRHSAttr = RHSCan.getObjCGCAttr(); 3350 // __weak attribute must appear on both declarations. __strong 3351 // __strong attribue is redundant if other decl is an objective-c 3352 // object pointer (or decorated with __strong attribute); otherwise 3353 // issue error. 3354 if ((GCAttr == QualType::Weak && GCRHSAttr != GCAttr) || 3355 (GCAttr == QualType::Strong && GCRHSAttr != GCAttr && 3356 RHSCan->isPointerType() && !isObjCObjectPointerType(RHSCan) && 3357 !isObjCIdStructType(RHSCan->getAsPointerType()->getPointeeType()))) 3358 return QualType(); 3359 3360 LHS = QualType(cast<ExtQualType>(LHS.getDesugaredType())->getBaseType(), 3361 LHS.getCVRQualifiers()); 3362 QualType Result = mergeTypes(LHS, RHS); 3363 if (!Result.isNull()) { 3364 if (Result.getObjCGCAttr() == QualType::GCNone) 3365 Result = getObjCGCQualType(Result, GCAttr); 3366 else if (Result.getObjCGCAttr() != GCAttr) 3367 Result = QualType(); 3368 } 3369 return Result; 3370 } 3371 } 3372 3373 // Same as above for arrays 3374 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray) 3375 LHSClass = Type::ConstantArray; 3376 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray) 3377 RHSClass = Type::ConstantArray; 3378 3379 // Canonicalize ExtVector -> Vector. 3380 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector; 3381 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector; 3382 3383 // Consider qualified interfaces and interfaces the same. 3384 if (LHSClass == Type::ObjCQualifiedInterface) LHSClass = Type::ObjCInterface; 3385 if (RHSClass == Type::ObjCQualifiedInterface) RHSClass = Type::ObjCInterface; 3386 3387 // If the canonical type classes don't match. 3388 if (LHSClass != RHSClass) { 3389 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType(); 3390 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType(); 3391 3392 // 'id' and 'Class' act sort of like void* for ObjC interfaces 3393 if (LHSIface && (isObjCIdStructType(RHS) || isObjCClassStructType(RHS))) 3394 return LHS; 3395 if (RHSIface && (isObjCIdStructType(LHS) || isObjCClassStructType(LHS))) 3396 return RHS; 3397 3398 // ID is compatible with all qualified id types. 3399 if (LHS->isObjCQualifiedIdType()) { 3400 if (const PointerType *PT = RHS->getAsPointerType()) { 3401 QualType pType = PT->getPointeeType(); 3402 if (isObjCIdStructType(pType) || isObjCClassStructType(pType)) 3403 return LHS; 3404 // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true). 3405 // Unfortunately, this API is part of Sema (which we don't have access 3406 // to. Need to refactor. The following check is insufficient, since we 3407 // need to make sure the class implements the protocol. 3408 if (pType->isObjCInterfaceType()) 3409 return LHS; 3410 } 3411 } 3412 if (RHS->isObjCQualifiedIdType()) { 3413 if (const PointerType *PT = LHS->getAsPointerType()) { 3414 QualType pType = PT->getPointeeType(); 3415 if (isObjCIdStructType(pType) || isObjCClassStructType(pType)) 3416 return RHS; 3417 // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true). 3418 // Unfortunately, this API is part of Sema (which we don't have access 3419 // to. Need to refactor. The following check is insufficient, since we 3420 // need to make sure the class implements the protocol. 3421 if (pType->isObjCInterfaceType()) 3422 return RHS; 3423 } 3424 } 3425 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char, 3426 // a signed integer type, or an unsigned integer type. 3427 if (const EnumType* ETy = LHS->getAsEnumType()) { 3428 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType()) 3429 return RHS; 3430 } 3431 if (const EnumType* ETy = RHS->getAsEnumType()) { 3432 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType()) 3433 return LHS; 3434 } 3435 3436 return QualType(); 3437 } 3438 3439 // The canonical type classes match. 3440 switch (LHSClass) { 3441#define TYPE(Class, Base) 3442#define ABSTRACT_TYPE(Class, Base) 3443#define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 3444#define DEPENDENT_TYPE(Class, Base) case Type::Class: 3445#include "clang/AST/TypeNodes.def" 3446 assert(false && "Non-canonical and dependent types shouldn't get here"); 3447 return QualType(); 3448 3449 case Type::LValueReference: 3450 case Type::RValueReference: 3451 case Type::MemberPointer: 3452 assert(false && "C++ should never be in mergeTypes"); 3453 return QualType(); 3454 3455 case Type::IncompleteArray: 3456 case Type::VariableArray: 3457 case Type::FunctionProto: 3458 case Type::ExtVector: 3459 case Type::ObjCQualifiedInterface: 3460 assert(false && "Types are eliminated above"); 3461 return QualType(); 3462 3463 case Type::Pointer: 3464 { 3465 // Merge two pointer types, while trying to preserve typedef info 3466 QualType LHSPointee = LHS->getAsPointerType()->getPointeeType(); 3467 QualType RHSPointee = RHS->getAsPointerType()->getPointeeType(); 3468 QualType ResultType = mergeTypes(LHSPointee, RHSPointee); 3469 if (ResultType.isNull()) return QualType(); 3470 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 3471 return LHS; 3472 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 3473 return RHS; 3474 return getPointerType(ResultType); 3475 } 3476 case Type::BlockPointer: 3477 { 3478 // Merge two block pointer types, while trying to preserve typedef info 3479 QualType LHSPointee = LHS->getAsBlockPointerType()->getPointeeType(); 3480 QualType RHSPointee = RHS->getAsBlockPointerType()->getPointeeType(); 3481 QualType ResultType = mergeTypes(LHSPointee, RHSPointee); 3482 if (ResultType.isNull()) return QualType(); 3483 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 3484 return LHS; 3485 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 3486 return RHS; 3487 return getBlockPointerType(ResultType); 3488 } 3489 case Type::ConstantArray: 3490 { 3491 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS); 3492 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS); 3493 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize()) 3494 return QualType(); 3495 3496 QualType LHSElem = getAsArrayType(LHS)->getElementType(); 3497 QualType RHSElem = getAsArrayType(RHS)->getElementType(); 3498 QualType ResultType = mergeTypes(LHSElem, RHSElem); 3499 if (ResultType.isNull()) return QualType(); 3500 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 3501 return LHS; 3502 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 3503 return RHS; 3504 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(), 3505 ArrayType::ArraySizeModifier(), 0); 3506 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(), 3507 ArrayType::ArraySizeModifier(), 0); 3508 const VariableArrayType* LVAT = getAsVariableArrayType(LHS); 3509 const VariableArrayType* RVAT = getAsVariableArrayType(RHS); 3510 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 3511 return LHS; 3512 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 3513 return RHS; 3514 if (LVAT) { 3515 // FIXME: This isn't correct! But tricky to implement because 3516 // the array's size has to be the size of LHS, but the type 3517 // has to be different. 3518 return LHS; 3519 } 3520 if (RVAT) { 3521 // FIXME: This isn't correct! But tricky to implement because 3522 // the array's size has to be the size of RHS, but the type 3523 // has to be different. 3524 return RHS; 3525 } 3526 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS; 3527 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS; 3528 return getIncompleteArrayType(ResultType, ArrayType::ArraySizeModifier(),0); 3529 } 3530 case Type::FunctionNoProto: 3531 return mergeFunctionTypes(LHS, RHS); 3532 case Type::Record: 3533 case Type::Enum: 3534 // FIXME: Why are these compatible? 3535 if (isObjCIdStructType(LHS) && isObjCClassStructType(RHS)) return LHS; 3536 if (isObjCClassStructType(LHS) && isObjCIdStructType(RHS)) return LHS; 3537 return QualType(); 3538 case Type::Builtin: 3539 // Only exactly equal builtin types are compatible, which is tested above. 3540 return QualType(); 3541 case Type::Complex: 3542 // Distinct complex types are incompatible. 3543 return QualType(); 3544 case Type::Vector: 3545 // FIXME: The merged type should be an ExtVector! 3546 if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType())) 3547 return LHS; 3548 return QualType(); 3549 case Type::ObjCInterface: { 3550 // Check if the interfaces are assignment compatible. 3551 // FIXME: This should be type compatibility, e.g. whether 3552 // "LHS x; RHS x;" at global scope is legal. 3553 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType(); 3554 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType(); 3555 if (LHSIface && RHSIface && 3556 canAssignObjCInterfaces(LHSIface, RHSIface)) 3557 return LHS; 3558 3559 return QualType(); 3560 } 3561 case Type::ObjCObjectPointer: 3562 // FIXME: finish 3563 // Distinct qualified id's are not compatible. 3564 return QualType(); 3565 case Type::FixedWidthInt: 3566 // Distinct fixed-width integers are not compatible. 3567 return QualType(); 3568 case Type::ExtQual: 3569 // FIXME: ExtQual types can be compatible even if they're not 3570 // identical! 3571 return QualType(); 3572 // First attempt at an implementation, but I'm not really sure it's 3573 // right... 3574#if 0 3575 ExtQualType* LQual = cast<ExtQualType>(LHSCan); 3576 ExtQualType* RQual = cast<ExtQualType>(RHSCan); 3577 if (LQual->getAddressSpace() != RQual->getAddressSpace() || 3578 LQual->getObjCGCAttr() != RQual->getObjCGCAttr()) 3579 return QualType(); 3580 QualType LHSBase, RHSBase, ResultType, ResCanUnqual; 3581 LHSBase = QualType(LQual->getBaseType(), 0); 3582 RHSBase = QualType(RQual->getBaseType(), 0); 3583 ResultType = mergeTypes(LHSBase, RHSBase); 3584 if (ResultType.isNull()) return QualType(); 3585 ResCanUnqual = getCanonicalType(ResultType).getUnqualifiedType(); 3586 if (LHSCan.getUnqualifiedType() == ResCanUnqual) 3587 return LHS; 3588 if (RHSCan.getUnqualifiedType() == ResCanUnqual) 3589 return RHS; 3590 ResultType = getAddrSpaceQualType(ResultType, LQual->getAddressSpace()); 3591 ResultType = getObjCGCQualType(ResultType, LQual->getObjCGCAttr()); 3592 ResultType.setCVRQualifiers(LHSCan.getCVRQualifiers()); 3593 return ResultType; 3594#endif 3595 3596 case Type::TemplateSpecialization: 3597 assert(false && "Dependent types have no size"); 3598 break; 3599 } 3600 3601 return QualType(); 3602} 3603 3604//===----------------------------------------------------------------------===// 3605// Integer Predicates 3606//===----------------------------------------------------------------------===// 3607 3608unsigned ASTContext::getIntWidth(QualType T) { 3609 if (T == BoolTy) 3610 return 1; 3611 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) { 3612 return FWIT->getWidth(); 3613 } 3614 // For builtin types, just use the standard type sizing method 3615 return (unsigned)getTypeSize(T); 3616} 3617 3618QualType ASTContext::getCorrespondingUnsignedType(QualType T) { 3619 assert(T->isSignedIntegerType() && "Unexpected type"); 3620 if (const EnumType* ETy = T->getAsEnumType()) 3621 T = ETy->getDecl()->getIntegerType(); 3622 const BuiltinType* BTy = T->getAsBuiltinType(); 3623 assert (BTy && "Unexpected signed integer type"); 3624 switch (BTy->getKind()) { 3625 case BuiltinType::Char_S: 3626 case BuiltinType::SChar: 3627 return UnsignedCharTy; 3628 case BuiltinType::Short: 3629 return UnsignedShortTy; 3630 case BuiltinType::Int: 3631 return UnsignedIntTy; 3632 case BuiltinType::Long: 3633 return UnsignedLongTy; 3634 case BuiltinType::LongLong: 3635 return UnsignedLongLongTy; 3636 case BuiltinType::Int128: 3637 return UnsignedInt128Ty; 3638 default: 3639 assert(0 && "Unexpected signed integer type"); 3640 return QualType(); 3641 } 3642} 3643 3644ExternalASTSource::~ExternalASTSource() { } 3645 3646void ExternalASTSource::PrintStats() { } 3647 3648 3649//===----------------------------------------------------------------------===// 3650// Builtin Type Computation 3651//===----------------------------------------------------------------------===// 3652 3653/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the 3654/// pointer over the consumed characters. This returns the resultant type. 3655static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context, 3656 ASTContext::GetBuiltinTypeError &Error, 3657 bool AllowTypeModifiers = true) { 3658 // Modifiers. 3659 int HowLong = 0; 3660 bool Signed = false, Unsigned = false; 3661 3662 // Read the modifiers first. 3663 bool Done = false; 3664 while (!Done) { 3665 switch (*Str++) { 3666 default: Done = true; --Str; break; 3667 case 'S': 3668 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!"); 3669 assert(!Signed && "Can't use 'S' modifier multiple times!"); 3670 Signed = true; 3671 break; 3672 case 'U': 3673 assert(!Signed && "Can't use both 'S' and 'U' modifiers!"); 3674 assert(!Unsigned && "Can't use 'S' modifier multiple times!"); 3675 Unsigned = true; 3676 break; 3677 case 'L': 3678 assert(HowLong <= 2 && "Can't have LLLL modifier"); 3679 ++HowLong; 3680 break; 3681 } 3682 } 3683 3684 QualType Type; 3685 3686 // Read the base type. 3687 switch (*Str++) { 3688 default: assert(0 && "Unknown builtin type letter!"); 3689 case 'v': 3690 assert(HowLong == 0 && !Signed && !Unsigned && 3691 "Bad modifiers used with 'v'!"); 3692 Type = Context.VoidTy; 3693 break; 3694 case 'f': 3695 assert(HowLong == 0 && !Signed && !Unsigned && 3696 "Bad modifiers used with 'f'!"); 3697 Type = Context.FloatTy; 3698 break; 3699 case 'd': 3700 assert(HowLong < 2 && !Signed && !Unsigned && 3701 "Bad modifiers used with 'd'!"); 3702 if (HowLong) 3703 Type = Context.LongDoubleTy; 3704 else 3705 Type = Context.DoubleTy; 3706 break; 3707 case 's': 3708 assert(HowLong == 0 && "Bad modifiers used with 's'!"); 3709 if (Unsigned) 3710 Type = Context.UnsignedShortTy; 3711 else 3712 Type = Context.ShortTy; 3713 break; 3714 case 'i': 3715 if (HowLong == 3) 3716 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty; 3717 else if (HowLong == 2) 3718 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy; 3719 else if (HowLong == 1) 3720 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy; 3721 else 3722 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy; 3723 break; 3724 case 'c': 3725 assert(HowLong == 0 && "Bad modifiers used with 'c'!"); 3726 if (Signed) 3727 Type = Context.SignedCharTy; 3728 else if (Unsigned) 3729 Type = Context.UnsignedCharTy; 3730 else 3731 Type = Context.CharTy; 3732 break; 3733 case 'b': // boolean 3734 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!"); 3735 Type = Context.BoolTy; 3736 break; 3737 case 'z': // size_t. 3738 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!"); 3739 Type = Context.getSizeType(); 3740 break; 3741 case 'F': 3742 Type = Context.getCFConstantStringType(); 3743 break; 3744 case 'a': 3745 Type = Context.getBuiltinVaListType(); 3746 assert(!Type.isNull() && "builtin va list type not initialized!"); 3747 break; 3748 case 'A': 3749 // This is a "reference" to a va_list; however, what exactly 3750 // this means depends on how va_list is defined. There are two 3751 // different kinds of va_list: ones passed by value, and ones 3752 // passed by reference. An example of a by-value va_list is 3753 // x86, where va_list is a char*. An example of by-ref va_list 3754 // is x86-64, where va_list is a __va_list_tag[1]. For x86, 3755 // we want this argument to be a char*&; for x86-64, we want 3756 // it to be a __va_list_tag*. 3757 Type = Context.getBuiltinVaListType(); 3758 assert(!Type.isNull() && "builtin va list type not initialized!"); 3759 if (Type->isArrayType()) { 3760 Type = Context.getArrayDecayedType(Type); 3761 } else { 3762 Type = Context.getLValueReferenceType(Type); 3763 } 3764 break; 3765 case 'V': { 3766 char *End; 3767 3768 unsigned NumElements = strtoul(Str, &End, 10); 3769 assert(End != Str && "Missing vector size"); 3770 3771 Str = End; 3772 3773 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false); 3774 Type = Context.getVectorType(ElementType, NumElements); 3775 break; 3776 } 3777 case 'P': { 3778 IdentifierInfo *II = &Context.Idents.get("FILE"); 3779 DeclContext::lookup_result Lookup 3780 = Context.getTranslationUnitDecl()->lookup(II); 3781 if (Lookup.first != Lookup.second && isa<TypeDecl>(*Lookup.first)) { 3782 Type = Context.getTypeDeclType(cast<TypeDecl>(*Lookup.first)); 3783 break; 3784 } 3785 else { 3786 Error = ASTContext::GE_Missing_FILE; 3787 return QualType(); 3788 } 3789 } 3790 } 3791 3792 if (!AllowTypeModifiers) 3793 return Type; 3794 3795 Done = false; 3796 while (!Done) { 3797 switch (*Str++) { 3798 default: Done = true; --Str; break; 3799 case '*': 3800 Type = Context.getPointerType(Type); 3801 break; 3802 case '&': 3803 Type = Context.getLValueReferenceType(Type); 3804 break; 3805 // FIXME: There's no way to have a built-in with an rvalue ref arg. 3806 case 'C': 3807 Type = Type.getQualifiedType(QualType::Const); 3808 break; 3809 } 3810 } 3811 3812 return Type; 3813} 3814 3815/// GetBuiltinType - Return the type for the specified builtin. 3816QualType ASTContext::GetBuiltinType(unsigned id, 3817 GetBuiltinTypeError &Error) { 3818 const char *TypeStr = BuiltinInfo.GetTypeString(id); 3819 3820 llvm::SmallVector<QualType, 8> ArgTypes; 3821 3822 Error = GE_None; 3823 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error); 3824 if (Error != GE_None) 3825 return QualType(); 3826 while (TypeStr[0] && TypeStr[0] != '.') { 3827 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error); 3828 if (Error != GE_None) 3829 return QualType(); 3830 3831 // Do array -> pointer decay. The builtin should use the decayed type. 3832 if (Ty->isArrayType()) 3833 Ty = getArrayDecayedType(Ty); 3834 3835 ArgTypes.push_back(Ty); 3836 } 3837 3838 assert((TypeStr[0] != '.' || TypeStr[1] == 0) && 3839 "'.' should only occur at end of builtin type list!"); 3840 3841 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);". 3842 if (ArgTypes.size() == 0 && TypeStr[0] == '.') 3843 return getFunctionNoProtoType(ResType); 3844 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), 3845 TypeStr[0] == '.', 0); 3846} 3847