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