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