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