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