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