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