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