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