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