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