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