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