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/CommentCommandTraits.h" 17 #include "clang/AST/DeclCXX.h" 18 #include "clang/AST/DeclObjC.h" 19 #include "clang/AST/DeclTemplate.h" 20 #include "clang/AST/TypeLoc.h" 21 #include "clang/AST/Expr.h" 22 #include "clang/AST/ExprCXX.h" 23 #include "clang/AST/ExternalASTSource.h" 24 #include "clang/AST/ASTMutationListener.h" 25 #include "clang/AST/RecordLayout.h" 26 #include "clang/AST/Mangle.h" 27 #include "clang/Basic/Builtins.h" 28 #include "clang/Basic/SourceManager.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "llvm/ADT/SmallString.h" 31 #include "llvm/ADT/StringExtras.h" 32 #include "llvm/Support/MathExtras.h" 33 #include "llvm/Support/raw_ostream.h" 34 #include "llvm/Support/Capacity.h" 35 #include "CXXABI.h" 36 #include <map> 37 38 using namespace clang; 39 40 unsigned ASTContext::NumImplicitDefaultConstructors; 41 unsigned ASTContext::NumImplicitDefaultConstructorsDeclared; 42 unsigned ASTContext::NumImplicitCopyConstructors; 43 unsigned ASTContext::NumImplicitCopyConstructorsDeclared; 44 unsigned ASTContext::NumImplicitMoveConstructors; 45 unsigned ASTContext::NumImplicitMoveConstructorsDeclared; 46 unsigned ASTContext::NumImplicitCopyAssignmentOperators; 47 unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 48 unsigned ASTContext::NumImplicitMoveAssignmentOperators; 49 unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 50 unsigned ASTContext::NumImplicitDestructors; 51 unsigned ASTContext::NumImplicitDestructorsDeclared; 52 53 enum FloatingRank { 54 HalfRank, FloatRank, DoubleRank, LongDoubleRank 55 }; 56 57 RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const { 58 if (!CommentsLoaded && ExternalSource) { 59 ExternalSource->ReadComments(); 60 CommentsLoaded = true; 61 } 62 63 assert(D); 64 65 // User can not attach documentation to implicit declarations. 66 if (D->isImplicit()) 67 return NULL; 68 69 // User can not attach documentation to implicit instantiations. 70 // FIXME: all these implicit instantiations shoud be marked as implicit 71 // declarations and get caught by condition above. 72 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 73 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 74 return NULL; 75 } 76 77 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 78 if (VD->isStaticDataMember() && 79 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 80 return NULL; 81 } 82 83 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) { 84 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 85 return NULL; 86 } 87 88 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) { 89 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 90 return NULL; 91 } 92 93 // TODO: handle comments for function parameters properly. 94 if (isa<ParmVarDecl>(D)) 95 return NULL; 96 97 // TODO: we could look up template parameter documentation in the template 98 // documentation. 99 if (isa<TemplateTypeParmDecl>(D) || 100 isa<NonTypeTemplateParmDecl>(D) || 101 isa<TemplateTemplateParmDecl>(D)) 102 return NULL; 103 104 ArrayRef<RawComment *> RawComments = Comments.getComments(); 105 106 // If there are no comments anywhere, we won't find anything. 107 if (RawComments.empty()) 108 return NULL; 109 110 // Find declaration location. 111 // For Objective-C declarations we generally don't expect to have multiple 112 // declarators, thus use declaration starting location as the "declaration 113 // location". 114 // For all other declarations multiple declarators are used quite frequently, 115 // so we use the location of the identifier as the "declaration location". 116 SourceLocation DeclLoc; 117 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) || 118 isa<ObjCPropertyDecl>(D) || 119 isa<RedeclarableTemplateDecl>(D) || 120 isa<ClassTemplateSpecializationDecl>(D)) 121 DeclLoc = D->getLocStart(); 122 else 123 DeclLoc = D->getLocation(); 124 125 // If the declaration doesn't map directly to a location in a file, we 126 // can't find the comment. 127 if (DeclLoc.isInvalid() || !DeclLoc.isFileID()) 128 return NULL; 129 130 // Find the comment that occurs just after this declaration. 131 ArrayRef<RawComment *>::iterator Comment; 132 { 133 // When searching for comments during parsing, the comment we are looking 134 // for is usually among the last two comments we parsed -- check them 135 // first. 136 RawComment CommentAtDeclLoc(SourceMgr, SourceRange(DeclLoc)); 137 BeforeThanCompare<RawComment> Compare(SourceMgr); 138 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1; 139 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc); 140 if (!Found && RawComments.size() >= 2) { 141 MaybeBeforeDecl--; 142 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc); 143 } 144 145 if (Found) { 146 Comment = MaybeBeforeDecl + 1; 147 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(), 148 &CommentAtDeclLoc, Compare)); 149 } else { 150 // Slow path. 151 Comment = std::lower_bound(RawComments.begin(), RawComments.end(), 152 &CommentAtDeclLoc, Compare); 153 } 154 } 155 156 // Decompose the location for the declaration and find the beginning of the 157 // file buffer. 158 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc); 159 160 // First check whether we have a trailing comment. 161 if (Comment != RawComments.end() && 162 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() && 163 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D))) { 164 std::pair<FileID, unsigned> CommentBeginDecomp 165 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin()); 166 // Check that Doxygen trailing comment comes after the declaration, starts 167 // on the same line and in the same file as the declaration. 168 if (DeclLocDecomp.first == CommentBeginDecomp.first && 169 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) 170 == SourceMgr.getLineNumber(CommentBeginDecomp.first, 171 CommentBeginDecomp.second)) { 172 return *Comment; 173 } 174 } 175 176 // The comment just after the declaration was not a trailing comment. 177 // Let's look at the previous comment. 178 if (Comment == RawComments.begin()) 179 return NULL; 180 --Comment; 181 182 // Check that we actually have a non-member Doxygen comment. 183 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment()) 184 return NULL; 185 186 // Decompose the end of the comment. 187 std::pair<FileID, unsigned> CommentEndDecomp 188 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd()); 189 190 // If the comment and the declaration aren't in the same file, then they 191 // aren't related. 192 if (DeclLocDecomp.first != CommentEndDecomp.first) 193 return NULL; 194 195 // Get the corresponding buffer. 196 bool Invalid = false; 197 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first, 198 &Invalid).data(); 199 if (Invalid) 200 return NULL; 201 202 // Extract text between the comment and declaration. 203 StringRef Text(Buffer + CommentEndDecomp.second, 204 DeclLocDecomp.second - CommentEndDecomp.second); 205 206 // There should be no other declarations or preprocessor directives between 207 // comment and declaration. 208 if (Text.find_first_of(",;{}#@") != StringRef::npos) 209 return NULL; 210 211 return *Comment; 212 } 213 214 namespace { 215 /// If we have a 'templated' declaration for a template, adjust 'D' to 216 /// refer to the actual template. 217 const Decl *adjustDeclToTemplate(const Decl *D) { 218 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 219 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 220 D = FTD; 221 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) { 222 if (const ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 223 D = CTD; 224 } 225 // FIXME: Alias templates? 226 return D; 227 } 228 } // unnamed namespace 229 230 const RawComment *ASTContext::getRawCommentForAnyRedecl( 231 const Decl *D, 232 const Decl **OriginalDecl) const { 233 D = adjustDeclToTemplate(D); 234 235 // Check whether we have cached a comment for this declaration already. 236 { 237 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos = 238 RedeclComments.find(D); 239 if (Pos != RedeclComments.end()) { 240 const RawCommentAndCacheFlags &Raw = Pos->second; 241 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) { 242 if (OriginalDecl) 243 *OriginalDecl = Raw.getOriginalDecl(); 244 return Raw.getRaw(); 245 } 246 } 247 } 248 249 // Search for comments attached to declarations in the redeclaration chain. 250 const RawComment *RC = NULL; 251 const Decl *OriginalDeclForRC = NULL; 252 for (Decl::redecl_iterator I = D->redecls_begin(), 253 E = D->redecls_end(); 254 I != E; ++I) { 255 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos = 256 RedeclComments.find(*I); 257 if (Pos != RedeclComments.end()) { 258 const RawCommentAndCacheFlags &Raw = Pos->second; 259 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) { 260 RC = Raw.getRaw(); 261 OriginalDeclForRC = Raw.getOriginalDecl(); 262 break; 263 } 264 } else { 265 RC = getRawCommentForDeclNoCache(*I); 266 OriginalDeclForRC = *I; 267 RawCommentAndCacheFlags Raw; 268 if (RC) { 269 Raw.setRaw(RC); 270 Raw.setKind(RawCommentAndCacheFlags::FromDecl); 271 } else 272 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl); 273 Raw.setOriginalDecl(*I); 274 RedeclComments[*I] = Raw; 275 if (RC) 276 break; 277 } 278 } 279 280 // If we found a comment, it should be a documentation comment. 281 assert(!RC || RC->isDocumentation()); 282 283 if (OriginalDecl) 284 *OriginalDecl = OriginalDeclForRC; 285 286 // Update cache for every declaration in the redeclaration chain. 287 RawCommentAndCacheFlags Raw; 288 Raw.setRaw(RC); 289 Raw.setKind(RawCommentAndCacheFlags::FromRedecl); 290 Raw.setOriginalDecl(OriginalDeclForRC); 291 292 for (Decl::redecl_iterator I = D->redecls_begin(), 293 E = D->redecls_end(); 294 I != E; ++I) { 295 RawCommentAndCacheFlags &R = RedeclComments[*I]; 296 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl) 297 R = Raw; 298 } 299 300 return RC; 301 } 302 303 comments::FullComment *ASTContext::getCommentForDecl(const Decl *D) const { 304 D = adjustDeclToTemplate(D); 305 const Decl *Canonical = D->getCanonicalDecl(); 306 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos = 307 ParsedComments.find(Canonical); 308 if (Pos != ParsedComments.end()) 309 return Pos->second; 310 311 const Decl *OriginalDecl; 312 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl); 313 if (!RC) 314 return NULL; 315 316 if (D != OriginalDecl) 317 return getCommentForDecl(OriginalDecl); 318 319 comments::FullComment *FC = RC->parse(*this, D); 320 ParsedComments[Canonical] = FC; 321 return FC; 322 } 323 324 void 325 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID, 326 TemplateTemplateParmDecl *Parm) { 327 ID.AddInteger(Parm->getDepth()); 328 ID.AddInteger(Parm->getPosition()); 329 ID.AddBoolean(Parm->isParameterPack()); 330 331 TemplateParameterList *Params = Parm->getTemplateParameters(); 332 ID.AddInteger(Params->size()); 333 for (TemplateParameterList::const_iterator P = Params->begin(), 334 PEnd = Params->end(); 335 P != PEnd; ++P) { 336 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { 337 ID.AddInteger(0); 338 ID.AddBoolean(TTP->isParameterPack()); 339 continue; 340 } 341 342 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 343 ID.AddInteger(1); 344 ID.AddBoolean(NTTP->isParameterPack()); 345 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr()); 346 if (NTTP->isExpandedParameterPack()) { 347 ID.AddBoolean(true); 348 ID.AddInteger(NTTP->getNumExpansionTypes()); 349 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { 350 QualType T = NTTP->getExpansionType(I); 351 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr()); 352 } 353 } else 354 ID.AddBoolean(false); 355 continue; 356 } 357 358 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P); 359 ID.AddInteger(2); 360 Profile(ID, TTP); 361 } 362 } 363 364 TemplateTemplateParmDecl * 365 ASTContext::getCanonicalTemplateTemplateParmDecl( 366 TemplateTemplateParmDecl *TTP) const { 367 // Check if we already have a canonical template template parameter. 368 llvm::FoldingSetNodeID ID; 369 CanonicalTemplateTemplateParm::Profile(ID, TTP); 370 void *InsertPos = 0; 371 CanonicalTemplateTemplateParm *Canonical 372 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 373 if (Canonical) 374 return Canonical->getParam(); 375 376 // Build a canonical template parameter list. 377 TemplateParameterList *Params = TTP->getTemplateParameters(); 378 SmallVector<NamedDecl *, 4> CanonParams; 379 CanonParams.reserve(Params->size()); 380 for (TemplateParameterList::const_iterator P = Params->begin(), 381 PEnd = Params->end(); 382 P != PEnd; ++P) { 383 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) 384 CanonParams.push_back( 385 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(), 386 SourceLocation(), 387 SourceLocation(), 388 TTP->getDepth(), 389 TTP->getIndex(), 0, false, 390 TTP->isParameterPack())); 391 else if (NonTypeTemplateParmDecl *NTTP 392 = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 393 QualType T = getCanonicalType(NTTP->getType()); 394 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); 395 NonTypeTemplateParmDecl *Param; 396 if (NTTP->isExpandedParameterPack()) { 397 SmallVector<QualType, 2> ExpandedTypes; 398 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos; 399 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { 400 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I))); 401 ExpandedTInfos.push_back( 402 getTrivialTypeSourceInfo(ExpandedTypes.back())); 403 } 404 405 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 406 SourceLocation(), 407 SourceLocation(), 408 NTTP->getDepth(), 409 NTTP->getPosition(), 0, 410 T, 411 TInfo, 412 ExpandedTypes.data(), 413 ExpandedTypes.size(), 414 ExpandedTInfos.data()); 415 } else { 416 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 417 SourceLocation(), 418 SourceLocation(), 419 NTTP->getDepth(), 420 NTTP->getPosition(), 0, 421 T, 422 NTTP->isParameterPack(), 423 TInfo); 424 } 425 CanonParams.push_back(Param); 426 427 } else 428 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl( 429 cast<TemplateTemplateParmDecl>(*P))); 430 } 431 432 TemplateTemplateParmDecl *CanonTTP 433 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 434 SourceLocation(), TTP->getDepth(), 435 TTP->getPosition(), 436 TTP->isParameterPack(), 437 0, 438 TemplateParameterList::Create(*this, SourceLocation(), 439 SourceLocation(), 440 CanonParams.data(), 441 CanonParams.size(), 442 SourceLocation())); 443 444 // Get the new insert position for the node we care about. 445 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 446 assert(Canonical == 0 && "Shouldn't be in the map!"); 447 (void)Canonical; 448 449 // Create the canonical template template parameter entry. 450 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP); 451 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos); 452 return CanonTTP; 453 } 454 455 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) { 456 if (!LangOpts.CPlusPlus) return 0; 457 458 switch (T.getCXXABI()) { 459 case CXXABI_ARM: 460 return CreateARMCXXABI(*this); 461 case CXXABI_Itanium: 462 return CreateItaniumCXXABI(*this); 463 case CXXABI_Microsoft: 464 return CreateMicrosoftCXXABI(*this); 465 } 466 llvm_unreachable("Invalid CXXABI type!"); 467 } 468 469 static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T, 470 const LangOptions &LOpts) { 471 if (LOpts.FakeAddressSpaceMap) { 472 // The fake address space map must have a distinct entry for each 473 // language-specific address space. 474 static const unsigned FakeAddrSpaceMap[] = { 475 1, // opencl_global 476 2, // opencl_local 477 3, // opencl_constant 478 4, // cuda_device 479 5, // cuda_constant 480 6 // cuda_shared 481 }; 482 return &FakeAddrSpaceMap; 483 } else { 484 return &T.getAddressSpaceMap(); 485 } 486 } 487 488 ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM, 489 const TargetInfo *t, 490 IdentifierTable &idents, SelectorTable &sels, 491 Builtin::Context &builtins, 492 unsigned size_reserve, 493 bool DelayInitialization) 494 : FunctionProtoTypes(this_()), 495 TemplateSpecializationTypes(this_()), 496 DependentTemplateSpecializationTypes(this_()), 497 SubstTemplateTemplateParmPacks(this_()), 498 GlobalNestedNameSpecifier(0), 499 Int128Decl(0), UInt128Decl(0), 500 BuiltinVaListDecl(0), 501 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0), 502 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0), 503 FILEDecl(0), 504 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0), 505 BlockDescriptorType(0), BlockDescriptorExtendedType(0), 506 cudaConfigureCallDecl(0), 507 NullTypeSourceInfo(QualType()), 508 FirstLocalImport(), LastLocalImport(), 509 SourceMgr(SM), LangOpts(LOpts), 510 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts), 511 Idents(idents), Selectors(sels), 512 BuiltinInfo(builtins), 513 DeclarationNames(*this), 514 ExternalSource(0), Listener(0), 515 Comments(SM), CommentsLoaded(false), 516 LastSDM(0, 0), 517 UniqueBlockByRefTypeID(0) 518 { 519 if (size_reserve > 0) Types.reserve(size_reserve); 520 TUDecl = TranslationUnitDecl::Create(*this); 521 522 if (!DelayInitialization) { 523 assert(t && "No target supplied for ASTContext initialization"); 524 InitBuiltinTypes(*t); 525 } 526 } 527 528 ASTContext::~ASTContext() { 529 // Release the DenseMaps associated with DeclContext objects. 530 // FIXME: Is this the ideal solution? 531 ReleaseDeclContextMaps(); 532 533 // Call all of the deallocation functions. 534 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I) 535 Deallocations[I].first(Deallocations[I].second); 536 537 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed 538 // because they can contain DenseMaps. 539 for (llvm::DenseMap<const ObjCContainerDecl*, 540 const ASTRecordLayout*>::iterator 541 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) 542 // Increment in loop to prevent using deallocated memory. 543 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second)) 544 R->Destroy(*this); 545 546 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator 547 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) { 548 // Increment in loop to prevent using deallocated memory. 549 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second)) 550 R->Destroy(*this); 551 } 552 553 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(), 554 AEnd = DeclAttrs.end(); 555 A != AEnd; ++A) 556 A->second->~AttrVec(); 557 } 558 559 void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) { 560 Deallocations.push_back(std::make_pair(Callback, Data)); 561 } 562 563 void 564 ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) { 565 ExternalSource.reset(Source.take()); 566 } 567 568 void ASTContext::PrintStats() const { 569 llvm::errs() << "\n*** AST Context Stats:\n"; 570 llvm::errs() << " " << Types.size() << " types total.\n"; 571 572 unsigned counts[] = { 573 #define TYPE(Name, Parent) 0, 574 #define ABSTRACT_TYPE(Name, Parent) 575 #include "clang/AST/TypeNodes.def" 576 0 // Extra 577 }; 578 579 for (unsigned i = 0, e = Types.size(); i != e; ++i) { 580 Type *T = Types[i]; 581 counts[(unsigned)T->getTypeClass()]++; 582 } 583 584 unsigned Idx = 0; 585 unsigned TotalBytes = 0; 586 #define TYPE(Name, Parent) \ 587 if (counts[Idx]) \ 588 llvm::errs() << " " << counts[Idx] << " " << #Name \ 589 << " types\n"; \ 590 TotalBytes += counts[Idx] * sizeof(Name##Type); \ 591 ++Idx; 592 #define ABSTRACT_TYPE(Name, Parent) 593 #include "clang/AST/TypeNodes.def" 594 595 llvm::errs() << "Total bytes = " << TotalBytes << "\n"; 596 597 // Implicit special member functions. 598 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/" 599 << NumImplicitDefaultConstructors 600 << " implicit default constructors created\n"; 601 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/" 602 << NumImplicitCopyConstructors 603 << " implicit copy constructors created\n"; 604 if (getLangOpts().CPlusPlus) 605 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/" 606 << NumImplicitMoveConstructors 607 << " implicit move constructors created\n"; 608 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/" 609 << NumImplicitCopyAssignmentOperators 610 << " implicit copy assignment operators created\n"; 611 if (getLangOpts().CPlusPlus) 612 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/" 613 << NumImplicitMoveAssignmentOperators 614 << " implicit move assignment operators created\n"; 615 llvm::errs() << NumImplicitDestructorsDeclared << "/" 616 << NumImplicitDestructors 617 << " implicit destructors created\n"; 618 619 if (ExternalSource.get()) { 620 llvm::errs() << "\n"; 621 ExternalSource->PrintStats(); 622 } 623 624 BumpAlloc.PrintStats(); 625 } 626 627 TypedefDecl *ASTContext::getInt128Decl() const { 628 if (!Int128Decl) { 629 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty); 630 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this), 631 getTranslationUnitDecl(), 632 SourceLocation(), 633 SourceLocation(), 634 &Idents.get("__int128_t"), 635 TInfo); 636 } 637 638 return Int128Decl; 639 } 640 641 TypedefDecl *ASTContext::getUInt128Decl() const { 642 if (!UInt128Decl) { 643 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty); 644 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this), 645 getTranslationUnitDecl(), 646 SourceLocation(), 647 SourceLocation(), 648 &Idents.get("__uint128_t"), 649 TInfo); 650 } 651 652 return UInt128Decl; 653 } 654 655 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) { 656 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K); 657 R = CanQualType::CreateUnsafe(QualType(Ty, 0)); 658 Types.push_back(Ty); 659 } 660 661 void ASTContext::InitBuiltinTypes(const TargetInfo &Target) { 662 assert((!this->Target || this->Target == &Target) && 663 "Incorrect target reinitialization"); 664 assert(VoidTy.isNull() && "Context reinitialized?"); 665 666 this->Target = &Target; 667 668 ABI.reset(createCXXABI(Target)); 669 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts); 670 671 // C99 6.2.5p19. 672 InitBuiltinType(VoidTy, BuiltinType::Void); 673 674 // C99 6.2.5p2. 675 InitBuiltinType(BoolTy, BuiltinType::Bool); 676 // C99 6.2.5p3. 677 if (LangOpts.CharIsSigned) 678 InitBuiltinType(CharTy, BuiltinType::Char_S); 679 else 680 InitBuiltinType(CharTy, BuiltinType::Char_U); 681 // C99 6.2.5p4. 682 InitBuiltinType(SignedCharTy, BuiltinType::SChar); 683 InitBuiltinType(ShortTy, BuiltinType::Short); 684 InitBuiltinType(IntTy, BuiltinType::Int); 685 InitBuiltinType(LongTy, BuiltinType::Long); 686 InitBuiltinType(LongLongTy, BuiltinType::LongLong); 687 688 // C99 6.2.5p6. 689 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar); 690 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort); 691 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt); 692 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong); 693 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong); 694 695 // C99 6.2.5p10. 696 InitBuiltinType(FloatTy, BuiltinType::Float); 697 InitBuiltinType(DoubleTy, BuiltinType::Double); 698 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble); 699 700 // GNU extension, 128-bit integers. 701 InitBuiltinType(Int128Ty, BuiltinType::Int128); 702 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128); 703 704 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5 705 if (TargetInfo::isTypeSigned(Target.getWCharType())) 706 InitBuiltinType(WCharTy, BuiltinType::WChar_S); 707 else // -fshort-wchar makes wchar_t be unsigned. 708 InitBuiltinType(WCharTy, BuiltinType::WChar_U); 709 } else // C99 710 WCharTy = getFromTargetType(Target.getWCharType()); 711 712 WIntTy = getFromTargetType(Target.getWIntType()); 713 714 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 715 InitBuiltinType(Char16Ty, BuiltinType::Char16); 716 else // C99 717 Char16Ty = getFromTargetType(Target.getChar16Type()); 718 719 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 720 InitBuiltinType(Char32Ty, BuiltinType::Char32); 721 else // C99 722 Char32Ty = getFromTargetType(Target.getChar32Type()); 723 724 // Placeholder type for type-dependent expressions whose type is 725 // completely unknown. No code should ever check a type against 726 // DependentTy and users should never see it; however, it is here to 727 // help diagnose failures to properly check for type-dependent 728 // expressions. 729 InitBuiltinType(DependentTy, BuiltinType::Dependent); 730 731 // Placeholder type for functions. 732 InitBuiltinType(OverloadTy, BuiltinType::Overload); 733 734 // Placeholder type for bound members. 735 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember); 736 737 // Placeholder type for pseudo-objects. 738 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject); 739 740 // "any" type; useful for debugger-like clients. 741 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny); 742 743 // Placeholder type for unbridged ARC casts. 744 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast); 745 746 // C99 6.2.5p11. 747 FloatComplexTy = getComplexType(FloatTy); 748 DoubleComplexTy = getComplexType(DoubleTy); 749 LongDoubleComplexTy = getComplexType(LongDoubleTy); 750 751 // Builtin types for 'id', 'Class', and 'SEL'. 752 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId); 753 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass); 754 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel); 755 756 // Builtin type for __objc_yes and __objc_no 757 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ? 758 SignedCharTy : BoolTy); 759 760 ObjCConstantStringType = QualType(); 761 762 // void * type 763 VoidPtrTy = getPointerType(VoidTy); 764 765 // nullptr type (C++0x 2.14.7) 766 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr); 767 768 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16 769 InitBuiltinType(HalfTy, BuiltinType::Half); 770 771 // Builtin type used to help define __builtin_va_list. 772 VaListTagTy = QualType(); 773 } 774 775 DiagnosticsEngine &ASTContext::getDiagnostics() const { 776 return SourceMgr.getDiagnostics(); 777 } 778 779 AttrVec& ASTContext::getDeclAttrs(const Decl *D) { 780 AttrVec *&Result = DeclAttrs[D]; 781 if (!Result) { 782 void *Mem = Allocate(sizeof(AttrVec)); 783 Result = new (Mem) AttrVec; 784 } 785 786 return *Result; 787 } 788 789 /// \brief Erase the attributes corresponding to the given declaration. 790 void ASTContext::eraseDeclAttrs(const Decl *D) { 791 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D); 792 if (Pos != DeclAttrs.end()) { 793 Pos->second->~AttrVec(); 794 DeclAttrs.erase(Pos); 795 } 796 } 797 798 MemberSpecializationInfo * 799 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) { 800 assert(Var->isStaticDataMember() && "Not a static data member"); 801 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos 802 = InstantiatedFromStaticDataMember.find(Var); 803 if (Pos == InstantiatedFromStaticDataMember.end()) 804 return 0; 805 806 return Pos->second; 807 } 808 809 void 810 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, 811 TemplateSpecializationKind TSK, 812 SourceLocation PointOfInstantiation) { 813 assert(Inst->isStaticDataMember() && "Not a static data member"); 814 assert(Tmpl->isStaticDataMember() && "Not a static data member"); 815 assert(!InstantiatedFromStaticDataMember[Inst] && 816 "Already noted what static data member was instantiated from"); 817 InstantiatedFromStaticDataMember[Inst] 818 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation); 819 } 820 821 FunctionDecl *ASTContext::getClassScopeSpecializationPattern( 822 const FunctionDecl *FD){ 823 assert(FD && "Specialization is 0"); 824 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos 825 = ClassScopeSpecializationPattern.find(FD); 826 if (Pos == ClassScopeSpecializationPattern.end()) 827 return 0; 828 829 return Pos->second; 830 } 831 832 void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD, 833 FunctionDecl *Pattern) { 834 assert(FD && "Specialization is 0"); 835 assert(Pattern && "Class scope specialization pattern is 0"); 836 ClassScopeSpecializationPattern[FD] = Pattern; 837 } 838 839 NamedDecl * 840 ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) { 841 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos 842 = InstantiatedFromUsingDecl.find(UUD); 843 if (Pos == InstantiatedFromUsingDecl.end()) 844 return 0; 845 846 return Pos->second; 847 } 848 849 void 850 ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) { 851 assert((isa<UsingDecl>(Pattern) || 852 isa<UnresolvedUsingValueDecl>(Pattern) || 853 isa<UnresolvedUsingTypenameDecl>(Pattern)) && 854 "pattern decl is not a using decl"); 855 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists"); 856 InstantiatedFromUsingDecl[Inst] = Pattern; 857 } 858 859 UsingShadowDecl * 860 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) { 861 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos 862 = InstantiatedFromUsingShadowDecl.find(Inst); 863 if (Pos == InstantiatedFromUsingShadowDecl.end()) 864 return 0; 865 866 return Pos->second; 867 } 868 869 void 870 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, 871 UsingShadowDecl *Pattern) { 872 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists"); 873 InstantiatedFromUsingShadowDecl[Inst] = Pattern; 874 } 875 876 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) { 877 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos 878 = InstantiatedFromUnnamedFieldDecl.find(Field); 879 if (Pos == InstantiatedFromUnnamedFieldDecl.end()) 880 return 0; 881 882 return Pos->second; 883 } 884 885 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, 886 FieldDecl *Tmpl) { 887 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed"); 888 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed"); 889 assert(!InstantiatedFromUnnamedFieldDecl[Inst] && 890 "Already noted what unnamed field was instantiated from"); 891 892 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl; 893 } 894 895 bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD, 896 const FieldDecl *LastFD) const { 897 return (FD->isBitField() && LastFD && !LastFD->isBitField() && 898 FD->getBitWidthValue(*this) == 0); 899 } 900 901 bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD, 902 const FieldDecl *LastFD) const { 903 return (FD->isBitField() && LastFD && LastFD->isBitField() && 904 FD->getBitWidthValue(*this) == 0 && 905 LastFD->getBitWidthValue(*this) != 0); 906 } 907 908 bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD, 909 const FieldDecl *LastFD) const { 910 return (FD->isBitField() && LastFD && LastFD->isBitField() && 911 FD->getBitWidthValue(*this) && 912 LastFD->getBitWidthValue(*this)); 913 } 914 915 bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD, 916 const FieldDecl *LastFD) const { 917 return (!FD->isBitField() && LastFD && LastFD->isBitField() && 918 LastFD->getBitWidthValue(*this)); 919 } 920 921 bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD, 922 const FieldDecl *LastFD) const { 923 return (FD->isBitField() && LastFD && !LastFD->isBitField() && 924 FD->getBitWidthValue(*this)); 925 } 926 927 ASTContext::overridden_cxx_method_iterator 928 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const { 929 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos 930 = OverriddenMethods.find(Method); 931 if (Pos == OverriddenMethods.end()) 932 return 0; 933 934 return Pos->second.begin(); 935 } 936 937 ASTContext::overridden_cxx_method_iterator 938 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const { 939 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos 940 = OverriddenMethods.find(Method); 941 if (Pos == OverriddenMethods.end()) 942 return 0; 943 944 return Pos->second.end(); 945 } 946 947 unsigned 948 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const { 949 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos 950 = OverriddenMethods.find(Method); 951 if (Pos == OverriddenMethods.end()) 952 return 0; 953 954 return Pos->second.size(); 955 } 956 957 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method, 958 const CXXMethodDecl *Overridden) { 959 OverriddenMethods[Method].push_back(Overridden); 960 } 961 962 void ASTContext::addedLocalImportDecl(ImportDecl *Import) { 963 assert(!Import->NextLocalImport && "Import declaration already in the chain"); 964 assert(!Import->isFromASTFile() && "Non-local import declaration"); 965 if (!FirstLocalImport) { 966 FirstLocalImport = Import; 967 LastLocalImport = Import; 968 return; 969 } 970 971 LastLocalImport->NextLocalImport = Import; 972 LastLocalImport = Import; 973 } 974 975 //===----------------------------------------------------------------------===// 976 // Type Sizing and Analysis 977 //===----------------------------------------------------------------------===// 978 979 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified 980 /// scalar floating point type. 981 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const { 982 const BuiltinType *BT = T->getAs<BuiltinType>(); 983 assert(BT && "Not a floating point type!"); 984 switch (BT->getKind()) { 985 default: llvm_unreachable("Not a floating point type!"); 986 case BuiltinType::Half: return Target->getHalfFormat(); 987 case BuiltinType::Float: return Target->getFloatFormat(); 988 case BuiltinType::Double: return Target->getDoubleFormat(); 989 case BuiltinType::LongDouble: return Target->getLongDoubleFormat(); 990 } 991 } 992 993 /// getDeclAlign - Return a conservative estimate of the alignment of the 994 /// specified decl. Note that bitfields do not have a valid alignment, so 995 /// this method will assert on them. 996 /// If @p RefAsPointee, references are treated like their underlying type 997 /// (for alignof), else they're treated like pointers (for CodeGen). 998 CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const { 999 unsigned Align = Target->getCharWidth(); 1000 1001 bool UseAlignAttrOnly = false; 1002 if (unsigned AlignFromAttr = D->getMaxAlignment()) { 1003 Align = AlignFromAttr; 1004 1005 // __attribute__((aligned)) can increase or decrease alignment 1006 // *except* on a struct or struct member, where it only increases 1007 // alignment unless 'packed' is also specified. 1008 // 1009 // It is an error for alignas to decrease alignment, so we can 1010 // ignore that possibility; Sema should diagnose it. 1011 if (isa<FieldDecl>(D)) { 1012 UseAlignAttrOnly = D->hasAttr<PackedAttr>() || 1013 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 1014 } else { 1015 UseAlignAttrOnly = true; 1016 } 1017 } 1018 else if (isa<FieldDecl>(D)) 1019 UseAlignAttrOnly = 1020 D->hasAttr<PackedAttr>() || 1021 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 1022 1023 // If we're using the align attribute only, just ignore everything 1024 // else about the declaration and its type. 1025 if (UseAlignAttrOnly) { 1026 // do nothing 1027 1028 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 1029 QualType T = VD->getType(); 1030 if (const ReferenceType* RT = T->getAs<ReferenceType>()) { 1031 if (RefAsPointee) 1032 T = RT->getPointeeType(); 1033 else 1034 T = getPointerType(RT->getPointeeType()); 1035 } 1036 if (!T->isIncompleteType() && !T->isFunctionType()) { 1037 // Adjust alignments of declarations with array type by the 1038 // large-array alignment on the target. 1039 unsigned MinWidth = Target->getLargeArrayMinWidth(); 1040 const ArrayType *arrayType; 1041 if (MinWidth && (arrayType = getAsArrayType(T))) { 1042 if (isa<VariableArrayType>(arrayType)) 1043 Align = std::max(Align, Target->getLargeArrayAlign()); 1044 else if (isa<ConstantArrayType>(arrayType) && 1045 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType))) 1046 Align = std::max(Align, Target->getLargeArrayAlign()); 1047 1048 // Walk through any array types while we're at it. 1049 T = getBaseElementType(arrayType); 1050 } 1051 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr())); 1052 } 1053 1054 // Fields can be subject to extra alignment constraints, like if 1055 // the field is packed, the struct is packed, or the struct has a 1056 // a max-field-alignment constraint (#pragma pack). So calculate 1057 // the actual alignment of the field within the struct, and then 1058 // (as we're expected to) constrain that by the alignment of the type. 1059 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) { 1060 // So calculate the alignment of the field. 1061 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent()); 1062 1063 // Start with the record's overall alignment. 1064 unsigned fieldAlign = toBits(layout.getAlignment()); 1065 1066 // Use the GCD of that and the offset within the record. 1067 uint64_t offset = layout.getFieldOffset(field->getFieldIndex()); 1068 if (offset > 0) { 1069 // Alignment is always a power of 2, so the GCD will be a power of 2, 1070 // which means we get to do this crazy thing instead of Euclid's. 1071 uint64_t lowBitOfOffset = offset & (~offset + 1); 1072 if (lowBitOfOffset < fieldAlign) 1073 fieldAlign = static_cast<unsigned>(lowBitOfOffset); 1074 } 1075 1076 Align = std::min(Align, fieldAlign); 1077 } 1078 } 1079 1080 return toCharUnitsFromBits(Align); 1081 } 1082 1083 // getTypeInfoDataSizeInChars - Return the size of a type, in 1084 // chars. If the type is a record, its data size is returned. This is 1085 // the size of the memcpy that's performed when assigning this type 1086 // using a trivial copy/move assignment operator. 1087 std::pair<CharUnits, CharUnits> 1088 ASTContext::getTypeInfoDataSizeInChars(QualType T) const { 1089 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T); 1090 1091 // In C++, objects can sometimes be allocated into the tail padding 1092 // of a base-class subobject. We decide whether that's possible 1093 // during class layout, so here we can just trust the layout results. 1094 if (getLangOpts().CPlusPlus) { 1095 if (const RecordType *RT = T->getAs<RecordType>()) { 1096 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl()); 1097 sizeAndAlign.first = layout.getDataSize(); 1098 } 1099 } 1100 1101 return sizeAndAlign; 1102 } 1103 1104 std::pair<CharUnits, CharUnits> 1105 ASTContext::getTypeInfoInChars(const Type *T) const { 1106 std::pair<uint64_t, unsigned> Info = getTypeInfo(T); 1107 return std::make_pair(toCharUnitsFromBits(Info.first), 1108 toCharUnitsFromBits(Info.second)); 1109 } 1110 1111 std::pair<CharUnits, CharUnits> 1112 ASTContext::getTypeInfoInChars(QualType T) const { 1113 return getTypeInfoInChars(T.getTypePtr()); 1114 } 1115 1116 std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const { 1117 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T); 1118 if (it != MemoizedTypeInfo.end()) 1119 return it->second; 1120 1121 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T); 1122 MemoizedTypeInfo.insert(std::make_pair(T, Info)); 1123 return Info; 1124 } 1125 1126 /// getTypeInfoImpl - Return the size of the specified type, in bits. This 1127 /// method does not work on incomplete types. 1128 /// 1129 /// FIXME: Pointers into different addr spaces could have different sizes and 1130 /// alignment requirements: getPointerInfo should take an AddrSpace, this 1131 /// should take a QualType, &c. 1132 std::pair<uint64_t, unsigned> 1133 ASTContext::getTypeInfoImpl(const Type *T) const { 1134 uint64_t Width=0; 1135 unsigned Align=8; 1136 switch (T->getTypeClass()) { 1137 #define TYPE(Class, Base) 1138 #define ABSTRACT_TYPE(Class, Base) 1139 #define NON_CANONICAL_TYPE(Class, Base) 1140 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 1141 #include "clang/AST/TypeNodes.def" 1142 llvm_unreachable("Should not see dependent types"); 1143 1144 case Type::FunctionNoProto: 1145 case Type::FunctionProto: 1146 // GCC extension: alignof(function) = 32 bits 1147 Width = 0; 1148 Align = 32; 1149 break; 1150 1151 case Type::IncompleteArray: 1152 case Type::VariableArray: 1153 Width = 0; 1154 Align = getTypeAlign(cast<ArrayType>(T)->getElementType()); 1155 break; 1156 1157 case Type::ConstantArray: { 1158 const ConstantArrayType *CAT = cast<ConstantArrayType>(T); 1159 1160 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType()); 1161 uint64_t Size = CAT->getSize().getZExtValue(); 1162 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) && 1163 "Overflow in array type bit size evaluation"); 1164 Width = EltInfo.first*Size; 1165 Align = EltInfo.second; 1166 Width = llvm::RoundUpToAlignment(Width, Align); 1167 break; 1168 } 1169 case Type::ExtVector: 1170 case Type::Vector: { 1171 const VectorType *VT = cast<VectorType>(T); 1172 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType()); 1173 Width = EltInfo.first*VT->getNumElements(); 1174 Align = Width; 1175 // If the alignment is not a power of 2, round up to the next power of 2. 1176 // This happens for non-power-of-2 length vectors. 1177 if (Align & (Align-1)) { 1178 Align = llvm::NextPowerOf2(Align); 1179 Width = llvm::RoundUpToAlignment(Width, Align); 1180 } 1181 // Adjust the alignment based on the target max. 1182 uint64_t TargetVectorAlign = Target->getMaxVectorAlign(); 1183 if (TargetVectorAlign && TargetVectorAlign < Align) 1184 Align = TargetVectorAlign; 1185 break; 1186 } 1187 1188 case Type::Builtin: 1189 switch (cast<BuiltinType>(T)->getKind()) { 1190 default: llvm_unreachable("Unknown builtin type!"); 1191 case BuiltinType::Void: 1192 // GCC extension: alignof(void) = 8 bits. 1193 Width = 0; 1194 Align = 8; 1195 break; 1196 1197 case BuiltinType::Bool: 1198 Width = Target->getBoolWidth(); 1199 Align = Target->getBoolAlign(); 1200 break; 1201 case BuiltinType::Char_S: 1202 case BuiltinType::Char_U: 1203 case BuiltinType::UChar: 1204 case BuiltinType::SChar: 1205 Width = Target->getCharWidth(); 1206 Align = Target->getCharAlign(); 1207 break; 1208 case BuiltinType::WChar_S: 1209 case BuiltinType::WChar_U: 1210 Width = Target->getWCharWidth(); 1211 Align = Target->getWCharAlign(); 1212 break; 1213 case BuiltinType::Char16: 1214 Width = Target->getChar16Width(); 1215 Align = Target->getChar16Align(); 1216 break; 1217 case BuiltinType::Char32: 1218 Width = Target->getChar32Width(); 1219 Align = Target->getChar32Align(); 1220 break; 1221 case BuiltinType::UShort: 1222 case BuiltinType::Short: 1223 Width = Target->getShortWidth(); 1224 Align = Target->getShortAlign(); 1225 break; 1226 case BuiltinType::UInt: 1227 case BuiltinType::Int: 1228 Width = Target->getIntWidth(); 1229 Align = Target->getIntAlign(); 1230 break; 1231 case BuiltinType::ULong: 1232 case BuiltinType::Long: 1233 Width = Target->getLongWidth(); 1234 Align = Target->getLongAlign(); 1235 break; 1236 case BuiltinType::ULongLong: 1237 case BuiltinType::LongLong: 1238 Width = Target->getLongLongWidth(); 1239 Align = Target->getLongLongAlign(); 1240 break; 1241 case BuiltinType::Int128: 1242 case BuiltinType::UInt128: 1243 Width = 128; 1244 Align = 128; // int128_t is 128-bit aligned on all targets. 1245 break; 1246 case BuiltinType::Half: 1247 Width = Target->getHalfWidth(); 1248 Align = Target->getHalfAlign(); 1249 break; 1250 case BuiltinType::Float: 1251 Width = Target->getFloatWidth(); 1252 Align = Target->getFloatAlign(); 1253 break; 1254 case BuiltinType::Double: 1255 Width = Target->getDoubleWidth(); 1256 Align = Target->getDoubleAlign(); 1257 break; 1258 case BuiltinType::LongDouble: 1259 Width = Target->getLongDoubleWidth(); 1260 Align = Target->getLongDoubleAlign(); 1261 break; 1262 case BuiltinType::NullPtr: 1263 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t) 1264 Align = Target->getPointerAlign(0); // == sizeof(void*) 1265 break; 1266 case BuiltinType::ObjCId: 1267 case BuiltinType::ObjCClass: 1268 case BuiltinType::ObjCSel: 1269 Width = Target->getPointerWidth(0); 1270 Align = Target->getPointerAlign(0); 1271 break; 1272 } 1273 break; 1274 case Type::ObjCObjectPointer: 1275 Width = Target->getPointerWidth(0); 1276 Align = Target->getPointerAlign(0); 1277 break; 1278 case Type::BlockPointer: { 1279 unsigned AS = getTargetAddressSpace( 1280 cast<BlockPointerType>(T)->getPointeeType()); 1281 Width = Target->getPointerWidth(AS); 1282 Align = Target->getPointerAlign(AS); 1283 break; 1284 } 1285 case Type::LValueReference: 1286 case Type::RValueReference: { 1287 // alignof and sizeof should never enter this code path here, so we go 1288 // the pointer route. 1289 unsigned AS = getTargetAddressSpace( 1290 cast<ReferenceType>(T)->getPointeeType()); 1291 Width = Target->getPointerWidth(AS); 1292 Align = Target->getPointerAlign(AS); 1293 break; 1294 } 1295 case Type::Pointer: { 1296 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType()); 1297 Width = Target->getPointerWidth(AS); 1298 Align = Target->getPointerAlign(AS); 1299 break; 1300 } 1301 case Type::MemberPointer: { 1302 const MemberPointerType *MPT = cast<MemberPointerType>(T); 1303 std::pair<uint64_t, unsigned> PtrDiffInfo = 1304 getTypeInfo(getPointerDiffType()); 1305 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT); 1306 Align = PtrDiffInfo.second; 1307 break; 1308 } 1309 case Type::Complex: { 1310 // Complex types have the same alignment as their elements, but twice the 1311 // size. 1312 std::pair<uint64_t, unsigned> EltInfo = 1313 getTypeInfo(cast<ComplexType>(T)->getElementType()); 1314 Width = EltInfo.first*2; 1315 Align = EltInfo.second; 1316 break; 1317 } 1318 case Type::ObjCObject: 1319 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr()); 1320 case Type::ObjCInterface: { 1321 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T); 1322 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 1323 Width = toBits(Layout.getSize()); 1324 Align = toBits(Layout.getAlignment()); 1325 break; 1326 } 1327 case Type::Record: 1328 case Type::Enum: { 1329 const TagType *TT = cast<TagType>(T); 1330 1331 if (TT->getDecl()->isInvalidDecl()) { 1332 Width = 8; 1333 Align = 8; 1334 break; 1335 } 1336 1337 if (const EnumType *ET = dyn_cast<EnumType>(TT)) 1338 return getTypeInfo(ET->getDecl()->getIntegerType()); 1339 1340 const RecordType *RT = cast<RecordType>(TT); 1341 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl()); 1342 Width = toBits(Layout.getSize()); 1343 Align = toBits(Layout.getAlignment()); 1344 break; 1345 } 1346 1347 case Type::SubstTemplateTypeParm: 1348 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)-> 1349 getReplacementType().getTypePtr()); 1350 1351 case Type::Auto: { 1352 const AutoType *A = cast<AutoType>(T); 1353 assert(A->isDeduced() && "Cannot request the size of a dependent type"); 1354 return getTypeInfo(A->getDeducedType().getTypePtr()); 1355 } 1356 1357 case Type::Paren: 1358 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr()); 1359 1360 case Type::Typedef: { 1361 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl(); 1362 std::pair<uint64_t, unsigned> Info 1363 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr()); 1364 // If the typedef has an aligned attribute on it, it overrides any computed 1365 // alignment we have. This violates the GCC documentation (which says that 1366 // attribute(aligned) can only round up) but matches its implementation. 1367 if (unsigned AttrAlign = Typedef->getMaxAlignment()) 1368 Align = AttrAlign; 1369 else 1370 Align = Info.second; 1371 Width = Info.first; 1372 break; 1373 } 1374 1375 case Type::TypeOfExpr: 1376 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType() 1377 .getTypePtr()); 1378 1379 case Type::TypeOf: 1380 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr()); 1381 1382 case Type::Decltype: 1383 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType() 1384 .getTypePtr()); 1385 1386 case Type::UnaryTransform: 1387 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType()); 1388 1389 case Type::Elaborated: 1390 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr()); 1391 1392 case Type::Attributed: 1393 return getTypeInfo( 1394 cast<AttributedType>(T)->getEquivalentType().getTypePtr()); 1395 1396 case Type::TemplateSpecialization: { 1397 assert(getCanonicalType(T) != T && 1398 "Cannot request the size of a dependent type"); 1399 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T); 1400 // A type alias template specialization may refer to a typedef with the 1401 // aligned attribute on it. 1402 if (TST->isTypeAlias()) 1403 return getTypeInfo(TST->getAliasedType().getTypePtr()); 1404 else 1405 return getTypeInfo(getCanonicalType(T)); 1406 } 1407 1408 case Type::Atomic: { 1409 std::pair<uint64_t, unsigned> Info 1410 = getTypeInfo(cast<AtomicType>(T)->getValueType()); 1411 Width = Info.first; 1412 Align = Info.second; 1413 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() && 1414 llvm::isPowerOf2_64(Width)) { 1415 // We can potentially perform lock-free atomic operations for this 1416 // type; promote the alignment appropriately. 1417 // FIXME: We could potentially promote the width here as well... 1418 // is that worthwhile? (Non-struct atomic types generally have 1419 // power-of-two size anyway, but structs might not. Requires a bit 1420 // of implementation work to make sure we zero out the extra bits.) 1421 Align = static_cast<unsigned>(Width); 1422 } 1423 } 1424 1425 } 1426 1427 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2"); 1428 return std::make_pair(Width, Align); 1429 } 1430 1431 /// toCharUnitsFromBits - Convert a size in bits to a size in characters. 1432 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const { 1433 return CharUnits::fromQuantity(BitSize / getCharWidth()); 1434 } 1435 1436 /// toBits - Convert a size in characters to a size in characters. 1437 int64_t ASTContext::toBits(CharUnits CharSize) const { 1438 return CharSize.getQuantity() * getCharWidth(); 1439 } 1440 1441 /// getTypeSizeInChars - Return the size of the specified type, in characters. 1442 /// This method does not work on incomplete types. 1443 CharUnits ASTContext::getTypeSizeInChars(QualType T) const { 1444 return toCharUnitsFromBits(getTypeSize(T)); 1445 } 1446 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const { 1447 return toCharUnitsFromBits(getTypeSize(T)); 1448 } 1449 1450 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in 1451 /// characters. This method does not work on incomplete types. 1452 CharUnits ASTContext::getTypeAlignInChars(QualType T) const { 1453 return toCharUnitsFromBits(getTypeAlign(T)); 1454 } 1455 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const { 1456 return toCharUnitsFromBits(getTypeAlign(T)); 1457 } 1458 1459 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified 1460 /// type for the current target in bits. This can be different than the ABI 1461 /// alignment in cases where it is beneficial for performance to overalign 1462 /// a data type. 1463 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const { 1464 unsigned ABIAlign = getTypeAlign(T); 1465 1466 // Double and long long should be naturally aligned if possible. 1467 if (const ComplexType* CT = T->getAs<ComplexType>()) 1468 T = CT->getElementType().getTypePtr(); 1469 if (T->isSpecificBuiltinType(BuiltinType::Double) || 1470 T->isSpecificBuiltinType(BuiltinType::LongLong) || 1471 T->isSpecificBuiltinType(BuiltinType::ULongLong)) 1472 return std::max(ABIAlign, (unsigned)getTypeSize(T)); 1473 1474 return ABIAlign; 1475 } 1476 1477 /// DeepCollectObjCIvars - 1478 /// This routine first collects all declared, but not synthesized, ivars in 1479 /// super class and then collects all ivars, including those synthesized for 1480 /// current class. This routine is used for implementation of current class 1481 /// when all ivars, declared and synthesized are known. 1482 /// 1483 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, 1484 bool leafClass, 1485 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const { 1486 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass()) 1487 DeepCollectObjCIvars(SuperClass, false, Ivars); 1488 if (!leafClass) { 1489 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(), 1490 E = OI->ivar_end(); I != E; ++I) 1491 Ivars.push_back(*I); 1492 } else { 1493 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI); 1494 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv; 1495 Iv= Iv->getNextIvar()) 1496 Ivars.push_back(Iv); 1497 } 1498 } 1499 1500 /// CollectInheritedProtocols - Collect all protocols in current class and 1501 /// those inherited by it. 1502 void ASTContext::CollectInheritedProtocols(const Decl *CDecl, 1503 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) { 1504 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) { 1505 // We can use protocol_iterator here instead of 1506 // all_referenced_protocol_iterator since we are walking all categories. 1507 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(), 1508 PE = OI->all_referenced_protocol_end(); P != PE; ++P) { 1509 ObjCProtocolDecl *Proto = (*P); 1510 Protocols.insert(Proto->getCanonicalDecl()); 1511 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(), 1512 PE = Proto->protocol_end(); P != PE; ++P) { 1513 Protocols.insert((*P)->getCanonicalDecl()); 1514 CollectInheritedProtocols(*P, Protocols); 1515 } 1516 } 1517 1518 // Categories of this Interface. 1519 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList(); 1520 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory()) 1521 CollectInheritedProtocols(CDeclChain, Protocols); 1522 if (ObjCInterfaceDecl *SD = OI->getSuperClass()) 1523 while (SD) { 1524 CollectInheritedProtocols(SD, Protocols); 1525 SD = SD->getSuperClass(); 1526 } 1527 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) { 1528 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(), 1529 PE = OC->protocol_end(); P != PE; ++P) { 1530 ObjCProtocolDecl *Proto = (*P); 1531 Protocols.insert(Proto->getCanonicalDecl()); 1532 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(), 1533 PE = Proto->protocol_end(); P != PE; ++P) 1534 CollectInheritedProtocols(*P, Protocols); 1535 } 1536 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) { 1537 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(), 1538 PE = OP->protocol_end(); P != PE; ++P) { 1539 ObjCProtocolDecl *Proto = (*P); 1540 Protocols.insert(Proto->getCanonicalDecl()); 1541 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(), 1542 PE = Proto->protocol_end(); P != PE; ++P) 1543 CollectInheritedProtocols(*P, Protocols); 1544 } 1545 } 1546 } 1547 1548 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const { 1549 unsigned count = 0; 1550 // Count ivars declared in class extension. 1551 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl; 1552 CDecl = CDecl->getNextClassExtension()) 1553 count += CDecl->ivar_size(); 1554 1555 // Count ivar defined in this class's implementation. This 1556 // includes synthesized ivars. 1557 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) 1558 count += ImplDecl->ivar_size(); 1559 1560 return count; 1561 } 1562 1563 bool ASTContext::isSentinelNullExpr(const Expr *E) { 1564 if (!E) 1565 return false; 1566 1567 // nullptr_t is always treated as null. 1568 if (E->getType()->isNullPtrType()) return true; 1569 1570 if (E->getType()->isAnyPointerType() && 1571 E->IgnoreParenCasts()->isNullPointerConstant(*this, 1572 Expr::NPC_ValueDependentIsNull)) 1573 return true; 1574 1575 // Unfortunately, __null has type 'int'. 1576 if (isa<GNUNullExpr>(E)) return true; 1577 1578 return false; 1579 } 1580 1581 /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists. 1582 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) { 1583 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 1584 I = ObjCImpls.find(D); 1585 if (I != ObjCImpls.end()) 1586 return cast<ObjCImplementationDecl>(I->second); 1587 return 0; 1588 } 1589 /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists. 1590 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) { 1591 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 1592 I = ObjCImpls.find(D); 1593 if (I != ObjCImpls.end()) 1594 return cast<ObjCCategoryImplDecl>(I->second); 1595 return 0; 1596 } 1597 1598 /// \brief Set the implementation of ObjCInterfaceDecl. 1599 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD, 1600 ObjCImplementationDecl *ImplD) { 1601 assert(IFaceD && ImplD && "Passed null params"); 1602 ObjCImpls[IFaceD] = ImplD; 1603 } 1604 /// \brief Set the implementation of ObjCCategoryDecl. 1605 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD, 1606 ObjCCategoryImplDecl *ImplD) { 1607 assert(CatD && ImplD && "Passed null params"); 1608 ObjCImpls[CatD] = ImplD; 1609 } 1610 1611 ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const { 1612 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext())) 1613 return ID; 1614 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext())) 1615 return CD->getClassInterface(); 1616 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext())) 1617 return IMD->getClassInterface(); 1618 1619 return 0; 1620 } 1621 1622 /// \brief Get the copy initialization expression of VarDecl,or NULL if 1623 /// none exists. 1624 Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) { 1625 assert(VD && "Passed null params"); 1626 assert(VD->hasAttr<BlocksAttr>() && 1627 "getBlockVarCopyInits - not __block var"); 1628 llvm::DenseMap<const VarDecl*, Expr*>::iterator 1629 I = BlockVarCopyInits.find(VD); 1630 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0; 1631 } 1632 1633 /// \brief Set the copy inialization expression of a block var decl. 1634 void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) { 1635 assert(VD && Init && "Passed null params"); 1636 assert(VD->hasAttr<BlocksAttr>() && 1637 "setBlockVarCopyInits - not __block var"); 1638 BlockVarCopyInits[VD] = Init; 1639 } 1640 1641 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T, 1642 unsigned DataSize) const { 1643 if (!DataSize) 1644 DataSize = TypeLoc::getFullDataSizeForType(T); 1645 else 1646 assert(DataSize == TypeLoc::getFullDataSizeForType(T) && 1647 "incorrect data size provided to CreateTypeSourceInfo!"); 1648 1649 TypeSourceInfo *TInfo = 1650 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8); 1651 new (TInfo) TypeSourceInfo(T); 1652 return TInfo; 1653 } 1654 1655 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T, 1656 SourceLocation L) const { 1657 TypeSourceInfo *DI = CreateTypeSourceInfo(T); 1658 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L); 1659 return DI; 1660 } 1661 1662 const ASTRecordLayout & 1663 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const { 1664 return getObjCLayout(D, 0); 1665 } 1666 1667 const ASTRecordLayout & 1668 ASTContext::getASTObjCImplementationLayout( 1669 const ObjCImplementationDecl *D) const { 1670 return getObjCLayout(D->getClassInterface(), D); 1671 } 1672 1673 //===----------------------------------------------------------------------===// 1674 // Type creation/memoization methods 1675 //===----------------------------------------------------------------------===// 1676 1677 QualType 1678 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const { 1679 unsigned fastQuals = quals.getFastQualifiers(); 1680 quals.removeFastQualifiers(); 1681 1682 // Check if we've already instantiated this type. 1683 llvm::FoldingSetNodeID ID; 1684 ExtQuals::Profile(ID, baseType, quals); 1685 void *insertPos = 0; 1686 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) { 1687 assert(eq->getQualifiers() == quals); 1688 return QualType(eq, fastQuals); 1689 } 1690 1691 // If the base type is not canonical, make the appropriate canonical type. 1692 QualType canon; 1693 if (!baseType->isCanonicalUnqualified()) { 1694 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split(); 1695 canonSplit.Quals.addConsistentQualifiers(quals); 1696 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals); 1697 1698 // Re-find the insert position. 1699 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos); 1700 } 1701 1702 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals); 1703 ExtQualNodes.InsertNode(eq, insertPos); 1704 return QualType(eq, fastQuals); 1705 } 1706 1707 QualType 1708 ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const { 1709 QualType CanT = getCanonicalType(T); 1710 if (CanT.getAddressSpace() == AddressSpace) 1711 return T; 1712 1713 // If we are composing extended qualifiers together, merge together 1714 // into one ExtQuals node. 1715 QualifierCollector Quals; 1716 const Type *TypeNode = Quals.strip(T); 1717 1718 // If this type already has an address space specified, it cannot get 1719 // another one. 1720 assert(!Quals.hasAddressSpace() && 1721 "Type cannot be in multiple addr spaces!"); 1722 Quals.addAddressSpace(AddressSpace); 1723 1724 return getExtQualType(TypeNode, Quals); 1725 } 1726 1727 QualType ASTContext::getObjCGCQualType(QualType T, 1728 Qualifiers::GC GCAttr) const { 1729 QualType CanT = getCanonicalType(T); 1730 if (CanT.getObjCGCAttr() == GCAttr) 1731 return T; 1732 1733 if (const PointerType *ptr = T->getAs<PointerType>()) { 1734 QualType Pointee = ptr->getPointeeType(); 1735 if (Pointee->isAnyPointerType()) { 1736 QualType ResultType = getObjCGCQualType(Pointee, GCAttr); 1737 return getPointerType(ResultType); 1738 } 1739 } 1740 1741 // If we are composing extended qualifiers together, merge together 1742 // into one ExtQuals node. 1743 QualifierCollector Quals; 1744 const Type *TypeNode = Quals.strip(T); 1745 1746 // If this type already has an ObjCGC specified, it cannot get 1747 // another one. 1748 assert(!Quals.hasObjCGCAttr() && 1749 "Type cannot have multiple ObjCGCs!"); 1750 Quals.addObjCGCAttr(GCAttr); 1751 1752 return getExtQualType(TypeNode, Quals); 1753 } 1754 1755 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T, 1756 FunctionType::ExtInfo Info) { 1757 if (T->getExtInfo() == Info) 1758 return T; 1759 1760 QualType Result; 1761 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) { 1762 Result = getFunctionNoProtoType(FNPT->getResultType(), Info); 1763 } else { 1764 const FunctionProtoType *FPT = cast<FunctionProtoType>(T); 1765 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 1766 EPI.ExtInfo = Info; 1767 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(), 1768 FPT->getNumArgs(), EPI); 1769 } 1770 1771 return cast<FunctionType>(Result.getTypePtr()); 1772 } 1773 1774 /// getComplexType - Return the uniqued reference to the type for a complex 1775 /// number with the specified element type. 1776 QualType ASTContext::getComplexType(QualType T) const { 1777 // Unique pointers, to guarantee there is only one pointer of a particular 1778 // structure. 1779 llvm::FoldingSetNodeID ID; 1780 ComplexType::Profile(ID, T); 1781 1782 void *InsertPos = 0; 1783 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos)) 1784 return QualType(CT, 0); 1785 1786 // If the pointee type isn't canonical, this won't be a canonical type either, 1787 // so fill in the canonical type field. 1788 QualType Canonical; 1789 if (!T.isCanonical()) { 1790 Canonical = getComplexType(getCanonicalType(T)); 1791 1792 // Get the new insert position for the node we care about. 1793 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos); 1794 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 1795 } 1796 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical); 1797 Types.push_back(New); 1798 ComplexTypes.InsertNode(New, InsertPos); 1799 return QualType(New, 0); 1800 } 1801 1802 /// getPointerType - Return the uniqued reference to the type for a pointer to 1803 /// the specified type. 1804 QualType ASTContext::getPointerType(QualType T) const { 1805 // Unique pointers, to guarantee there is only one pointer of a particular 1806 // structure. 1807 llvm::FoldingSetNodeID ID; 1808 PointerType::Profile(ID, T); 1809 1810 void *InsertPos = 0; 1811 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 1812 return QualType(PT, 0); 1813 1814 // If the pointee type isn't canonical, this won't be a canonical type either, 1815 // so fill in the canonical type field. 1816 QualType Canonical; 1817 if (!T.isCanonical()) { 1818 Canonical = getPointerType(getCanonicalType(T)); 1819 1820 // Get the new insert position for the node we care about. 1821 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos); 1822 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 1823 } 1824 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical); 1825 Types.push_back(New); 1826 PointerTypes.InsertNode(New, InsertPos); 1827 return QualType(New, 0); 1828 } 1829 1830 /// getBlockPointerType - Return the uniqued reference to the type for 1831 /// a pointer to the specified block. 1832 QualType ASTContext::getBlockPointerType(QualType T) const { 1833 assert(T->isFunctionType() && "block of function types only"); 1834 // Unique pointers, to guarantee there is only one block of a particular 1835 // structure. 1836 llvm::FoldingSetNodeID ID; 1837 BlockPointerType::Profile(ID, T); 1838 1839 void *InsertPos = 0; 1840 if (BlockPointerType *PT = 1841 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 1842 return QualType(PT, 0); 1843 1844 // If the block pointee type isn't canonical, this won't be a canonical 1845 // type either so fill in the canonical type field. 1846 QualType Canonical; 1847 if (!T.isCanonical()) { 1848 Canonical = getBlockPointerType(getCanonicalType(T)); 1849 1850 // Get the new insert position for the node we care about. 1851 BlockPointerType *NewIP = 1852 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 1853 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 1854 } 1855 BlockPointerType *New 1856 = new (*this, TypeAlignment) BlockPointerType(T, Canonical); 1857 Types.push_back(New); 1858 BlockPointerTypes.InsertNode(New, InsertPos); 1859 return QualType(New, 0); 1860 } 1861 1862 /// getLValueReferenceType - Return the uniqued reference to the type for an 1863 /// lvalue reference to the specified type. 1864 QualType 1865 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const { 1866 assert(getCanonicalType(T) != OverloadTy && 1867 "Unresolved overloaded function type"); 1868 1869 // Unique pointers, to guarantee there is only one pointer of a particular 1870 // structure. 1871 llvm::FoldingSetNodeID ID; 1872 ReferenceType::Profile(ID, T, SpelledAsLValue); 1873 1874 void *InsertPos = 0; 1875 if (LValueReferenceType *RT = 1876 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 1877 return QualType(RT, 0); 1878 1879 const ReferenceType *InnerRef = T->getAs<ReferenceType>(); 1880 1881 // If the referencee type isn't canonical, this won't be a canonical type 1882 // either, so fill in the canonical type field. 1883 QualType Canonical; 1884 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) { 1885 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 1886 Canonical = getLValueReferenceType(getCanonicalType(PointeeType)); 1887 1888 // Get the new insert position for the node we care about. 1889 LValueReferenceType *NewIP = 1890 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 1891 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 1892 } 1893 1894 LValueReferenceType *New 1895 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical, 1896 SpelledAsLValue); 1897 Types.push_back(New); 1898 LValueReferenceTypes.InsertNode(New, InsertPos); 1899 1900 return QualType(New, 0); 1901 } 1902 1903 /// getRValueReferenceType - Return the uniqued reference to the type for an 1904 /// rvalue reference to the specified type. 1905 QualType ASTContext::getRValueReferenceType(QualType T) const { 1906 // Unique pointers, to guarantee there is only one pointer of a particular 1907 // structure. 1908 llvm::FoldingSetNodeID ID; 1909 ReferenceType::Profile(ID, T, false); 1910 1911 void *InsertPos = 0; 1912 if (RValueReferenceType *RT = 1913 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 1914 return QualType(RT, 0); 1915 1916 const ReferenceType *InnerRef = T->getAs<ReferenceType>(); 1917 1918 // If the referencee type isn't canonical, this won't be a canonical type 1919 // either, so fill in the canonical type field. 1920 QualType Canonical; 1921 if (InnerRef || !T.isCanonical()) { 1922 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 1923 Canonical = getRValueReferenceType(getCanonicalType(PointeeType)); 1924 1925 // Get the new insert position for the node we care about. 1926 RValueReferenceType *NewIP = 1927 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 1928 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 1929 } 1930 1931 RValueReferenceType *New 1932 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical); 1933 Types.push_back(New); 1934 RValueReferenceTypes.InsertNode(New, InsertPos); 1935 return QualType(New, 0); 1936 } 1937 1938 /// getMemberPointerType - Return the uniqued reference to the type for a 1939 /// member pointer to the specified type, in the specified class. 1940 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const { 1941 // Unique pointers, to guarantee there is only one pointer of a particular 1942 // structure. 1943 llvm::FoldingSetNodeID ID; 1944 MemberPointerType::Profile(ID, T, Cls); 1945 1946 void *InsertPos = 0; 1947 if (MemberPointerType *PT = 1948 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 1949 return QualType(PT, 0); 1950 1951 // If the pointee or class type isn't canonical, this won't be a canonical 1952 // type either, so fill in the canonical type field. 1953 QualType Canonical; 1954 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) { 1955 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls)); 1956 1957 // Get the new insert position for the node we care about. 1958 MemberPointerType *NewIP = 1959 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 1960 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 1961 } 1962 MemberPointerType *New 1963 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical); 1964 Types.push_back(New); 1965 MemberPointerTypes.InsertNode(New, InsertPos); 1966 return QualType(New, 0); 1967 } 1968 1969 /// getConstantArrayType - Return the unique reference to the type for an 1970 /// array of the specified element type. 1971 QualType ASTContext::getConstantArrayType(QualType EltTy, 1972 const llvm::APInt &ArySizeIn, 1973 ArrayType::ArraySizeModifier ASM, 1974 unsigned IndexTypeQuals) const { 1975 assert((EltTy->isDependentType() || 1976 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) && 1977 "Constant array of VLAs is illegal!"); 1978 1979 // Convert the array size into a canonical width matching the pointer size for 1980 // the target. 1981 llvm::APInt ArySize(ArySizeIn); 1982 ArySize = 1983 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy))); 1984 1985 llvm::FoldingSetNodeID ID; 1986 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals); 1987 1988 void *InsertPos = 0; 1989 if (ConstantArrayType *ATP = 1990 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 1991 return QualType(ATP, 0); 1992 1993 // If the element type isn't canonical or has qualifiers, this won't 1994 // be a canonical type either, so fill in the canonical type field. 1995 QualType Canon; 1996 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) { 1997 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 1998 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, 1999 ASM, IndexTypeQuals); 2000 Canon = getQualifiedType(Canon, canonSplit.Quals); 2001 2002 // Get the new insert position for the node we care about. 2003 ConstantArrayType *NewIP = 2004 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 2005 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 2006 } 2007 2008 ConstantArrayType *New = new(*this,TypeAlignment) 2009 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals); 2010 ConstantArrayTypes.InsertNode(New, InsertPos); 2011 Types.push_back(New); 2012 return QualType(New, 0); 2013 } 2014 2015 /// getVariableArrayDecayedType - Turns the given type, which may be 2016 /// variably-modified, into the corresponding type with all the known 2017 /// sizes replaced with [*]. 2018 QualType ASTContext::getVariableArrayDecayedType(QualType type) const { 2019 // Vastly most common case. 2020 if (!type->isVariablyModifiedType()) return type; 2021 2022 QualType result; 2023 2024 SplitQualType split = type.getSplitDesugaredType(); 2025 const Type *ty = split.Ty; 2026 switch (ty->getTypeClass()) { 2027 #define TYPE(Class, Base) 2028 #define ABSTRACT_TYPE(Class, Base) 2029 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 2030 #include "clang/AST/TypeNodes.def" 2031 llvm_unreachable("didn't desugar past all non-canonical types?"); 2032 2033 // These types should never be variably-modified. 2034 case Type::Builtin: 2035 case Type::Complex: 2036 case Type::Vector: 2037 case Type::ExtVector: 2038 case Type::DependentSizedExtVector: 2039 case Type::ObjCObject: 2040 case Type::ObjCInterface: 2041 case Type::ObjCObjectPointer: 2042 case Type::Record: 2043 case Type::Enum: 2044 case Type::UnresolvedUsing: 2045 case Type::TypeOfExpr: 2046 case Type::TypeOf: 2047 case Type::Decltype: 2048 case Type::UnaryTransform: 2049 case Type::DependentName: 2050 case Type::InjectedClassName: 2051 case Type::TemplateSpecialization: 2052 case Type::DependentTemplateSpecialization: 2053 case Type::TemplateTypeParm: 2054 case Type::SubstTemplateTypeParmPack: 2055 case Type::Auto: 2056 case Type::PackExpansion: 2057 llvm_unreachable("type should never be variably-modified"); 2058 2059 // These types can be variably-modified but should never need to 2060 // further decay. 2061 case Type::FunctionNoProto: 2062 case Type::FunctionProto: 2063 case Type::BlockPointer: 2064 case Type::MemberPointer: 2065 return type; 2066 2067 // These types can be variably-modified. All these modifications 2068 // preserve structure except as noted by comments. 2069 // TODO: if we ever care about optimizing VLAs, there are no-op 2070 // optimizations available here. 2071 case Type::Pointer: 2072 result = getPointerType(getVariableArrayDecayedType( 2073 cast<PointerType>(ty)->getPointeeType())); 2074 break; 2075 2076 case Type::LValueReference: { 2077 const LValueReferenceType *lv = cast<LValueReferenceType>(ty); 2078 result = getLValueReferenceType( 2079 getVariableArrayDecayedType(lv->getPointeeType()), 2080 lv->isSpelledAsLValue()); 2081 break; 2082 } 2083 2084 case Type::RValueReference: { 2085 const RValueReferenceType *lv = cast<RValueReferenceType>(ty); 2086 result = getRValueReferenceType( 2087 getVariableArrayDecayedType(lv->getPointeeType())); 2088 break; 2089 } 2090 2091 case Type::Atomic: { 2092 const AtomicType *at = cast<AtomicType>(ty); 2093 result = getAtomicType(getVariableArrayDecayedType(at->getValueType())); 2094 break; 2095 } 2096 2097 case Type::ConstantArray: { 2098 const ConstantArrayType *cat = cast<ConstantArrayType>(ty); 2099 result = getConstantArrayType( 2100 getVariableArrayDecayedType(cat->getElementType()), 2101 cat->getSize(), 2102 cat->getSizeModifier(), 2103 cat->getIndexTypeCVRQualifiers()); 2104 break; 2105 } 2106 2107 case Type::DependentSizedArray: { 2108 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty); 2109 result = getDependentSizedArrayType( 2110 getVariableArrayDecayedType(dat->getElementType()), 2111 dat->getSizeExpr(), 2112 dat->getSizeModifier(), 2113 dat->getIndexTypeCVRQualifiers(), 2114 dat->getBracketsRange()); 2115 break; 2116 } 2117 2118 // Turn incomplete types into [*] types. 2119 case Type::IncompleteArray: { 2120 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty); 2121 result = getVariableArrayType( 2122 getVariableArrayDecayedType(iat->getElementType()), 2123 /*size*/ 0, 2124 ArrayType::Normal, 2125 iat->getIndexTypeCVRQualifiers(), 2126 SourceRange()); 2127 break; 2128 } 2129 2130 // Turn VLA types into [*] types. 2131 case Type::VariableArray: { 2132 const VariableArrayType *vat = cast<VariableArrayType>(ty); 2133 result = getVariableArrayType( 2134 getVariableArrayDecayedType(vat->getElementType()), 2135 /*size*/ 0, 2136 ArrayType::Star, 2137 vat->getIndexTypeCVRQualifiers(), 2138 vat->getBracketsRange()); 2139 break; 2140 } 2141 } 2142 2143 // Apply the top-level qualifiers from the original. 2144 return getQualifiedType(result, split.Quals); 2145 } 2146 2147 /// getVariableArrayType - Returns a non-unique reference to the type for a 2148 /// variable array of the specified element type. 2149 QualType ASTContext::getVariableArrayType(QualType EltTy, 2150 Expr *NumElts, 2151 ArrayType::ArraySizeModifier ASM, 2152 unsigned IndexTypeQuals, 2153 SourceRange Brackets) const { 2154 // Since we don't unique expressions, it isn't possible to unique VLA's 2155 // that have an expression provided for their size. 2156 QualType Canon; 2157 2158 // Be sure to pull qualifiers off the element type. 2159 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) { 2160 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 2161 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM, 2162 IndexTypeQuals, Brackets); 2163 Canon = getQualifiedType(Canon, canonSplit.Quals); 2164 } 2165 2166 VariableArrayType *New = new(*this, TypeAlignment) 2167 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets); 2168 2169 VariableArrayTypes.push_back(New); 2170 Types.push_back(New); 2171 return QualType(New, 0); 2172 } 2173 2174 /// getDependentSizedArrayType - Returns a non-unique reference to 2175 /// the type for a dependently-sized array of the specified element 2176 /// type. 2177 QualType ASTContext::getDependentSizedArrayType(QualType elementType, 2178 Expr *numElements, 2179 ArrayType::ArraySizeModifier ASM, 2180 unsigned elementTypeQuals, 2181 SourceRange brackets) const { 2182 assert((!numElements || numElements->isTypeDependent() || 2183 numElements->isValueDependent()) && 2184 "Size must be type- or value-dependent!"); 2185 2186 // Dependently-sized array types that do not have a specified number 2187 // of elements will have their sizes deduced from a dependent 2188 // initializer. We do no canonicalization here at all, which is okay 2189 // because they can't be used in most locations. 2190 if (!numElements) { 2191 DependentSizedArrayType *newType 2192 = new (*this, TypeAlignment) 2193 DependentSizedArrayType(*this, elementType, QualType(), 2194 numElements, ASM, elementTypeQuals, 2195 brackets); 2196 Types.push_back(newType); 2197 return QualType(newType, 0); 2198 } 2199 2200 // Otherwise, we actually build a new type every time, but we 2201 // also build a canonical type. 2202 2203 SplitQualType canonElementType = getCanonicalType(elementType).split(); 2204 2205 void *insertPos = 0; 2206 llvm::FoldingSetNodeID ID; 2207 DependentSizedArrayType::Profile(ID, *this, 2208 QualType(canonElementType.Ty, 0), 2209 ASM, elementTypeQuals, numElements); 2210 2211 // Look for an existing type with these properties. 2212 DependentSizedArrayType *canonTy = 2213 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos); 2214 2215 // If we don't have one, build one. 2216 if (!canonTy) { 2217 canonTy = new (*this, TypeAlignment) 2218 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0), 2219 QualType(), numElements, ASM, elementTypeQuals, 2220 brackets); 2221 DependentSizedArrayTypes.InsertNode(canonTy, insertPos); 2222 Types.push_back(canonTy); 2223 } 2224 2225 // Apply qualifiers from the element type to the array. 2226 QualType canon = getQualifiedType(QualType(canonTy,0), 2227 canonElementType.Quals); 2228 2229 // If we didn't need extra canonicalization for the element type, 2230 // then just use that as our result. 2231 if (QualType(canonElementType.Ty, 0) == elementType) 2232 return canon; 2233 2234 // Otherwise, we need to build a type which follows the spelling 2235 // of the element type. 2236 DependentSizedArrayType *sugaredType 2237 = new (*this, TypeAlignment) 2238 DependentSizedArrayType(*this, elementType, canon, numElements, 2239 ASM, elementTypeQuals, brackets); 2240 Types.push_back(sugaredType); 2241 return QualType(sugaredType, 0); 2242 } 2243 2244 QualType ASTContext::getIncompleteArrayType(QualType elementType, 2245 ArrayType::ArraySizeModifier ASM, 2246 unsigned elementTypeQuals) const { 2247 llvm::FoldingSetNodeID ID; 2248 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals); 2249 2250 void *insertPos = 0; 2251 if (IncompleteArrayType *iat = 2252 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos)) 2253 return QualType(iat, 0); 2254 2255 // If the element type isn't canonical, this won't be a canonical type 2256 // either, so fill in the canonical type field. We also have to pull 2257 // qualifiers off the element type. 2258 QualType canon; 2259 2260 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) { 2261 SplitQualType canonSplit = getCanonicalType(elementType).split(); 2262 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0), 2263 ASM, elementTypeQuals); 2264 canon = getQualifiedType(canon, canonSplit.Quals); 2265 2266 // Get the new insert position for the node we care about. 2267 IncompleteArrayType *existing = 2268 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos); 2269 assert(!existing && "Shouldn't be in the map!"); (void) existing; 2270 } 2271 2272 IncompleteArrayType *newType = new (*this, TypeAlignment) 2273 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals); 2274 2275 IncompleteArrayTypes.InsertNode(newType, insertPos); 2276 Types.push_back(newType); 2277 return QualType(newType, 0); 2278 } 2279 2280 /// getVectorType - Return the unique reference to a vector type of 2281 /// the specified element type and size. VectorType must be a built-in type. 2282 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts, 2283 VectorType::VectorKind VecKind) const { 2284 assert(vecType->isBuiltinType()); 2285 2286 // Check if we've already instantiated a vector of this type. 2287 llvm::FoldingSetNodeID ID; 2288 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind); 2289 2290 void *InsertPos = 0; 2291 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 2292 return QualType(VTP, 0); 2293 2294 // If the element type isn't canonical, this won't be a canonical type either, 2295 // so fill in the canonical type field. 2296 QualType Canonical; 2297 if (!vecType.isCanonical()) { 2298 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind); 2299 2300 // Get the new insert position for the node we care about. 2301 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 2302 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 2303 } 2304 VectorType *New = new (*this, TypeAlignment) 2305 VectorType(vecType, NumElts, Canonical, VecKind); 2306 VectorTypes.InsertNode(New, InsertPos); 2307 Types.push_back(New); 2308 return QualType(New, 0); 2309 } 2310 2311 /// getExtVectorType - Return the unique reference to an extended vector type of 2312 /// the specified element type and size. VectorType must be a built-in type. 2313 QualType 2314 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const { 2315 assert(vecType->isBuiltinType() || vecType->isDependentType()); 2316 2317 // Check if we've already instantiated a vector of this type. 2318 llvm::FoldingSetNodeID ID; 2319 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, 2320 VectorType::GenericVector); 2321 void *InsertPos = 0; 2322 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 2323 return QualType(VTP, 0); 2324 2325 // If the element type isn't canonical, this won't be a canonical type either, 2326 // so fill in the canonical type field. 2327 QualType Canonical; 2328 if (!vecType.isCanonical()) { 2329 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts); 2330 2331 // Get the new insert position for the node we care about. 2332 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 2333 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 2334 } 2335 ExtVectorType *New = new (*this, TypeAlignment) 2336 ExtVectorType(vecType, NumElts, Canonical); 2337 VectorTypes.InsertNode(New, InsertPos); 2338 Types.push_back(New); 2339 return QualType(New, 0); 2340 } 2341 2342 QualType 2343 ASTContext::getDependentSizedExtVectorType(QualType vecType, 2344 Expr *SizeExpr, 2345 SourceLocation AttrLoc) const { 2346 llvm::FoldingSetNodeID ID; 2347 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType), 2348 SizeExpr); 2349 2350 void *InsertPos = 0; 2351 DependentSizedExtVectorType *Canon 2352 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 2353 DependentSizedExtVectorType *New; 2354 if (Canon) { 2355 // We already have a canonical version of this array type; use it as 2356 // the canonical type for a newly-built type. 2357 New = new (*this, TypeAlignment) 2358 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0), 2359 SizeExpr, AttrLoc); 2360 } else { 2361 QualType CanonVecTy = getCanonicalType(vecType); 2362 if (CanonVecTy == vecType) { 2363 New = new (*this, TypeAlignment) 2364 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr, 2365 AttrLoc); 2366 2367 DependentSizedExtVectorType *CanonCheck 2368 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 2369 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken"); 2370 (void)CanonCheck; 2371 DependentSizedExtVectorTypes.InsertNode(New, InsertPos); 2372 } else { 2373 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr, 2374 SourceLocation()); 2375 New = new (*this, TypeAlignment) 2376 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc); 2377 } 2378 } 2379 2380 Types.push_back(New); 2381 return QualType(New, 0); 2382 } 2383 2384 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'. 2385 /// 2386 QualType 2387 ASTContext::getFunctionNoProtoType(QualType ResultTy, 2388 const FunctionType::ExtInfo &Info) const { 2389 const CallingConv DefaultCC = Info.getCC(); 2390 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ? 2391 CC_X86StdCall : DefaultCC; 2392 // Unique functions, to guarantee there is only one function of a particular 2393 // structure. 2394 llvm::FoldingSetNodeID ID; 2395 FunctionNoProtoType::Profile(ID, ResultTy, Info); 2396 2397 void *InsertPos = 0; 2398 if (FunctionNoProtoType *FT = 2399 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 2400 return QualType(FT, 0); 2401 2402 QualType Canonical; 2403 if (!ResultTy.isCanonical() || 2404 getCanonicalCallConv(CallConv) != CallConv) { 2405 Canonical = 2406 getFunctionNoProtoType(getCanonicalType(ResultTy), 2407 Info.withCallingConv(getCanonicalCallConv(CallConv))); 2408 2409 // Get the new insert position for the node we care about. 2410 FunctionNoProtoType *NewIP = 2411 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 2412 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 2413 } 2414 2415 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv); 2416 FunctionNoProtoType *New = new (*this, TypeAlignment) 2417 FunctionNoProtoType(ResultTy, Canonical, newInfo); 2418 Types.push_back(New); 2419 FunctionNoProtoTypes.InsertNode(New, InsertPos); 2420 return QualType(New, 0); 2421 } 2422 2423 /// getFunctionType - Return a normal function type with a typed argument 2424 /// list. isVariadic indicates whether the argument list includes '...'. 2425 QualType 2426 ASTContext::getFunctionType(QualType ResultTy, 2427 const QualType *ArgArray, unsigned NumArgs, 2428 const FunctionProtoType::ExtProtoInfo &EPI) const { 2429 // Unique functions, to guarantee there is only one function of a particular 2430 // structure. 2431 llvm::FoldingSetNodeID ID; 2432 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this); 2433 2434 void *InsertPos = 0; 2435 if (FunctionProtoType *FTP = 2436 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 2437 return QualType(FTP, 0); 2438 2439 // Determine whether the type being created is already canonical or not. 2440 bool isCanonical = 2441 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() && 2442 !EPI.HasTrailingReturn; 2443 for (unsigned i = 0; i != NumArgs && isCanonical; ++i) 2444 if (!ArgArray[i].isCanonicalAsParam()) 2445 isCanonical = false; 2446 2447 const CallingConv DefaultCC = EPI.ExtInfo.getCC(); 2448 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ? 2449 CC_X86StdCall : DefaultCC; 2450 2451 // If this type isn't canonical, get the canonical version of it. 2452 // The exception spec is not part of the canonical type. 2453 QualType Canonical; 2454 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) { 2455 SmallVector<QualType, 16> CanonicalArgs; 2456 CanonicalArgs.reserve(NumArgs); 2457 for (unsigned i = 0; i != NumArgs; ++i) 2458 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i])); 2459 2460 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI; 2461 CanonicalEPI.HasTrailingReturn = false; 2462 CanonicalEPI.ExceptionSpecType = EST_None; 2463 CanonicalEPI.NumExceptions = 0; 2464 CanonicalEPI.ExtInfo 2465 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv)); 2466 2467 Canonical = getFunctionType(getCanonicalType(ResultTy), 2468 CanonicalArgs.data(), NumArgs, 2469 CanonicalEPI); 2470 2471 // Get the new insert position for the node we care about. 2472 FunctionProtoType *NewIP = 2473 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 2474 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 2475 } 2476 2477 // FunctionProtoType objects are allocated with extra bytes after 2478 // them for three variable size arrays at the end: 2479 // - parameter types 2480 // - exception types 2481 // - consumed-arguments flags 2482 // Instead of the exception types, there could be a noexcept 2483 // expression, or information used to resolve the exception 2484 // specification. 2485 size_t Size = sizeof(FunctionProtoType) + 2486 NumArgs * sizeof(QualType); 2487 if (EPI.ExceptionSpecType == EST_Dynamic) { 2488 Size += EPI.NumExceptions * sizeof(QualType); 2489 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) { 2490 Size += sizeof(Expr*); 2491 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) { 2492 Size += 2 * sizeof(FunctionDecl*); 2493 } else if (EPI.ExceptionSpecType == EST_Unevaluated) { 2494 Size += sizeof(FunctionDecl*); 2495 } 2496 if (EPI.ConsumedArguments) 2497 Size += NumArgs * sizeof(bool); 2498 2499 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment); 2500 FunctionProtoType::ExtProtoInfo newEPI = EPI; 2501 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv); 2502 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI); 2503 Types.push_back(FTP); 2504 FunctionProtoTypes.InsertNode(FTP, InsertPos); 2505 return QualType(FTP, 0); 2506 } 2507 2508 #ifndef NDEBUG 2509 static bool NeedsInjectedClassNameType(const RecordDecl *D) { 2510 if (!isa<CXXRecordDecl>(D)) return false; 2511 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D); 2512 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) 2513 return true; 2514 if (RD->getDescribedClassTemplate() && 2515 !isa<ClassTemplateSpecializationDecl>(RD)) 2516 return true; 2517 return false; 2518 } 2519 #endif 2520 2521 /// getInjectedClassNameType - Return the unique reference to the 2522 /// injected class name type for the specified templated declaration. 2523 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl, 2524 QualType TST) const { 2525 assert(NeedsInjectedClassNameType(Decl)); 2526 if (Decl->TypeForDecl) { 2527 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 2528 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) { 2529 assert(PrevDecl->TypeForDecl && "previous declaration has no type"); 2530 Decl->TypeForDecl = PrevDecl->TypeForDecl; 2531 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 2532 } else { 2533 Type *newType = 2534 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST); 2535 Decl->TypeForDecl = newType; 2536 Types.push_back(newType); 2537 } 2538 return QualType(Decl->TypeForDecl, 0); 2539 } 2540 2541 /// getTypeDeclType - Return the unique reference to the type for the 2542 /// specified type declaration. 2543 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const { 2544 assert(Decl && "Passed null for Decl param"); 2545 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case"); 2546 2547 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl)) 2548 return getTypedefType(Typedef); 2549 2550 assert(!isa<TemplateTypeParmDecl>(Decl) && 2551 "Template type parameter types are always available."); 2552 2553 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) { 2554 assert(!Record->getPreviousDecl() && 2555 "struct/union has previous declaration"); 2556 assert(!NeedsInjectedClassNameType(Record)); 2557 return getRecordType(Record); 2558 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) { 2559 assert(!Enum->getPreviousDecl() && 2560 "enum has previous declaration"); 2561 return getEnumType(Enum); 2562 } else if (const UnresolvedUsingTypenameDecl *Using = 2563 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) { 2564 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using); 2565 Decl->TypeForDecl = newType; 2566 Types.push_back(newType); 2567 } else 2568 llvm_unreachable("TypeDecl without a type?"); 2569 2570 return QualType(Decl->TypeForDecl, 0); 2571 } 2572 2573 /// getTypedefType - Return the unique reference to the type for the 2574 /// specified typedef name decl. 2575 QualType 2576 ASTContext::getTypedefType(const TypedefNameDecl *Decl, 2577 QualType Canonical) const { 2578 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 2579 2580 if (Canonical.isNull()) 2581 Canonical = getCanonicalType(Decl->getUnderlyingType()); 2582 TypedefType *newType = new(*this, TypeAlignment) 2583 TypedefType(Type::Typedef, Decl, Canonical); 2584 Decl->TypeForDecl = newType; 2585 Types.push_back(newType); 2586 return QualType(newType, 0); 2587 } 2588 2589 QualType ASTContext::getRecordType(const RecordDecl *Decl) const { 2590 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 2591 2592 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl()) 2593 if (PrevDecl->TypeForDecl) 2594 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 2595 2596 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl); 2597 Decl->TypeForDecl = newType; 2598 Types.push_back(newType); 2599 return QualType(newType, 0); 2600 } 2601 2602 QualType ASTContext::getEnumType(const EnumDecl *Decl) const { 2603 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 2604 2605 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl()) 2606 if (PrevDecl->TypeForDecl) 2607 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 2608 2609 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl); 2610 Decl->TypeForDecl = newType; 2611 Types.push_back(newType); 2612 return QualType(newType, 0); 2613 } 2614 2615 QualType ASTContext::getAttributedType(AttributedType::Kind attrKind, 2616 QualType modifiedType, 2617 QualType equivalentType) { 2618 llvm::FoldingSetNodeID id; 2619 AttributedType::Profile(id, attrKind, modifiedType, equivalentType); 2620 2621 void *insertPos = 0; 2622 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos); 2623 if (type) return QualType(type, 0); 2624 2625 QualType canon = getCanonicalType(equivalentType); 2626 type = new (*this, TypeAlignment) 2627 AttributedType(canon, attrKind, modifiedType, equivalentType); 2628 2629 Types.push_back(type); 2630 AttributedTypes.InsertNode(type, insertPos); 2631 2632 return QualType(type, 0); 2633 } 2634 2635 2636 /// \brief Retrieve a substitution-result type. 2637 QualType 2638 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm, 2639 QualType Replacement) const { 2640 assert(Replacement.isCanonical() 2641 && "replacement types must always be canonical"); 2642 2643 llvm::FoldingSetNodeID ID; 2644 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement); 2645 void *InsertPos = 0; 2646 SubstTemplateTypeParmType *SubstParm 2647 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 2648 2649 if (!SubstParm) { 2650 SubstParm = new (*this, TypeAlignment) 2651 SubstTemplateTypeParmType(Parm, Replacement); 2652 Types.push_back(SubstParm); 2653 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos); 2654 } 2655 2656 return QualType(SubstParm, 0); 2657 } 2658 2659 /// \brief Retrieve a 2660 QualType ASTContext::getSubstTemplateTypeParmPackType( 2661 const TemplateTypeParmType *Parm, 2662 const TemplateArgument &ArgPack) { 2663 #ifndef NDEBUG 2664 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(), 2665 PEnd = ArgPack.pack_end(); 2666 P != PEnd; ++P) { 2667 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type"); 2668 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type"); 2669 } 2670 #endif 2671 2672 llvm::FoldingSetNodeID ID; 2673 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack); 2674 void *InsertPos = 0; 2675 if (SubstTemplateTypeParmPackType *SubstParm 2676 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos)) 2677 return QualType(SubstParm, 0); 2678 2679 QualType Canon; 2680 if (!Parm->isCanonicalUnqualified()) { 2681 Canon = getCanonicalType(QualType(Parm, 0)); 2682 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon), 2683 ArgPack); 2684 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos); 2685 } 2686 2687 SubstTemplateTypeParmPackType *SubstParm 2688 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon, 2689 ArgPack); 2690 Types.push_back(SubstParm); 2691 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos); 2692 return QualType(SubstParm, 0); 2693 } 2694 2695 /// \brief Retrieve the template type parameter type for a template 2696 /// parameter or parameter pack with the given depth, index, and (optionally) 2697 /// name. 2698 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index, 2699 bool ParameterPack, 2700 TemplateTypeParmDecl *TTPDecl) const { 2701 llvm::FoldingSetNodeID ID; 2702 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl); 2703 void *InsertPos = 0; 2704 TemplateTypeParmType *TypeParm 2705 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 2706 2707 if (TypeParm) 2708 return QualType(TypeParm, 0); 2709 2710 if (TTPDecl) { 2711 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack); 2712 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon); 2713 2714 TemplateTypeParmType *TypeCheck 2715 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 2716 assert(!TypeCheck && "Template type parameter canonical type broken"); 2717 (void)TypeCheck; 2718 } else 2719 TypeParm = new (*this, TypeAlignment) 2720 TemplateTypeParmType(Depth, Index, ParameterPack); 2721 2722 Types.push_back(TypeParm); 2723 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos); 2724 2725 return QualType(TypeParm, 0); 2726 } 2727 2728 TypeSourceInfo * 2729 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name, 2730 SourceLocation NameLoc, 2731 const TemplateArgumentListInfo &Args, 2732 QualType Underlying) const { 2733 assert(!Name.getAsDependentTemplateName() && 2734 "No dependent template names here!"); 2735 QualType TST = getTemplateSpecializationType(Name, Args, Underlying); 2736 2737 TypeSourceInfo *DI = CreateTypeSourceInfo(TST); 2738 TemplateSpecializationTypeLoc TL 2739 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc()); 2740 TL.setTemplateKeywordLoc(SourceLocation()); 2741 TL.setTemplateNameLoc(NameLoc); 2742 TL.setLAngleLoc(Args.getLAngleLoc()); 2743 TL.setRAngleLoc(Args.getRAngleLoc()); 2744 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 2745 TL.setArgLocInfo(i, Args[i].getLocInfo()); 2746 return DI; 2747 } 2748 2749 QualType 2750 ASTContext::getTemplateSpecializationType(TemplateName Template, 2751 const TemplateArgumentListInfo &Args, 2752 QualType Underlying) const { 2753 assert(!Template.getAsDependentTemplateName() && 2754 "No dependent template names here!"); 2755 2756 unsigned NumArgs = Args.size(); 2757 2758 SmallVector<TemplateArgument, 4> ArgVec; 2759 ArgVec.reserve(NumArgs); 2760 for (unsigned i = 0; i != NumArgs; ++i) 2761 ArgVec.push_back(Args[i].getArgument()); 2762 2763 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, 2764 Underlying); 2765 } 2766 2767 #ifndef NDEBUG 2768 static bool hasAnyPackExpansions(const TemplateArgument *Args, 2769 unsigned NumArgs) { 2770 for (unsigned I = 0; I != NumArgs; ++I) 2771 if (Args[I].isPackExpansion()) 2772 return true; 2773 2774 return true; 2775 } 2776 #endif 2777 2778 QualType 2779 ASTContext::getTemplateSpecializationType(TemplateName Template, 2780 const TemplateArgument *Args, 2781 unsigned NumArgs, 2782 QualType Underlying) const { 2783 assert(!Template.getAsDependentTemplateName() && 2784 "No dependent template names here!"); 2785 // Look through qualified template names. 2786 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 2787 Template = TemplateName(QTN->getTemplateDecl()); 2788 2789 bool IsTypeAlias = 2790 Template.getAsTemplateDecl() && 2791 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl()); 2792 QualType CanonType; 2793 if (!Underlying.isNull()) 2794 CanonType = getCanonicalType(Underlying); 2795 else { 2796 // We can get here with an alias template when the specialization contains 2797 // a pack expansion that does not match up with a parameter pack. 2798 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) && 2799 "Caller must compute aliased type"); 2800 IsTypeAlias = false; 2801 CanonType = getCanonicalTemplateSpecializationType(Template, Args, 2802 NumArgs); 2803 } 2804 2805 // Allocate the (non-canonical) template specialization type, but don't 2806 // try to unique it: these types typically have location information that 2807 // we don't unique and don't want to lose. 2808 void *Mem = Allocate(sizeof(TemplateSpecializationType) + 2809 sizeof(TemplateArgument) * NumArgs + 2810 (IsTypeAlias? sizeof(QualType) : 0), 2811 TypeAlignment); 2812 TemplateSpecializationType *Spec 2813 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType, 2814 IsTypeAlias ? Underlying : QualType()); 2815 2816 Types.push_back(Spec); 2817 return QualType(Spec, 0); 2818 } 2819 2820 QualType 2821 ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template, 2822 const TemplateArgument *Args, 2823 unsigned NumArgs) const { 2824 assert(!Template.getAsDependentTemplateName() && 2825 "No dependent template names here!"); 2826 2827 // Look through qualified template names. 2828 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 2829 Template = TemplateName(QTN->getTemplateDecl()); 2830 2831 // Build the canonical template specialization type. 2832 TemplateName CanonTemplate = getCanonicalTemplateName(Template); 2833 SmallVector<TemplateArgument, 4> CanonArgs; 2834 CanonArgs.reserve(NumArgs); 2835 for (unsigned I = 0; I != NumArgs; ++I) 2836 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I])); 2837 2838 // Determine whether this canonical template specialization type already 2839 // exists. 2840 llvm::FoldingSetNodeID ID; 2841 TemplateSpecializationType::Profile(ID, CanonTemplate, 2842 CanonArgs.data(), NumArgs, *this); 2843 2844 void *InsertPos = 0; 2845 TemplateSpecializationType *Spec 2846 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 2847 2848 if (!Spec) { 2849 // Allocate a new canonical template specialization type. 2850 void *Mem = Allocate((sizeof(TemplateSpecializationType) + 2851 sizeof(TemplateArgument) * NumArgs), 2852 TypeAlignment); 2853 Spec = new (Mem) TemplateSpecializationType(CanonTemplate, 2854 CanonArgs.data(), NumArgs, 2855 QualType(), QualType()); 2856 Types.push_back(Spec); 2857 TemplateSpecializationTypes.InsertNode(Spec, InsertPos); 2858 } 2859 2860 assert(Spec->isDependentType() && 2861 "Non-dependent template-id type must have a canonical type"); 2862 return QualType(Spec, 0); 2863 } 2864 2865 QualType 2866 ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword, 2867 NestedNameSpecifier *NNS, 2868 QualType NamedType) const { 2869 llvm::FoldingSetNodeID ID; 2870 ElaboratedType::Profile(ID, Keyword, NNS, NamedType); 2871 2872 void *InsertPos = 0; 2873 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 2874 if (T) 2875 return QualType(T, 0); 2876 2877 QualType Canon = NamedType; 2878 if (!Canon.isCanonical()) { 2879 Canon = getCanonicalType(NamedType); 2880 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 2881 assert(!CheckT && "Elaborated canonical type broken"); 2882 (void)CheckT; 2883 } 2884 2885 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon); 2886 Types.push_back(T); 2887 ElaboratedTypes.InsertNode(T, InsertPos); 2888 return QualType(T, 0); 2889 } 2890 2891 QualType 2892 ASTContext::getParenType(QualType InnerType) const { 2893 llvm::FoldingSetNodeID ID; 2894 ParenType::Profile(ID, InnerType); 2895 2896 void *InsertPos = 0; 2897 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 2898 if (T) 2899 return QualType(T, 0); 2900 2901 QualType Canon = InnerType; 2902 if (!Canon.isCanonical()) { 2903 Canon = getCanonicalType(InnerType); 2904 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 2905 assert(!CheckT && "Paren canonical type broken"); 2906 (void)CheckT; 2907 } 2908 2909 T = new (*this) ParenType(InnerType, Canon); 2910 Types.push_back(T); 2911 ParenTypes.InsertNode(T, InsertPos); 2912 return QualType(T, 0); 2913 } 2914 2915 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword, 2916 NestedNameSpecifier *NNS, 2917 const IdentifierInfo *Name, 2918 QualType Canon) const { 2919 assert(NNS->isDependent() && "nested-name-specifier must be dependent"); 2920 2921 if (Canon.isNull()) { 2922 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 2923 ElaboratedTypeKeyword CanonKeyword = Keyword; 2924 if (Keyword == ETK_None) 2925 CanonKeyword = ETK_Typename; 2926 2927 if (CanonNNS != NNS || CanonKeyword != Keyword) 2928 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name); 2929 } 2930 2931 llvm::FoldingSetNodeID ID; 2932 DependentNameType::Profile(ID, Keyword, NNS, Name); 2933 2934 void *InsertPos = 0; 2935 DependentNameType *T 2936 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos); 2937 if (T) 2938 return QualType(T, 0); 2939 2940 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon); 2941 Types.push_back(T); 2942 DependentNameTypes.InsertNode(T, InsertPos); 2943 return QualType(T, 0); 2944 } 2945 2946 QualType 2947 ASTContext::getDependentTemplateSpecializationType( 2948 ElaboratedTypeKeyword Keyword, 2949 NestedNameSpecifier *NNS, 2950 const IdentifierInfo *Name, 2951 const TemplateArgumentListInfo &Args) const { 2952 // TODO: avoid this copy 2953 SmallVector<TemplateArgument, 16> ArgCopy; 2954 for (unsigned I = 0, E = Args.size(); I != E; ++I) 2955 ArgCopy.push_back(Args[I].getArgument()); 2956 return getDependentTemplateSpecializationType(Keyword, NNS, Name, 2957 ArgCopy.size(), 2958 ArgCopy.data()); 2959 } 2960 2961 QualType 2962 ASTContext::getDependentTemplateSpecializationType( 2963 ElaboratedTypeKeyword Keyword, 2964 NestedNameSpecifier *NNS, 2965 const IdentifierInfo *Name, 2966 unsigned NumArgs, 2967 const TemplateArgument *Args) const { 2968 assert((!NNS || NNS->isDependent()) && 2969 "nested-name-specifier must be dependent"); 2970 2971 llvm::FoldingSetNodeID ID; 2972 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS, 2973 Name, NumArgs, Args); 2974 2975 void *InsertPos = 0; 2976 DependentTemplateSpecializationType *T 2977 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 2978 if (T) 2979 return QualType(T, 0); 2980 2981 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 2982 2983 ElaboratedTypeKeyword CanonKeyword = Keyword; 2984 if (Keyword == ETK_None) CanonKeyword = ETK_Typename; 2985 2986 bool AnyNonCanonArgs = false; 2987 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs); 2988 for (unsigned I = 0; I != NumArgs; ++I) { 2989 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]); 2990 if (!CanonArgs[I].structurallyEquals(Args[I])) 2991 AnyNonCanonArgs = true; 2992 } 2993 2994 QualType Canon; 2995 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) { 2996 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS, 2997 Name, NumArgs, 2998 CanonArgs.data()); 2999 3000 // Find the insert position again. 3001 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 3002 } 3003 3004 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) + 3005 sizeof(TemplateArgument) * NumArgs), 3006 TypeAlignment); 3007 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS, 3008 Name, NumArgs, Args, Canon); 3009 Types.push_back(T); 3010 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos); 3011 return QualType(T, 0); 3012 } 3013 3014 QualType ASTContext::getPackExpansionType(QualType Pattern, 3015 llvm::Optional<unsigned> NumExpansions) { 3016 llvm::FoldingSetNodeID ID; 3017 PackExpansionType::Profile(ID, Pattern, NumExpansions); 3018 3019 assert(Pattern->containsUnexpandedParameterPack() && 3020 "Pack expansions must expand one or more parameter packs"); 3021 void *InsertPos = 0; 3022 PackExpansionType *T 3023 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 3024 if (T) 3025 return QualType(T, 0); 3026 3027 QualType Canon; 3028 if (!Pattern.isCanonical()) { 3029 Canon = getCanonicalType(Pattern); 3030 // The canonical type might not contain an unexpanded parameter pack, if it 3031 // contains an alias template specialization which ignores one of its 3032 // parameters. 3033 if (Canon->containsUnexpandedParameterPack()) { 3034 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions); 3035 3036 // Find the insert position again, in case we inserted an element into 3037 // PackExpansionTypes and invalidated our insert position. 3038 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 3039 } 3040 } 3041 3042 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions); 3043 Types.push_back(T); 3044 PackExpansionTypes.InsertNode(T, InsertPos); 3045 return QualType(T, 0); 3046 } 3047 3048 /// CmpProtocolNames - Comparison predicate for sorting protocols 3049 /// alphabetically. 3050 static bool CmpProtocolNames(const ObjCProtocolDecl *LHS, 3051 const ObjCProtocolDecl *RHS) { 3052 return LHS->getDeclName() < RHS->getDeclName(); 3053 } 3054 3055 static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols, 3056 unsigned NumProtocols) { 3057 if (NumProtocols == 0) return true; 3058 3059 if (Protocols[0]->getCanonicalDecl() != Protocols[0]) 3060 return false; 3061 3062 for (unsigned i = 1; i != NumProtocols; ++i) 3063 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) || 3064 Protocols[i]->getCanonicalDecl() != Protocols[i]) 3065 return false; 3066 return true; 3067 } 3068 3069 static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols, 3070 unsigned &NumProtocols) { 3071 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols; 3072 3073 // Sort protocols, keyed by name. 3074 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames); 3075 3076 // Canonicalize. 3077 for (unsigned I = 0, N = NumProtocols; I != N; ++I) 3078 Protocols[I] = Protocols[I]->getCanonicalDecl(); 3079 3080 // Remove duplicates. 3081 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd); 3082 NumProtocols = ProtocolsEnd-Protocols; 3083 } 3084 3085 QualType ASTContext::getObjCObjectType(QualType BaseType, 3086 ObjCProtocolDecl * const *Protocols, 3087 unsigned NumProtocols) const { 3088 // If the base type is an interface and there aren't any protocols 3089 // to add, then the interface type will do just fine. 3090 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType)) 3091 return BaseType; 3092 3093 // Look in the folding set for an existing type. 3094 llvm::FoldingSetNodeID ID; 3095 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols); 3096 void *InsertPos = 0; 3097 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos)) 3098 return QualType(QT, 0); 3099 3100 // Build the canonical type, which has the canonical base type and 3101 // a sorted-and-uniqued list of protocols. 3102 QualType Canonical; 3103 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols); 3104 if (!ProtocolsSorted || !BaseType.isCanonical()) { 3105 if (!ProtocolsSorted) { 3106 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols, 3107 Protocols + NumProtocols); 3108 unsigned UniqueCount = NumProtocols; 3109 3110 SortAndUniqueProtocols(&Sorted[0], UniqueCount); 3111 Canonical = getObjCObjectType(getCanonicalType(BaseType), 3112 &Sorted[0], UniqueCount); 3113 } else { 3114 Canonical = getObjCObjectType(getCanonicalType(BaseType), 3115 Protocols, NumProtocols); 3116 } 3117 3118 // Regenerate InsertPos. 3119 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos); 3120 } 3121 3122 unsigned Size = sizeof(ObjCObjectTypeImpl); 3123 Size += NumProtocols * sizeof(ObjCProtocolDecl *); 3124 void *Mem = Allocate(Size, TypeAlignment); 3125 ObjCObjectTypeImpl *T = 3126 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols); 3127 3128 Types.push_back(T); 3129 ObjCObjectTypes.InsertNode(T, InsertPos); 3130 return QualType(T, 0); 3131 } 3132 3133 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for 3134 /// the given object type. 3135 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const { 3136 llvm::FoldingSetNodeID ID; 3137 ObjCObjectPointerType::Profile(ID, ObjectT); 3138 3139 void *InsertPos = 0; 3140 if (ObjCObjectPointerType *QT = 3141 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3142 return QualType(QT, 0); 3143 3144 // Find the canonical object type. 3145 QualType Canonical; 3146 if (!ObjectT.isCanonical()) { 3147 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT)); 3148 3149 // Regenerate InsertPos. 3150 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3151 } 3152 3153 // No match. 3154 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment); 3155 ObjCObjectPointerType *QType = 3156 new (Mem) ObjCObjectPointerType(Canonical, ObjectT); 3157 3158 Types.push_back(QType); 3159 ObjCObjectPointerTypes.InsertNode(QType, InsertPos); 3160 return QualType(QType, 0); 3161 } 3162 3163 /// getObjCInterfaceType - Return the unique reference to the type for the 3164 /// specified ObjC interface decl. The list of protocols is optional. 3165 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl, 3166 ObjCInterfaceDecl *PrevDecl) const { 3167 if (Decl->TypeForDecl) 3168 return QualType(Decl->TypeForDecl, 0); 3169 3170 if (PrevDecl) { 3171 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl"); 3172 Decl->TypeForDecl = PrevDecl->TypeForDecl; 3173 return QualType(PrevDecl->TypeForDecl, 0); 3174 } 3175 3176 // Prefer the definition, if there is one. 3177 if (const ObjCInterfaceDecl *Def = Decl->getDefinition()) 3178 Decl = Def; 3179 3180 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment); 3181 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl); 3182 Decl->TypeForDecl = T; 3183 Types.push_back(T); 3184 return QualType(T, 0); 3185 } 3186 3187 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique 3188 /// TypeOfExprType AST's (since expression's are never shared). For example, 3189 /// multiple declarations that refer to "typeof(x)" all contain different 3190 /// DeclRefExpr's. This doesn't effect the type checker, since it operates 3191 /// on canonical type's (which are always unique). 3192 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const { 3193 TypeOfExprType *toe; 3194 if (tofExpr->isTypeDependent()) { 3195 llvm::FoldingSetNodeID ID; 3196 DependentTypeOfExprType::Profile(ID, *this, tofExpr); 3197 3198 void *InsertPos = 0; 3199 DependentTypeOfExprType *Canon 3200 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos); 3201 if (Canon) { 3202 // We already have a "canonical" version of an identical, dependent 3203 // typeof(expr) type. Use that as our canonical type. 3204 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, 3205 QualType((TypeOfExprType*)Canon, 0)); 3206 } else { 3207 // Build a new, canonical typeof(expr) type. 3208 Canon 3209 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr); 3210 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos); 3211 toe = Canon; 3212 } 3213 } else { 3214 QualType Canonical = getCanonicalType(tofExpr->getType()); 3215 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical); 3216 } 3217 Types.push_back(toe); 3218 return QualType(toe, 0); 3219 } 3220 3221 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique 3222 /// TypeOfType AST's. The only motivation to unique these nodes would be 3223 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be 3224 /// an issue. This doesn't effect the type checker, since it operates 3225 /// on canonical type's (which are always unique). 3226 QualType ASTContext::getTypeOfType(QualType tofType) const { 3227 QualType Canonical = getCanonicalType(tofType); 3228 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical); 3229 Types.push_back(tot); 3230 return QualType(tot, 0); 3231 } 3232 3233 3234 /// getDecltypeType - Unlike many "get<Type>" functions, we don't unique 3235 /// DecltypeType AST's. The only motivation to unique these nodes would be 3236 /// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be 3237 /// an issue. This doesn't effect the type checker, since it operates 3238 /// on canonical types (which are always unique). 3239 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const { 3240 DecltypeType *dt; 3241 3242 // C++0x [temp.type]p2: 3243 // If an expression e involves a template parameter, decltype(e) denotes a 3244 // unique dependent type. Two such decltype-specifiers refer to the same 3245 // type only if their expressions are equivalent (14.5.6.1). 3246 if (e->isInstantiationDependent()) { 3247 llvm::FoldingSetNodeID ID; 3248 DependentDecltypeType::Profile(ID, *this, e); 3249 3250 void *InsertPos = 0; 3251 DependentDecltypeType *Canon 3252 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos); 3253 if (Canon) { 3254 // We already have a "canonical" version of an equivalent, dependent 3255 // decltype type. Use that as our canonical type. 3256 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType, 3257 QualType((DecltypeType*)Canon, 0)); 3258 } else { 3259 // Build a new, canonical typeof(expr) type. 3260 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e); 3261 DependentDecltypeTypes.InsertNode(Canon, InsertPos); 3262 dt = Canon; 3263 } 3264 } else { 3265 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType, 3266 getCanonicalType(UnderlyingType)); 3267 } 3268 Types.push_back(dt); 3269 return QualType(dt, 0); 3270 } 3271 3272 /// getUnaryTransformationType - We don't unique these, since the memory 3273 /// savings are minimal and these are rare. 3274 QualType ASTContext::getUnaryTransformType(QualType BaseType, 3275 QualType UnderlyingType, 3276 UnaryTransformType::UTTKind Kind) 3277 const { 3278 UnaryTransformType *Ty = 3279 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType, 3280 Kind, 3281 UnderlyingType->isDependentType() ? 3282 QualType() : getCanonicalType(UnderlyingType)); 3283 Types.push_back(Ty); 3284 return QualType(Ty, 0); 3285 } 3286 3287 /// getAutoType - We only unique auto types after they've been deduced. 3288 QualType ASTContext::getAutoType(QualType DeducedType) const { 3289 void *InsertPos = 0; 3290 if (!DeducedType.isNull()) { 3291 // Look in the folding set for an existing type. 3292 llvm::FoldingSetNodeID ID; 3293 AutoType::Profile(ID, DeducedType); 3294 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos)) 3295 return QualType(AT, 0); 3296 } 3297 3298 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType); 3299 Types.push_back(AT); 3300 if (InsertPos) 3301 AutoTypes.InsertNode(AT, InsertPos); 3302 return QualType(AT, 0); 3303 } 3304 3305 /// getAtomicType - Return the uniqued reference to the atomic type for 3306 /// the given value type. 3307 QualType ASTContext::getAtomicType(QualType T) const { 3308 // Unique pointers, to guarantee there is only one pointer of a particular 3309 // structure. 3310 llvm::FoldingSetNodeID ID; 3311 AtomicType::Profile(ID, T); 3312 3313 void *InsertPos = 0; 3314 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos)) 3315 return QualType(AT, 0); 3316 3317 // If the atomic value type isn't canonical, this won't be a canonical type 3318 // either, so fill in the canonical type field. 3319 QualType Canonical; 3320 if (!T.isCanonical()) { 3321 Canonical = getAtomicType(getCanonicalType(T)); 3322 3323 // Get the new insert position for the node we care about. 3324 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos); 3325 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 3326 } 3327 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical); 3328 Types.push_back(New); 3329 AtomicTypes.InsertNode(New, InsertPos); 3330 return QualType(New, 0); 3331 } 3332 3333 /// getAutoDeductType - Get type pattern for deducing against 'auto'. 3334 QualType ASTContext::getAutoDeductType() const { 3335 if (AutoDeductTy.isNull()) 3336 AutoDeductTy = getAutoType(QualType()); 3337 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern"); 3338 return AutoDeductTy; 3339 } 3340 3341 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'. 3342 QualType ASTContext::getAutoRRefDeductType() const { 3343 if (AutoRRefDeductTy.isNull()) 3344 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType()); 3345 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern"); 3346 return AutoRRefDeductTy; 3347 } 3348 3349 /// getTagDeclType - Return the unique reference to the type for the 3350 /// specified TagDecl (struct/union/class/enum) decl. 3351 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const { 3352 assert (Decl); 3353 // FIXME: What is the design on getTagDeclType when it requires casting 3354 // away const? mutable? 3355 return getTypeDeclType(const_cast<TagDecl*>(Decl)); 3356 } 3357 3358 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result 3359 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and 3360 /// needs to agree with the definition in <stddef.h>. 3361 CanQualType ASTContext::getSizeType() const { 3362 return getFromTargetType(Target->getSizeType()); 3363 } 3364 3365 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5). 3366 CanQualType ASTContext::getIntMaxType() const { 3367 return getFromTargetType(Target->getIntMaxType()); 3368 } 3369 3370 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5). 3371 CanQualType ASTContext::getUIntMaxType() const { 3372 return getFromTargetType(Target->getUIntMaxType()); 3373 } 3374 3375 /// getSignedWCharType - Return the type of "signed wchar_t". 3376 /// Used when in C++, as a GCC extension. 3377 QualType ASTContext::getSignedWCharType() const { 3378 // FIXME: derive from "Target" ? 3379 return WCharTy; 3380 } 3381 3382 /// getUnsignedWCharType - Return the type of "unsigned wchar_t". 3383 /// Used when in C++, as a GCC extension. 3384 QualType ASTContext::getUnsignedWCharType() const { 3385 // FIXME: derive from "Target" ? 3386 return UnsignedIntTy; 3387 } 3388 3389 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17) 3390 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9). 3391 QualType ASTContext::getPointerDiffType() const { 3392 return getFromTargetType(Target->getPtrDiffType(0)); 3393 } 3394 3395 //===----------------------------------------------------------------------===// 3396 // Type Operators 3397 //===----------------------------------------------------------------------===// 3398 3399 CanQualType ASTContext::getCanonicalParamType(QualType T) const { 3400 // Push qualifiers into arrays, and then discard any remaining 3401 // qualifiers. 3402 T = getCanonicalType(T); 3403 T = getVariableArrayDecayedType(T); 3404 const Type *Ty = T.getTypePtr(); 3405 QualType Result; 3406 if (isa<ArrayType>(Ty)) { 3407 Result = getArrayDecayedType(QualType(Ty,0)); 3408 } else if (isa<FunctionType>(Ty)) { 3409 Result = getPointerType(QualType(Ty, 0)); 3410 } else { 3411 Result = QualType(Ty, 0); 3412 } 3413 3414 return CanQualType::CreateUnsafe(Result); 3415 } 3416 3417 QualType ASTContext::getUnqualifiedArrayType(QualType type, 3418 Qualifiers &quals) { 3419 SplitQualType splitType = type.getSplitUnqualifiedType(); 3420 3421 // FIXME: getSplitUnqualifiedType() actually walks all the way to 3422 // the unqualified desugared type and then drops it on the floor. 3423 // We then have to strip that sugar back off with 3424 // getUnqualifiedDesugaredType(), which is silly. 3425 const ArrayType *AT = 3426 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType()); 3427 3428 // If we don't have an array, just use the results in splitType. 3429 if (!AT) { 3430 quals = splitType.Quals; 3431 return QualType(splitType.Ty, 0); 3432 } 3433 3434 // Otherwise, recurse on the array's element type. 3435 QualType elementType = AT->getElementType(); 3436 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals); 3437 3438 // If that didn't change the element type, AT has no qualifiers, so we 3439 // can just use the results in splitType. 3440 if (elementType == unqualElementType) { 3441 assert(quals.empty()); // from the recursive call 3442 quals = splitType.Quals; 3443 return QualType(splitType.Ty, 0); 3444 } 3445 3446 // Otherwise, add in the qualifiers from the outermost type, then 3447 // build the type back up. 3448 quals.addConsistentQualifiers(splitType.Quals); 3449 3450 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) { 3451 return getConstantArrayType(unqualElementType, CAT->getSize(), 3452 CAT->getSizeModifier(), 0); 3453 } 3454 3455 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) { 3456 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0); 3457 } 3458 3459 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) { 3460 return getVariableArrayType(unqualElementType, 3461 VAT->getSizeExpr(), 3462 VAT->getSizeModifier(), 3463 VAT->getIndexTypeCVRQualifiers(), 3464 VAT->getBracketsRange()); 3465 } 3466 3467 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT); 3468 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(), 3469 DSAT->getSizeModifier(), 0, 3470 SourceRange()); 3471 } 3472 3473 /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that 3474 /// may be similar (C++ 4.4), replaces T1 and T2 with the type that 3475 /// they point to and return true. If T1 and T2 aren't pointer types 3476 /// or pointer-to-member types, or if they are not similar at this 3477 /// level, returns false and leaves T1 and T2 unchanged. Top-level 3478 /// qualifiers on T1 and T2 are ignored. This function will typically 3479 /// be called in a loop that successively "unwraps" pointer and 3480 /// pointer-to-member types to compare them at each level. 3481 bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) { 3482 const PointerType *T1PtrType = T1->getAs<PointerType>(), 3483 *T2PtrType = T2->getAs<PointerType>(); 3484 if (T1PtrType && T2PtrType) { 3485 T1 = T1PtrType->getPointeeType(); 3486 T2 = T2PtrType->getPointeeType(); 3487 return true; 3488 } 3489 3490 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(), 3491 *T2MPType = T2->getAs<MemberPointerType>(); 3492 if (T1MPType && T2MPType && 3493 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0), 3494 QualType(T2MPType->getClass(), 0))) { 3495 T1 = T1MPType->getPointeeType(); 3496 T2 = T2MPType->getPointeeType(); 3497 return true; 3498 } 3499 3500 if (getLangOpts().ObjC1) { 3501 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(), 3502 *T2OPType = T2->getAs<ObjCObjectPointerType>(); 3503 if (T1OPType && T2OPType) { 3504 T1 = T1OPType->getPointeeType(); 3505 T2 = T2OPType->getPointeeType(); 3506 return true; 3507 } 3508 } 3509 3510 // FIXME: Block pointers, too? 3511 3512 return false; 3513 } 3514 3515 DeclarationNameInfo 3516 ASTContext::getNameForTemplate(TemplateName Name, 3517 SourceLocation NameLoc) const { 3518 switch (Name.getKind()) { 3519 case TemplateName::QualifiedTemplate: 3520 case TemplateName::Template: 3521 // DNInfo work in progress: CHECKME: what about DNLoc? 3522 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(), 3523 NameLoc); 3524 3525 case TemplateName::OverloadedTemplate: { 3526 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate(); 3527 // DNInfo work in progress: CHECKME: what about DNLoc? 3528 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc); 3529 } 3530 3531 case TemplateName::DependentTemplate: { 3532 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 3533 DeclarationName DName; 3534 if (DTN->isIdentifier()) { 3535 DName = DeclarationNames.getIdentifier(DTN->getIdentifier()); 3536 return DeclarationNameInfo(DName, NameLoc); 3537 } else { 3538 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator()); 3539 // DNInfo work in progress: FIXME: source locations? 3540 DeclarationNameLoc DNLoc; 3541 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding(); 3542 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding(); 3543 return DeclarationNameInfo(DName, NameLoc, DNLoc); 3544 } 3545 } 3546 3547 case TemplateName::SubstTemplateTemplateParm: { 3548 SubstTemplateTemplateParmStorage *subst 3549 = Name.getAsSubstTemplateTemplateParm(); 3550 return DeclarationNameInfo(subst->getParameter()->getDeclName(), 3551 NameLoc); 3552 } 3553 3554 case TemplateName::SubstTemplateTemplateParmPack: { 3555 SubstTemplateTemplateParmPackStorage *subst 3556 = Name.getAsSubstTemplateTemplateParmPack(); 3557 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(), 3558 NameLoc); 3559 } 3560 } 3561 3562 llvm_unreachable("bad template name kind!"); 3563 } 3564 3565 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const { 3566 switch (Name.getKind()) { 3567 case TemplateName::QualifiedTemplate: 3568 case TemplateName::Template: { 3569 TemplateDecl *Template = Name.getAsTemplateDecl(); 3570 if (TemplateTemplateParmDecl *TTP 3571 = dyn_cast<TemplateTemplateParmDecl>(Template)) 3572 Template = getCanonicalTemplateTemplateParmDecl(TTP); 3573 3574 // The canonical template name is the canonical template declaration. 3575 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl())); 3576 } 3577 3578 case TemplateName::OverloadedTemplate: 3579 llvm_unreachable("cannot canonicalize overloaded template"); 3580 3581 case TemplateName::DependentTemplate: { 3582 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 3583 assert(DTN && "Non-dependent template names must refer to template decls."); 3584 return DTN->CanonicalTemplateName; 3585 } 3586 3587 case TemplateName::SubstTemplateTemplateParm: { 3588 SubstTemplateTemplateParmStorage *subst 3589 = Name.getAsSubstTemplateTemplateParm(); 3590 return getCanonicalTemplateName(subst->getReplacement()); 3591 } 3592 3593 case TemplateName::SubstTemplateTemplateParmPack: { 3594 SubstTemplateTemplateParmPackStorage *subst 3595 = Name.getAsSubstTemplateTemplateParmPack(); 3596 TemplateTemplateParmDecl *canonParameter 3597 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack()); 3598 TemplateArgument canonArgPack 3599 = getCanonicalTemplateArgument(subst->getArgumentPack()); 3600 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack); 3601 } 3602 } 3603 3604 llvm_unreachable("bad template name!"); 3605 } 3606 3607 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) { 3608 X = getCanonicalTemplateName(X); 3609 Y = getCanonicalTemplateName(Y); 3610 return X.getAsVoidPointer() == Y.getAsVoidPointer(); 3611 } 3612 3613 TemplateArgument 3614 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const { 3615 switch (Arg.getKind()) { 3616 case TemplateArgument::Null: 3617 return Arg; 3618 3619 case TemplateArgument::Expression: 3620 return Arg; 3621 3622 case TemplateArgument::Declaration: { 3623 if (Decl *D = Arg.getAsDecl()) 3624 return TemplateArgument(D->getCanonicalDecl()); 3625 return TemplateArgument((Decl*)0); 3626 } 3627 3628 case TemplateArgument::Template: 3629 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate())); 3630 3631 case TemplateArgument::TemplateExpansion: 3632 return TemplateArgument(getCanonicalTemplateName( 3633 Arg.getAsTemplateOrTemplatePattern()), 3634 Arg.getNumTemplateExpansions()); 3635 3636 case TemplateArgument::Integral: 3637 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType())); 3638 3639 case TemplateArgument::Type: 3640 return TemplateArgument(getCanonicalType(Arg.getAsType())); 3641 3642 case TemplateArgument::Pack: { 3643 if (Arg.pack_size() == 0) 3644 return Arg; 3645 3646 TemplateArgument *CanonArgs 3647 = new (*this) TemplateArgument[Arg.pack_size()]; 3648 unsigned Idx = 0; 3649 for (TemplateArgument::pack_iterator A = Arg.pack_begin(), 3650 AEnd = Arg.pack_end(); 3651 A != AEnd; (void)++A, ++Idx) 3652 CanonArgs[Idx] = getCanonicalTemplateArgument(*A); 3653 3654 return TemplateArgument(CanonArgs, Arg.pack_size()); 3655 } 3656 } 3657 3658 // Silence GCC warning 3659 llvm_unreachable("Unhandled template argument kind"); 3660 } 3661 3662 NestedNameSpecifier * 3663 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const { 3664 if (!NNS) 3665 return 0; 3666 3667 switch (NNS->getKind()) { 3668 case NestedNameSpecifier::Identifier: 3669 // Canonicalize the prefix but keep the identifier the same. 3670 return NestedNameSpecifier::Create(*this, 3671 getCanonicalNestedNameSpecifier(NNS->getPrefix()), 3672 NNS->getAsIdentifier()); 3673 3674 case NestedNameSpecifier::Namespace: 3675 // A namespace is canonical; build a nested-name-specifier with 3676 // this namespace and no prefix. 3677 return NestedNameSpecifier::Create(*this, 0, 3678 NNS->getAsNamespace()->getOriginalNamespace()); 3679 3680 case NestedNameSpecifier::NamespaceAlias: 3681 // A namespace is canonical; build a nested-name-specifier with 3682 // this namespace and no prefix. 3683 return NestedNameSpecifier::Create(*this, 0, 3684 NNS->getAsNamespaceAlias()->getNamespace() 3685 ->getOriginalNamespace()); 3686 3687 case NestedNameSpecifier::TypeSpec: 3688 case NestedNameSpecifier::TypeSpecWithTemplate: { 3689 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0)); 3690 3691 // If we have some kind of dependent-named type (e.g., "typename T::type"), 3692 // break it apart into its prefix and identifier, then reconsititute those 3693 // as the canonical nested-name-specifier. This is required to canonicalize 3694 // a dependent nested-name-specifier involving typedefs of dependent-name 3695 // types, e.g., 3696 // typedef typename T::type T1; 3697 // typedef typename T1::type T2; 3698 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) 3699 return NestedNameSpecifier::Create(*this, DNT->getQualifier(), 3700 const_cast<IdentifierInfo *>(DNT->getIdentifier())); 3701 3702 // Otherwise, just canonicalize the type, and force it to be a TypeSpec. 3703 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the 3704 // first place? 3705 return NestedNameSpecifier::Create(*this, 0, false, 3706 const_cast<Type*>(T.getTypePtr())); 3707 } 3708 3709 case NestedNameSpecifier::Global: 3710 // The global specifier is canonical and unique. 3711 return NNS; 3712 } 3713 3714 llvm_unreachable("Invalid NestedNameSpecifier::Kind!"); 3715 } 3716 3717 3718 const ArrayType *ASTContext::getAsArrayType(QualType T) const { 3719 // Handle the non-qualified case efficiently. 3720 if (!T.hasLocalQualifiers()) { 3721 // Handle the common positive case fast. 3722 if (const ArrayType *AT = dyn_cast<ArrayType>(T)) 3723 return AT; 3724 } 3725 3726 // Handle the common negative case fast. 3727 if (!isa<ArrayType>(T.getCanonicalType())) 3728 return 0; 3729 3730 // Apply any qualifiers from the array type to the element type. This 3731 // implements C99 6.7.3p8: "If the specification of an array type includes 3732 // any type qualifiers, the element type is so qualified, not the array type." 3733 3734 // If we get here, we either have type qualifiers on the type, or we have 3735 // sugar such as a typedef in the way. If we have type qualifiers on the type 3736 // we must propagate them down into the element type. 3737 3738 SplitQualType split = T.getSplitDesugaredType(); 3739 Qualifiers qs = split.Quals; 3740 3741 // If we have a simple case, just return now. 3742 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty); 3743 if (ATy == 0 || qs.empty()) 3744 return ATy; 3745 3746 // Otherwise, we have an array and we have qualifiers on it. Push the 3747 // qualifiers into the array element type and return a new array type. 3748 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs); 3749 3750 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy)) 3751 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(), 3752 CAT->getSizeModifier(), 3753 CAT->getIndexTypeCVRQualifiers())); 3754 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy)) 3755 return cast<ArrayType>(getIncompleteArrayType(NewEltTy, 3756 IAT->getSizeModifier(), 3757 IAT->getIndexTypeCVRQualifiers())); 3758 3759 if (const DependentSizedArrayType *DSAT 3760 = dyn_cast<DependentSizedArrayType>(ATy)) 3761 return cast<ArrayType>( 3762 getDependentSizedArrayType(NewEltTy, 3763 DSAT->getSizeExpr(), 3764 DSAT->getSizeModifier(), 3765 DSAT->getIndexTypeCVRQualifiers(), 3766 DSAT->getBracketsRange())); 3767 3768 const VariableArrayType *VAT = cast<VariableArrayType>(ATy); 3769 return cast<ArrayType>(getVariableArrayType(NewEltTy, 3770 VAT->getSizeExpr(), 3771 VAT->getSizeModifier(), 3772 VAT->getIndexTypeCVRQualifiers(), 3773 VAT->getBracketsRange())); 3774 } 3775 3776 QualType ASTContext::getAdjustedParameterType(QualType T) const { 3777 // C99 6.7.5.3p7: 3778 // A declaration of a parameter as "array of type" shall be 3779 // adjusted to "qualified pointer to type", where the type 3780 // qualifiers (if any) are those specified within the [ and ] of 3781 // the array type derivation. 3782 if (T->isArrayType()) 3783 return getArrayDecayedType(T); 3784 3785 // C99 6.7.5.3p8: 3786 // A declaration of a parameter as "function returning type" 3787 // shall be adjusted to "pointer to function returning type", as 3788 // in 6.3.2.1. 3789 if (T->isFunctionType()) 3790 return getPointerType(T); 3791 3792 return T; 3793 } 3794 3795 QualType ASTContext::getSignatureParameterType(QualType T) const { 3796 T = getVariableArrayDecayedType(T); 3797 T = getAdjustedParameterType(T); 3798 return T.getUnqualifiedType(); 3799 } 3800 3801 /// getArrayDecayedType - Return the properly qualified result of decaying the 3802 /// specified array type to a pointer. This operation is non-trivial when 3803 /// handling typedefs etc. The canonical type of "T" must be an array type, 3804 /// this returns a pointer to a properly qualified element of the array. 3805 /// 3806 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3. 3807 QualType ASTContext::getArrayDecayedType(QualType Ty) const { 3808 // Get the element type with 'getAsArrayType' so that we don't lose any 3809 // typedefs in the element type of the array. This also handles propagation 3810 // of type qualifiers from the array type into the element type if present 3811 // (C99 6.7.3p8). 3812 const ArrayType *PrettyArrayType = getAsArrayType(Ty); 3813 assert(PrettyArrayType && "Not an array type!"); 3814 3815 QualType PtrTy = getPointerType(PrettyArrayType->getElementType()); 3816 3817 // int x[restrict 4] -> int *restrict 3818 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers()); 3819 } 3820 3821 QualType ASTContext::getBaseElementType(const ArrayType *array) const { 3822 return getBaseElementType(array->getElementType()); 3823 } 3824 3825 QualType ASTContext::getBaseElementType(QualType type) const { 3826 Qualifiers qs; 3827 while (true) { 3828 SplitQualType split = type.getSplitDesugaredType(); 3829 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe(); 3830 if (!array) break; 3831 3832 type = array->getElementType(); 3833 qs.addConsistentQualifiers(split.Quals); 3834 } 3835 3836 return getQualifiedType(type, qs); 3837 } 3838 3839 /// getConstantArrayElementCount - Returns number of constant array elements. 3840 uint64_t 3841 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const { 3842 uint64_t ElementCount = 1; 3843 do { 3844 ElementCount *= CA->getSize().getZExtValue(); 3845 CA = dyn_cast<ConstantArrayType>(CA->getElementType()); 3846 } while (CA); 3847 return ElementCount; 3848 } 3849 3850 /// getFloatingRank - Return a relative rank for floating point types. 3851 /// This routine will assert if passed a built-in type that isn't a float. 3852 static FloatingRank getFloatingRank(QualType T) { 3853 if (const ComplexType *CT = T->getAs<ComplexType>()) 3854 return getFloatingRank(CT->getElementType()); 3855 3856 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type"); 3857 switch (T->getAs<BuiltinType>()->getKind()) { 3858 default: llvm_unreachable("getFloatingRank(): not a floating type"); 3859 case BuiltinType::Half: return HalfRank; 3860 case BuiltinType::Float: return FloatRank; 3861 case BuiltinType::Double: return DoubleRank; 3862 case BuiltinType::LongDouble: return LongDoubleRank; 3863 } 3864 } 3865 3866 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating 3867 /// point or a complex type (based on typeDomain/typeSize). 3868 /// 'typeDomain' is a real floating point or complex type. 3869 /// 'typeSize' is a real floating point or complex type. 3870 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size, 3871 QualType Domain) const { 3872 FloatingRank EltRank = getFloatingRank(Size); 3873 if (Domain->isComplexType()) { 3874 switch (EltRank) { 3875 case HalfRank: llvm_unreachable("Complex half is not supported"); 3876 case FloatRank: return FloatComplexTy; 3877 case DoubleRank: return DoubleComplexTy; 3878 case LongDoubleRank: return LongDoubleComplexTy; 3879 } 3880 } 3881 3882 assert(Domain->isRealFloatingType() && "Unknown domain!"); 3883 switch (EltRank) { 3884 case HalfRank: llvm_unreachable("Half ranks are not valid here"); 3885 case FloatRank: return FloatTy; 3886 case DoubleRank: return DoubleTy; 3887 case LongDoubleRank: return LongDoubleTy; 3888 } 3889 llvm_unreachable("getFloatingRank(): illegal value for rank"); 3890 } 3891 3892 /// getFloatingTypeOrder - Compare the rank of the two specified floating 3893 /// point types, ignoring the domain of the type (i.e. 'double' == 3894 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If 3895 /// LHS < RHS, return -1. 3896 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const { 3897 FloatingRank LHSR = getFloatingRank(LHS); 3898 FloatingRank RHSR = getFloatingRank(RHS); 3899 3900 if (LHSR == RHSR) 3901 return 0; 3902 if (LHSR > RHSR) 3903 return 1; 3904 return -1; 3905 } 3906 3907 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This 3908 /// routine will assert if passed a built-in type that isn't an integer or enum, 3909 /// or if it is not canonicalized. 3910 unsigned ASTContext::getIntegerRank(const Type *T) const { 3911 assert(T->isCanonicalUnqualified() && "T should be canonicalized"); 3912 3913 switch (cast<BuiltinType>(T)->getKind()) { 3914 default: llvm_unreachable("getIntegerRank(): not a built-in integer"); 3915 case BuiltinType::Bool: 3916 return 1 + (getIntWidth(BoolTy) << 3); 3917 case BuiltinType::Char_S: 3918 case BuiltinType::Char_U: 3919 case BuiltinType::SChar: 3920 case BuiltinType::UChar: 3921 return 2 + (getIntWidth(CharTy) << 3); 3922 case BuiltinType::Short: 3923 case BuiltinType::UShort: 3924 return 3 + (getIntWidth(ShortTy) << 3); 3925 case BuiltinType::Int: 3926 case BuiltinType::UInt: 3927 return 4 + (getIntWidth(IntTy) << 3); 3928 case BuiltinType::Long: 3929 case BuiltinType::ULong: 3930 return 5 + (getIntWidth(LongTy) << 3); 3931 case BuiltinType::LongLong: 3932 case BuiltinType::ULongLong: 3933 return 6 + (getIntWidth(LongLongTy) << 3); 3934 case BuiltinType::Int128: 3935 case BuiltinType::UInt128: 3936 return 7 + (getIntWidth(Int128Ty) << 3); 3937 } 3938 } 3939 3940 /// \brief Whether this is a promotable bitfield reference according 3941 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions). 3942 /// 3943 /// \returns the type this bit-field will promote to, or NULL if no 3944 /// promotion occurs. 3945 QualType ASTContext::isPromotableBitField(Expr *E) const { 3946 if (E->isTypeDependent() || E->isValueDependent()) 3947 return QualType(); 3948 3949 FieldDecl *Field = E->getBitField(); 3950 if (!Field) 3951 return QualType(); 3952 3953 QualType FT = Field->getType(); 3954 3955 uint64_t BitWidth = Field->getBitWidthValue(*this); 3956 uint64_t IntSize = getTypeSize(IntTy); 3957 // GCC extension compatibility: if the bit-field size is less than or equal 3958 // to the size of int, it gets promoted no matter what its type is. 3959 // For instance, unsigned long bf : 4 gets promoted to signed int. 3960 if (BitWidth < IntSize) 3961 return IntTy; 3962 3963 if (BitWidth == IntSize) 3964 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy; 3965 3966 // Types bigger than int are not subject to promotions, and therefore act 3967 // like the base type. 3968 // FIXME: This doesn't quite match what gcc does, but what gcc does here 3969 // is ridiculous. 3970 return QualType(); 3971 } 3972 3973 /// getPromotedIntegerType - Returns the type that Promotable will 3974 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable 3975 /// integer type. 3976 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const { 3977 assert(!Promotable.isNull()); 3978 assert(Promotable->isPromotableIntegerType()); 3979 if (const EnumType *ET = Promotable->getAs<EnumType>()) 3980 return ET->getDecl()->getPromotionType(); 3981 3982 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) { 3983 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t 3984 // (3.9.1) can be converted to a prvalue of the first of the following 3985 // types that can represent all the values of its underlying type: 3986 // int, unsigned int, long int, unsigned long int, long long int, or 3987 // unsigned long long int [...] 3988 // FIXME: Is there some better way to compute this? 3989 if (BT->getKind() == BuiltinType::WChar_S || 3990 BT->getKind() == BuiltinType::WChar_U || 3991 BT->getKind() == BuiltinType::Char16 || 3992 BT->getKind() == BuiltinType::Char32) { 3993 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S; 3994 uint64_t FromSize = getTypeSize(BT); 3995 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy, 3996 LongLongTy, UnsignedLongLongTy }; 3997 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) { 3998 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]); 3999 if (FromSize < ToSize || 4000 (FromSize == ToSize && 4001 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) 4002 return PromoteTypes[Idx]; 4003 } 4004 llvm_unreachable("char type should fit into long long"); 4005 } 4006 } 4007 4008 // At this point, we should have a signed or unsigned integer type. 4009 if (Promotable->isSignedIntegerType()) 4010 return IntTy; 4011 uint64_t PromotableSize = getTypeSize(Promotable); 4012 uint64_t IntSize = getTypeSize(IntTy); 4013 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize); 4014 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy; 4015 } 4016 4017 /// \brief Recurses in pointer/array types until it finds an objc retainable 4018 /// type and returns its ownership. 4019 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const { 4020 while (!T.isNull()) { 4021 if (T.getObjCLifetime() != Qualifiers::OCL_None) 4022 return T.getObjCLifetime(); 4023 if (T->isArrayType()) 4024 T = getBaseElementType(T); 4025 else if (const PointerType *PT = T->getAs<PointerType>()) 4026 T = PT->getPointeeType(); 4027 else if (const ReferenceType *RT = T->getAs<ReferenceType>()) 4028 T = RT->getPointeeType(); 4029 else 4030 break; 4031 } 4032 4033 return Qualifiers::OCL_None; 4034 } 4035 4036 /// getIntegerTypeOrder - Returns the highest ranked integer type: 4037 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If 4038 /// LHS < RHS, return -1. 4039 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const { 4040 const Type *LHSC = getCanonicalType(LHS).getTypePtr(); 4041 const Type *RHSC = getCanonicalType(RHS).getTypePtr(); 4042 if (LHSC == RHSC) return 0; 4043 4044 bool LHSUnsigned = LHSC->isUnsignedIntegerType(); 4045 bool RHSUnsigned = RHSC->isUnsignedIntegerType(); 4046 4047 unsigned LHSRank = getIntegerRank(LHSC); 4048 unsigned RHSRank = getIntegerRank(RHSC); 4049 4050 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned. 4051 if (LHSRank == RHSRank) return 0; 4052 return LHSRank > RHSRank ? 1 : -1; 4053 } 4054 4055 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa. 4056 if (LHSUnsigned) { 4057 // If the unsigned [LHS] type is larger, return it. 4058 if (LHSRank >= RHSRank) 4059 return 1; 4060 4061 // If the signed type can represent all values of the unsigned type, it 4062 // wins. Because we are dealing with 2's complement and types that are 4063 // powers of two larger than each other, this is always safe. 4064 return -1; 4065 } 4066 4067 // If the unsigned [RHS] type is larger, return it. 4068 if (RHSRank >= LHSRank) 4069 return -1; 4070 4071 // If the signed type can represent all values of the unsigned type, it 4072 // wins. Because we are dealing with 2's complement and types that are 4073 // powers of two larger than each other, this is always safe. 4074 return 1; 4075 } 4076 4077 static RecordDecl * 4078 CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK, 4079 DeclContext *DC, IdentifierInfo *Id) { 4080 SourceLocation Loc; 4081 if (Ctx.getLangOpts().CPlusPlus) 4082 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id); 4083 else 4084 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id); 4085 } 4086 4087 // getCFConstantStringType - Return the type used for constant CFStrings. 4088 QualType ASTContext::getCFConstantStringType() const { 4089 if (!CFConstantStringTypeDecl) { 4090 CFConstantStringTypeDecl = 4091 CreateRecordDecl(*this, TTK_Struct, TUDecl, 4092 &Idents.get("NSConstantString")); 4093 CFConstantStringTypeDecl->startDefinition(); 4094 4095 QualType FieldTypes[4]; 4096 4097 // const int *isa; 4098 FieldTypes[0] = getPointerType(IntTy.withConst()); 4099 // int flags; 4100 FieldTypes[1] = IntTy; 4101 // const char *str; 4102 FieldTypes[2] = getPointerType(CharTy.withConst()); 4103 // long length; 4104 FieldTypes[3] = LongTy; 4105 4106 // Create fields 4107 for (unsigned i = 0; i < 4; ++i) { 4108 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl, 4109 SourceLocation(), 4110 SourceLocation(), 0, 4111 FieldTypes[i], /*TInfo=*/0, 4112 /*BitWidth=*/0, 4113 /*Mutable=*/false, 4114 ICIS_NoInit); 4115 Field->setAccess(AS_public); 4116 CFConstantStringTypeDecl->addDecl(Field); 4117 } 4118 4119 CFConstantStringTypeDecl->completeDefinition(); 4120 } 4121 4122 return getTagDeclType(CFConstantStringTypeDecl); 4123 } 4124 4125 void ASTContext::setCFConstantStringType(QualType T) { 4126 const RecordType *Rec = T->getAs<RecordType>(); 4127 assert(Rec && "Invalid CFConstantStringType"); 4128 CFConstantStringTypeDecl = Rec->getDecl(); 4129 } 4130 4131 QualType ASTContext::getBlockDescriptorType() const { 4132 if (BlockDescriptorType) 4133 return getTagDeclType(BlockDescriptorType); 4134 4135 RecordDecl *T; 4136 // FIXME: Needs the FlagAppleBlock bit. 4137 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, 4138 &Idents.get("__block_descriptor")); 4139 T->startDefinition(); 4140 4141 QualType FieldTypes[] = { 4142 UnsignedLongTy, 4143 UnsignedLongTy, 4144 }; 4145 4146 const char *FieldNames[] = { 4147 "reserved", 4148 "Size" 4149 }; 4150 4151 for (size_t i = 0; i < 2; ++i) { 4152 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(), 4153 SourceLocation(), 4154 &Idents.get(FieldNames[i]), 4155 FieldTypes[i], /*TInfo=*/0, 4156 /*BitWidth=*/0, 4157 /*Mutable=*/false, 4158 ICIS_NoInit); 4159 Field->setAccess(AS_public); 4160 T->addDecl(Field); 4161 } 4162 4163 T->completeDefinition(); 4164 4165 BlockDescriptorType = T; 4166 4167 return getTagDeclType(BlockDescriptorType); 4168 } 4169 4170 QualType ASTContext::getBlockDescriptorExtendedType() const { 4171 if (BlockDescriptorExtendedType) 4172 return getTagDeclType(BlockDescriptorExtendedType); 4173 4174 RecordDecl *T; 4175 // FIXME: Needs the FlagAppleBlock bit. 4176 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, 4177 &Idents.get("__block_descriptor_withcopydispose")); 4178 T->startDefinition(); 4179 4180 QualType FieldTypes[] = { 4181 UnsignedLongTy, 4182 UnsignedLongTy, 4183 getPointerType(VoidPtrTy), 4184 getPointerType(VoidPtrTy) 4185 }; 4186 4187 const char *FieldNames[] = { 4188 "reserved", 4189 "Size", 4190 "CopyFuncPtr", 4191 "DestroyFuncPtr" 4192 }; 4193 4194 for (size_t i = 0; i < 4; ++i) { 4195 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(), 4196 SourceLocation(), 4197 &Idents.get(FieldNames[i]), 4198 FieldTypes[i], /*TInfo=*/0, 4199 /*BitWidth=*/0, 4200 /*Mutable=*/false, 4201 ICIS_NoInit); 4202 Field->setAccess(AS_public); 4203 T->addDecl(Field); 4204 } 4205 4206 T->completeDefinition(); 4207 4208 BlockDescriptorExtendedType = T; 4209 4210 return getTagDeclType(BlockDescriptorExtendedType); 4211 } 4212 4213 bool ASTContext::BlockRequiresCopying(QualType Ty) const { 4214 if (Ty->isObjCRetainableType()) 4215 return true; 4216 if (getLangOpts().CPlusPlus) { 4217 if (const RecordType *RT = Ty->getAs<RecordType>()) { 4218 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 4219 return RD->hasConstCopyConstructor(); 4220 4221 } 4222 } 4223 return false; 4224 } 4225 4226 QualType 4227 ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const { 4228 // type = struct __Block_byref_1_X { 4229 // void *__isa; 4230 // struct __Block_byref_1_X *__forwarding; 4231 // unsigned int __flags; 4232 // unsigned int __size; 4233 // void *__copy_helper; // as needed 4234 // void *__destroy_help // as needed 4235 // int X; 4236 // } * 4237 4238 bool HasCopyAndDispose = BlockRequiresCopying(Ty); 4239 4240 // FIXME: Move up 4241 SmallString<36> Name; 4242 llvm::raw_svector_ostream(Name) << "__Block_byref_" << 4243 ++UniqueBlockByRefTypeID << '_' << DeclName; 4244 RecordDecl *T; 4245 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str())); 4246 T->startDefinition(); 4247 QualType Int32Ty = IntTy; 4248 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported"); 4249 QualType FieldTypes[] = { 4250 getPointerType(VoidPtrTy), 4251 getPointerType(getTagDeclType(T)), 4252 Int32Ty, 4253 Int32Ty, 4254 getPointerType(VoidPtrTy), 4255 getPointerType(VoidPtrTy), 4256 Ty 4257 }; 4258 4259 StringRef FieldNames[] = { 4260 "__isa", 4261 "__forwarding", 4262 "__flags", 4263 "__size", 4264 "__copy_helper", 4265 "__destroy_helper", 4266 DeclName, 4267 }; 4268 4269 for (size_t i = 0; i < 7; ++i) { 4270 if (!HasCopyAndDispose && i >=4 && i <= 5) 4271 continue; 4272 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(), 4273 SourceLocation(), 4274 &Idents.get(FieldNames[i]), 4275 FieldTypes[i], /*TInfo=*/0, 4276 /*BitWidth=*/0, /*Mutable=*/false, 4277 ICIS_NoInit); 4278 Field->setAccess(AS_public); 4279 T->addDecl(Field); 4280 } 4281 4282 T->completeDefinition(); 4283 4284 return getPointerType(getTagDeclType(T)); 4285 } 4286 4287 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() { 4288 if (!ObjCInstanceTypeDecl) 4289 ObjCInstanceTypeDecl = TypedefDecl::Create(*this, 4290 getTranslationUnitDecl(), 4291 SourceLocation(), 4292 SourceLocation(), 4293 &Idents.get("instancetype"), 4294 getTrivialTypeSourceInfo(getObjCIdType())); 4295 return ObjCInstanceTypeDecl; 4296 } 4297 4298 // This returns true if a type has been typedefed to BOOL: 4299 // typedef <type> BOOL; 4300 static bool isTypeTypedefedAsBOOL(QualType T) { 4301 if (const TypedefType *TT = dyn_cast<TypedefType>(T)) 4302 if (IdentifierInfo *II = TT->getDecl()->getIdentifier()) 4303 return II->isStr("BOOL"); 4304 4305 return false; 4306 } 4307 4308 /// getObjCEncodingTypeSize returns size of type for objective-c encoding 4309 /// purpose. 4310 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const { 4311 if (!type->isIncompleteArrayType() && type->isIncompleteType()) 4312 return CharUnits::Zero(); 4313 4314 CharUnits sz = getTypeSizeInChars(type); 4315 4316 // Make all integer and enum types at least as large as an int 4317 if (sz.isPositive() && type->isIntegralOrEnumerationType()) 4318 sz = std::max(sz, getTypeSizeInChars(IntTy)); 4319 // Treat arrays as pointers, since that's how they're passed in. 4320 else if (type->isArrayType()) 4321 sz = getTypeSizeInChars(VoidPtrTy); 4322 return sz; 4323 } 4324 4325 static inline 4326 std::string charUnitsToString(const CharUnits &CU) { 4327 return llvm::itostr(CU.getQuantity()); 4328 } 4329 4330 /// getObjCEncodingForBlock - Return the encoded type for this block 4331 /// declaration. 4332 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const { 4333 std::string S; 4334 4335 const BlockDecl *Decl = Expr->getBlockDecl(); 4336 QualType BlockTy = 4337 Expr->getType()->getAs<BlockPointerType>()->getPointeeType(); 4338 // Encode result type. 4339 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S); 4340 // Compute size of all parameters. 4341 // Start with computing size of a pointer in number of bytes. 4342 // FIXME: There might(should) be a better way of doing this computation! 4343 SourceLocation Loc; 4344 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 4345 CharUnits ParmOffset = PtrSize; 4346 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), 4347 E = Decl->param_end(); PI != E; ++PI) { 4348 QualType PType = (*PI)->getType(); 4349 CharUnits sz = getObjCEncodingTypeSize(PType); 4350 if (sz.isZero()) 4351 continue; 4352 assert (sz.isPositive() && "BlockExpr - Incomplete param type"); 4353 ParmOffset += sz; 4354 } 4355 // Size of the argument frame 4356 S += charUnitsToString(ParmOffset); 4357 // Block pointer and offset. 4358 S += "@?0"; 4359 4360 // Argument types. 4361 ParmOffset = PtrSize; 4362 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E = 4363 Decl->param_end(); PI != E; ++PI) { 4364 ParmVarDecl *PVDecl = *PI; 4365 QualType PType = PVDecl->getOriginalType(); 4366 if (const ArrayType *AT = 4367 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 4368 // Use array's original type only if it has known number of 4369 // elements. 4370 if (!isa<ConstantArrayType>(AT)) 4371 PType = PVDecl->getType(); 4372 } else if (PType->isFunctionType()) 4373 PType = PVDecl->getType(); 4374 getObjCEncodingForType(PType, S); 4375 S += charUnitsToString(ParmOffset); 4376 ParmOffset += getObjCEncodingTypeSize(PType); 4377 } 4378 4379 return S; 4380 } 4381 4382 bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl, 4383 std::string& S) { 4384 // Encode result type. 4385 getObjCEncodingForType(Decl->getResultType(), S); 4386 CharUnits ParmOffset; 4387 // Compute size of all parameters. 4388 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(), 4389 E = Decl->param_end(); PI != E; ++PI) { 4390 QualType PType = (*PI)->getType(); 4391 CharUnits sz = getObjCEncodingTypeSize(PType); 4392 if (sz.isZero()) 4393 continue; 4394 4395 assert (sz.isPositive() && 4396 "getObjCEncodingForFunctionDecl - Incomplete param type"); 4397 ParmOffset += sz; 4398 } 4399 S += charUnitsToString(ParmOffset); 4400 ParmOffset = CharUnits::Zero(); 4401 4402 // Argument types. 4403 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(), 4404 E = Decl->param_end(); PI != E; ++PI) { 4405 ParmVarDecl *PVDecl = *PI; 4406 QualType PType = PVDecl->getOriginalType(); 4407 if (const ArrayType *AT = 4408 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 4409 // Use array's original type only if it has known number of 4410 // elements. 4411 if (!isa<ConstantArrayType>(AT)) 4412 PType = PVDecl->getType(); 4413 } else if (PType->isFunctionType()) 4414 PType = PVDecl->getType(); 4415 getObjCEncodingForType(PType, S); 4416 S += charUnitsToString(ParmOffset); 4417 ParmOffset += getObjCEncodingTypeSize(PType); 4418 } 4419 4420 return false; 4421 } 4422 4423 /// getObjCEncodingForMethodParameter - Return the encoded type for a single 4424 /// method parameter or return type. If Extended, include class names and 4425 /// block object types. 4426 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, 4427 QualType T, std::string& S, 4428 bool Extended) const { 4429 // Encode type qualifer, 'in', 'inout', etc. for the parameter. 4430 getObjCEncodingForTypeQualifier(QT, S); 4431 // Encode parameter type. 4432 getObjCEncodingForTypeImpl(T, S, true, true, 0, 4433 true /*OutermostType*/, 4434 false /*EncodingProperty*/, 4435 false /*StructField*/, 4436 Extended /*EncodeBlockParameters*/, 4437 Extended /*EncodeClassNames*/); 4438 } 4439 4440 /// getObjCEncodingForMethodDecl - Return the encoded type for this method 4441 /// declaration. 4442 bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, 4443 std::string& S, 4444 bool Extended) const { 4445 // FIXME: This is not very efficient. 4446 // Encode return type. 4447 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(), 4448 Decl->getResultType(), S, Extended); 4449 // Compute size of all parameters. 4450 // Start with computing size of a pointer in number of bytes. 4451 // FIXME: There might(should) be a better way of doing this computation! 4452 SourceLocation Loc; 4453 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 4454 // The first two arguments (self and _cmd) are pointers; account for 4455 // their size. 4456 CharUnits ParmOffset = 2 * PtrSize; 4457 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 4458 E = Decl->sel_param_end(); PI != E; ++PI) { 4459 QualType PType = (*PI)->getType(); 4460 CharUnits sz = getObjCEncodingTypeSize(PType); 4461 if (sz.isZero()) 4462 continue; 4463 4464 assert (sz.isPositive() && 4465 "getObjCEncodingForMethodDecl - Incomplete param type"); 4466 ParmOffset += sz; 4467 } 4468 S += charUnitsToString(ParmOffset); 4469 S += "@0:"; 4470 S += charUnitsToString(PtrSize); 4471 4472 // Argument types. 4473 ParmOffset = 2 * PtrSize; 4474 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 4475 E = Decl->sel_param_end(); PI != E; ++PI) { 4476 const ParmVarDecl *PVDecl = *PI; 4477 QualType PType = PVDecl->getOriginalType(); 4478 if (const ArrayType *AT = 4479 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 4480 // Use array's original type only if it has known number of 4481 // elements. 4482 if (!isa<ConstantArrayType>(AT)) 4483 PType = PVDecl->getType(); 4484 } else if (PType->isFunctionType()) 4485 PType = PVDecl->getType(); 4486 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(), 4487 PType, S, Extended); 4488 S += charUnitsToString(ParmOffset); 4489 ParmOffset += getObjCEncodingTypeSize(PType); 4490 } 4491 4492 return false; 4493 } 4494 4495 /// getObjCEncodingForPropertyDecl - Return the encoded type for this 4496 /// property declaration. If non-NULL, Container must be either an 4497 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be 4498 /// NULL when getting encodings for protocol properties. 4499 /// Property attributes are stored as a comma-delimited C string. The simple 4500 /// attributes readonly and bycopy are encoded as single characters. The 4501 /// parametrized attributes, getter=name, setter=name, and ivar=name, are 4502 /// encoded as single characters, followed by an identifier. Property types 4503 /// are also encoded as a parametrized attribute. The characters used to encode 4504 /// these attributes are defined by the following enumeration: 4505 /// @code 4506 /// enum PropertyAttributes { 4507 /// kPropertyReadOnly = 'R', // property is read-only. 4508 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned 4509 /// kPropertyByref = '&', // property is a reference to the value last assigned 4510 /// kPropertyDynamic = 'D', // property is dynamic 4511 /// kPropertyGetter = 'G', // followed by getter selector name 4512 /// kPropertySetter = 'S', // followed by setter selector name 4513 /// kPropertyInstanceVariable = 'V' // followed by instance variable name 4514 /// kPropertyType = 'T' // followed by old-style type encoding. 4515 /// kPropertyWeak = 'W' // 'weak' property 4516 /// kPropertyStrong = 'P' // property GC'able 4517 /// kPropertyNonAtomic = 'N' // property non-atomic 4518 /// }; 4519 /// @endcode 4520 void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, 4521 const Decl *Container, 4522 std::string& S) const { 4523 // Collect information from the property implementation decl(s). 4524 bool Dynamic = false; 4525 ObjCPropertyImplDecl *SynthesizePID = 0; 4526 4527 // FIXME: Duplicated code due to poor abstraction. 4528 if (Container) { 4529 if (const ObjCCategoryImplDecl *CID = 4530 dyn_cast<ObjCCategoryImplDecl>(Container)) { 4531 for (ObjCCategoryImplDecl::propimpl_iterator 4532 i = CID->propimpl_begin(), e = CID->propimpl_end(); 4533 i != e; ++i) { 4534 ObjCPropertyImplDecl *PID = *i; 4535 if (PID->getPropertyDecl() == PD) { 4536 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) { 4537 Dynamic = true; 4538 } else { 4539 SynthesizePID = PID; 4540 } 4541 } 4542 } 4543 } else { 4544 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container); 4545 for (ObjCCategoryImplDecl::propimpl_iterator 4546 i = OID->propimpl_begin(), e = OID->propimpl_end(); 4547 i != e; ++i) { 4548 ObjCPropertyImplDecl *PID = *i; 4549 if (PID->getPropertyDecl() == PD) { 4550 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) { 4551 Dynamic = true; 4552 } else { 4553 SynthesizePID = PID; 4554 } 4555 } 4556 } 4557 } 4558 } 4559 4560 // FIXME: This is not very efficient. 4561 S = "T"; 4562 4563 // Encode result type. 4564 // GCC has some special rules regarding encoding of properties which 4565 // closely resembles encoding of ivars. 4566 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0, 4567 true /* outermost type */, 4568 true /* encoding for property */); 4569 4570 if (PD->isReadOnly()) { 4571 S += ",R"; 4572 } else { 4573 switch (PD->getSetterKind()) { 4574 case ObjCPropertyDecl::Assign: break; 4575 case ObjCPropertyDecl::Copy: S += ",C"; break; 4576 case ObjCPropertyDecl::Retain: S += ",&"; break; 4577 case ObjCPropertyDecl::Weak: S += ",W"; break; 4578 } 4579 } 4580 4581 // It really isn't clear at all what this means, since properties 4582 // are "dynamic by default". 4583 if (Dynamic) 4584 S += ",D"; 4585 4586 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic) 4587 S += ",N"; 4588 4589 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) { 4590 S += ",G"; 4591 S += PD->getGetterName().getAsString(); 4592 } 4593 4594 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) { 4595 S += ",S"; 4596 S += PD->getSetterName().getAsString(); 4597 } 4598 4599 if (SynthesizePID) { 4600 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl(); 4601 S += ",V"; 4602 S += OID->getNameAsString(); 4603 } 4604 4605 // FIXME: OBJCGC: weak & strong 4606 } 4607 4608 /// getLegacyIntegralTypeEncoding - 4609 /// Another legacy compatibility encoding: 32-bit longs are encoded as 4610 /// 'l' or 'L' , but not always. For typedefs, we need to use 4611 /// 'i' or 'I' instead if encoding a struct field, or a pointer! 4612 /// 4613 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const { 4614 if (isa<TypedefType>(PointeeTy.getTypePtr())) { 4615 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) { 4616 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32) 4617 PointeeTy = UnsignedIntTy; 4618 else 4619 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32) 4620 PointeeTy = IntTy; 4621 } 4622 } 4623 } 4624 4625 void ASTContext::getObjCEncodingForType(QualType T, std::string& S, 4626 const FieldDecl *Field) const { 4627 // We follow the behavior of gcc, expanding structures which are 4628 // directly pointed to, and expanding embedded structures. Note that 4629 // these rules are sufficient to prevent recursive encoding of the 4630 // same type. 4631 getObjCEncodingForTypeImpl(T, S, true, true, Field, 4632 true /* outermost type */); 4633 } 4634 4635 static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) { 4636 switch (T->getAs<BuiltinType>()->getKind()) { 4637 default: llvm_unreachable("Unhandled builtin type kind"); 4638 case BuiltinType::Void: return 'v'; 4639 case BuiltinType::Bool: return 'B'; 4640 case BuiltinType::Char_U: 4641 case BuiltinType::UChar: return 'C'; 4642 case BuiltinType::UShort: return 'S'; 4643 case BuiltinType::UInt: return 'I'; 4644 case BuiltinType::ULong: 4645 return C->getIntWidth(T) == 32 ? 'L' : 'Q'; 4646 case BuiltinType::UInt128: return 'T'; 4647 case BuiltinType::ULongLong: return 'Q'; 4648 case BuiltinType::Char_S: 4649 case BuiltinType::SChar: return 'c'; 4650 case BuiltinType::Short: return 's'; 4651 case BuiltinType::WChar_S: 4652 case BuiltinType::WChar_U: 4653 case BuiltinType::Int: return 'i'; 4654 case BuiltinType::Long: 4655 return C->getIntWidth(T) == 32 ? 'l' : 'q'; 4656 case BuiltinType::LongLong: return 'q'; 4657 case BuiltinType::Int128: return 't'; 4658 case BuiltinType::Float: return 'f'; 4659 case BuiltinType::Double: return 'd'; 4660 case BuiltinType::LongDouble: return 'D'; 4661 } 4662 } 4663 4664 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) { 4665 EnumDecl *Enum = ET->getDecl(); 4666 4667 // The encoding of an non-fixed enum type is always 'i', regardless of size. 4668 if (!Enum->isFixed()) 4669 return 'i'; 4670 4671 // The encoding of a fixed enum type matches its fixed underlying type. 4672 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType()); 4673 } 4674 4675 static void EncodeBitField(const ASTContext *Ctx, std::string& S, 4676 QualType T, const FieldDecl *FD) { 4677 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl"); 4678 S += 'b'; 4679 // The NeXT runtime encodes bit fields as b followed by the number of bits. 4680 // The GNU runtime requires more information; bitfields are encoded as b, 4681 // then the offset (in bits) of the first element, then the type of the 4682 // bitfield, then the size in bits. For example, in this structure: 4683 // 4684 // struct 4685 // { 4686 // int integer; 4687 // int flags:2; 4688 // }; 4689 // On a 32-bit system, the encoding for flags would be b2 for the NeXT 4690 // runtime, but b32i2 for the GNU runtime. The reason for this extra 4691 // information is not especially sensible, but we're stuck with it for 4692 // compatibility with GCC, although providing it breaks anything that 4693 // actually uses runtime introspection and wants to work on both runtimes... 4694 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) { 4695 const RecordDecl *RD = FD->getParent(); 4696 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD); 4697 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex())); 4698 if (const EnumType *ET = T->getAs<EnumType>()) 4699 S += ObjCEncodingForEnumType(Ctx, ET); 4700 else 4701 S += ObjCEncodingForPrimitiveKind(Ctx, T); 4702 } 4703 S += llvm::utostr(FD->getBitWidthValue(*Ctx)); 4704 } 4705 4706 // FIXME: Use SmallString for accumulating string. 4707 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, 4708 bool ExpandPointedToStructures, 4709 bool ExpandStructures, 4710 const FieldDecl *FD, 4711 bool OutermostType, 4712 bool EncodingProperty, 4713 bool StructField, 4714 bool EncodeBlockParameters, 4715 bool EncodeClassNames) const { 4716 if (T->getAs<BuiltinType>()) { 4717 if (FD && FD->isBitField()) 4718 return EncodeBitField(this, S, T, FD); 4719 S += ObjCEncodingForPrimitiveKind(this, T); 4720 return; 4721 } 4722 4723 if (const ComplexType *CT = T->getAs<ComplexType>()) { 4724 S += 'j'; 4725 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false, 4726 false); 4727 return; 4728 } 4729 4730 // encoding for pointer or r3eference types. 4731 QualType PointeeTy; 4732 if (const PointerType *PT = T->getAs<PointerType>()) { 4733 if (PT->isObjCSelType()) { 4734 S += ':'; 4735 return; 4736 } 4737 PointeeTy = PT->getPointeeType(); 4738 } 4739 else if (const ReferenceType *RT = T->getAs<ReferenceType>()) 4740 PointeeTy = RT->getPointeeType(); 4741 if (!PointeeTy.isNull()) { 4742 bool isReadOnly = false; 4743 // For historical/compatibility reasons, the read-only qualifier of the 4744 // pointee gets emitted _before_ the '^'. The read-only qualifier of 4745 // the pointer itself gets ignored, _unless_ we are looking at a typedef! 4746 // Also, do not emit the 'r' for anything but the outermost type! 4747 if (isa<TypedefType>(T.getTypePtr())) { 4748 if (OutermostType && T.isConstQualified()) { 4749 isReadOnly = true; 4750 S += 'r'; 4751 } 4752 } else if (OutermostType) { 4753 QualType P = PointeeTy; 4754 while (P->getAs<PointerType>()) 4755 P = P->getAs<PointerType>()->getPointeeType(); 4756 if (P.isConstQualified()) { 4757 isReadOnly = true; 4758 S += 'r'; 4759 } 4760 } 4761 if (isReadOnly) { 4762 // Another legacy compatibility encoding. Some ObjC qualifier and type 4763 // combinations need to be rearranged. 4764 // Rewrite "in const" from "nr" to "rn" 4765 if (StringRef(S).endswith("nr")) 4766 S.replace(S.end()-2, S.end(), "rn"); 4767 } 4768 4769 if (PointeeTy->isCharType()) { 4770 // char pointer types should be encoded as '*' unless it is a 4771 // type that has been typedef'd to 'BOOL'. 4772 if (!isTypeTypedefedAsBOOL(PointeeTy)) { 4773 S += '*'; 4774 return; 4775 } 4776 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) { 4777 // GCC binary compat: Need to convert "struct objc_class *" to "#". 4778 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) { 4779 S += '#'; 4780 return; 4781 } 4782 // GCC binary compat: Need to convert "struct objc_object *" to "@". 4783 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) { 4784 S += '@'; 4785 return; 4786 } 4787 // fall through... 4788 } 4789 S += '^'; 4790 getLegacyIntegralTypeEncoding(PointeeTy); 4791 4792 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures, 4793 NULL); 4794 return; 4795 } 4796 4797 if (const ArrayType *AT = 4798 // Ignore type qualifiers etc. 4799 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) { 4800 if (isa<IncompleteArrayType>(AT) && !StructField) { 4801 // Incomplete arrays are encoded as a pointer to the array element. 4802 S += '^'; 4803 4804 getObjCEncodingForTypeImpl(AT->getElementType(), S, 4805 false, ExpandStructures, FD); 4806 } else { 4807 S += '['; 4808 4809 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) { 4810 if (getTypeSize(CAT->getElementType()) == 0) 4811 S += '0'; 4812 else 4813 S += llvm::utostr(CAT->getSize().getZExtValue()); 4814 } else { 4815 //Variable length arrays are encoded as a regular array with 0 elements. 4816 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) && 4817 "Unknown array type!"); 4818 S += '0'; 4819 } 4820 4821 getObjCEncodingForTypeImpl(AT->getElementType(), S, 4822 false, ExpandStructures, FD); 4823 S += ']'; 4824 } 4825 return; 4826 } 4827 4828 if (T->getAs<FunctionType>()) { 4829 S += '?'; 4830 return; 4831 } 4832 4833 if (const RecordType *RTy = T->getAs<RecordType>()) { 4834 RecordDecl *RDecl = RTy->getDecl(); 4835 S += RDecl->isUnion() ? '(' : '{'; 4836 // Anonymous structures print as '?' 4837 if (const IdentifierInfo *II = RDecl->getIdentifier()) { 4838 S += II->getName(); 4839 if (ClassTemplateSpecializationDecl *Spec 4840 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) { 4841 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 4842 std::string TemplateArgsStr 4843 = TemplateSpecializationType::PrintTemplateArgumentList( 4844 TemplateArgs.data(), 4845 TemplateArgs.size(), 4846 (*this).getPrintingPolicy()); 4847 4848 S += TemplateArgsStr; 4849 } 4850 } else { 4851 S += '?'; 4852 } 4853 if (ExpandStructures) { 4854 S += '='; 4855 if (!RDecl->isUnion()) { 4856 getObjCEncodingForStructureImpl(RDecl, S, FD); 4857 } else { 4858 for (RecordDecl::field_iterator Field = RDecl->field_begin(), 4859 FieldEnd = RDecl->field_end(); 4860 Field != FieldEnd; ++Field) { 4861 if (FD) { 4862 S += '"'; 4863 S += Field->getNameAsString(); 4864 S += '"'; 4865 } 4866 4867 // Special case bit-fields. 4868 if (Field->isBitField()) { 4869 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, 4870 *Field); 4871 } else { 4872 QualType qt = Field->getType(); 4873 getLegacyIntegralTypeEncoding(qt); 4874 getObjCEncodingForTypeImpl(qt, S, false, true, 4875 FD, /*OutermostType*/false, 4876 /*EncodingProperty*/false, 4877 /*StructField*/true); 4878 } 4879 } 4880 } 4881 } 4882 S += RDecl->isUnion() ? ')' : '}'; 4883 return; 4884 } 4885 4886 if (const EnumType *ET = T->getAs<EnumType>()) { 4887 if (FD && FD->isBitField()) 4888 EncodeBitField(this, S, T, FD); 4889 else 4890 S += ObjCEncodingForEnumType(this, ET); 4891 return; 4892 } 4893 4894 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) { 4895 S += "@?"; // Unlike a pointer-to-function, which is "^?". 4896 if (EncodeBlockParameters) { 4897 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>(); 4898 4899 S += '<'; 4900 // Block return type 4901 getObjCEncodingForTypeImpl(FT->getResultType(), S, 4902 ExpandPointedToStructures, ExpandStructures, 4903 FD, 4904 false /* OutermostType */, 4905 EncodingProperty, 4906 false /* StructField */, 4907 EncodeBlockParameters, 4908 EncodeClassNames); 4909 // Block self 4910 S += "@?"; 4911 // Block parameters 4912 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) { 4913 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(), 4914 E = FPT->arg_type_end(); I && (I != E); ++I) { 4915 getObjCEncodingForTypeImpl(*I, S, 4916 ExpandPointedToStructures, 4917 ExpandStructures, 4918 FD, 4919 false /* OutermostType */, 4920 EncodingProperty, 4921 false /* StructField */, 4922 EncodeBlockParameters, 4923 EncodeClassNames); 4924 } 4925 } 4926 S += '>'; 4927 } 4928 return; 4929 } 4930 4931 // Ignore protocol qualifiers when mangling at this level. 4932 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>()) 4933 T = OT->getBaseType(); 4934 4935 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) { 4936 // @encode(class_name) 4937 ObjCInterfaceDecl *OI = OIT->getDecl(); 4938 S += '{'; 4939 const IdentifierInfo *II = OI->getIdentifier(); 4940 S += II->getName(); 4941 S += '='; 4942 SmallVector<const ObjCIvarDecl*, 32> Ivars; 4943 DeepCollectObjCIvars(OI, true, Ivars); 4944 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) { 4945 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]); 4946 if (Field->isBitField()) 4947 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field); 4948 else 4949 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD); 4950 } 4951 S += '}'; 4952 return; 4953 } 4954 4955 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) { 4956 if (OPT->isObjCIdType()) { 4957 S += '@'; 4958 return; 4959 } 4960 4961 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) { 4962 // FIXME: Consider if we need to output qualifiers for 'Class<p>'. 4963 // Since this is a binary compatibility issue, need to consult with runtime 4964 // folks. Fortunately, this is a *very* obsure construct. 4965 S += '#'; 4966 return; 4967 } 4968 4969 if (OPT->isObjCQualifiedIdType()) { 4970 getObjCEncodingForTypeImpl(getObjCIdType(), S, 4971 ExpandPointedToStructures, 4972 ExpandStructures, FD); 4973 if (FD || EncodingProperty || EncodeClassNames) { 4974 // Note that we do extended encoding of protocol qualifer list 4975 // Only when doing ivar or property encoding. 4976 S += '"'; 4977 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(), 4978 E = OPT->qual_end(); I != E; ++I) { 4979 S += '<'; 4980 S += (*I)->getNameAsString(); 4981 S += '>'; 4982 } 4983 S += '"'; 4984 } 4985 return; 4986 } 4987 4988 QualType PointeeTy = OPT->getPointeeType(); 4989 if (!EncodingProperty && 4990 isa<TypedefType>(PointeeTy.getTypePtr())) { 4991 // Another historical/compatibility reason. 4992 // We encode the underlying type which comes out as 4993 // {...}; 4994 S += '^'; 4995 getObjCEncodingForTypeImpl(PointeeTy, S, 4996 false, ExpandPointedToStructures, 4997 NULL); 4998 return; 4999 } 5000 5001 S += '@'; 5002 if (OPT->getInterfaceDecl() && 5003 (FD || EncodingProperty || EncodeClassNames)) { 5004 S += '"'; 5005 S += OPT->getInterfaceDecl()->getIdentifier()->getName(); 5006 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(), 5007 E = OPT->qual_end(); I != E; ++I) { 5008 S += '<'; 5009 S += (*I)->getNameAsString(); 5010 S += '>'; 5011 } 5012 S += '"'; 5013 } 5014 return; 5015 } 5016 5017 // gcc just blithely ignores member pointers. 5018 // TODO: maybe there should be a mangling for these 5019 if (T->getAs<MemberPointerType>()) 5020 return; 5021 5022 if (T->isVectorType()) { 5023 // This matches gcc's encoding, even though technically it is 5024 // insufficient. 5025 // FIXME. We should do a better job than gcc. 5026 return; 5027 } 5028 5029 llvm_unreachable("@encode for type not implemented!"); 5030 } 5031 5032 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl, 5033 std::string &S, 5034 const FieldDecl *FD, 5035 bool includeVBases) const { 5036 assert(RDecl && "Expected non-null RecordDecl"); 5037 assert(!RDecl->isUnion() && "Should not be called for unions"); 5038 if (!RDecl->getDefinition()) 5039 return; 5040 5041 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl); 5042 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets; 5043 const ASTRecordLayout &layout = getASTRecordLayout(RDecl); 5044 5045 if (CXXRec) { 5046 for (CXXRecordDecl::base_class_iterator 5047 BI = CXXRec->bases_begin(), 5048 BE = CXXRec->bases_end(); BI != BE; ++BI) { 5049 if (!BI->isVirtual()) { 5050 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl(); 5051 if (base->isEmpty()) 5052 continue; 5053 uint64_t offs = toBits(layout.getBaseClassOffset(base)); 5054 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 5055 std::make_pair(offs, base)); 5056 } 5057 } 5058 } 5059 5060 unsigned i = 0; 5061 for (RecordDecl::field_iterator Field = RDecl->field_begin(), 5062 FieldEnd = RDecl->field_end(); 5063 Field != FieldEnd; ++Field, ++i) { 5064 uint64_t offs = layout.getFieldOffset(i); 5065 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 5066 std::make_pair(offs, *Field)); 5067 } 5068 5069 if (CXXRec && includeVBases) { 5070 for (CXXRecordDecl::base_class_iterator 5071 BI = CXXRec->vbases_begin(), 5072 BE = CXXRec->vbases_end(); BI != BE; ++BI) { 5073 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl(); 5074 if (base->isEmpty()) 5075 continue; 5076 uint64_t offs = toBits(layout.getVBaseClassOffset(base)); 5077 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end()) 5078 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(), 5079 std::make_pair(offs, base)); 5080 } 5081 } 5082 5083 CharUnits size; 5084 if (CXXRec) { 5085 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize(); 5086 } else { 5087 size = layout.getSize(); 5088 } 5089 5090 uint64_t CurOffs = 0; 5091 std::multimap<uint64_t, NamedDecl *>::iterator 5092 CurLayObj = FieldOrBaseOffsets.begin(); 5093 5094 if (CXXRec && CXXRec->isDynamicClass() && 5095 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) { 5096 if (FD) { 5097 S += "\"_vptr$"; 5098 std::string recname = CXXRec->getNameAsString(); 5099 if (recname.empty()) recname = "?"; 5100 S += recname; 5101 S += '"'; 5102 } 5103 S += "^^?"; 5104 CurOffs += getTypeSize(VoidPtrTy); 5105 } 5106 5107 if (!RDecl->hasFlexibleArrayMember()) { 5108 // Mark the end of the structure. 5109 uint64_t offs = toBits(size); 5110 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 5111 std::make_pair(offs, (NamedDecl*)0)); 5112 } 5113 5114 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) { 5115 assert(CurOffs <= CurLayObj->first); 5116 5117 if (CurOffs < CurLayObj->first) { 5118 uint64_t padding = CurLayObj->first - CurOffs; 5119 // FIXME: There doesn't seem to be a way to indicate in the encoding that 5120 // packing/alignment of members is different that normal, in which case 5121 // the encoding will be out-of-sync with the real layout. 5122 // If the runtime switches to just consider the size of types without 5123 // taking into account alignment, we could make padding explicit in the 5124 // encoding (e.g. using arrays of chars). The encoding strings would be 5125 // longer then though. 5126 CurOffs += padding; 5127 } 5128 5129 NamedDecl *dcl = CurLayObj->second; 5130 if (dcl == 0) 5131 break; // reached end of structure. 5132 5133 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) { 5134 // We expand the bases without their virtual bases since those are going 5135 // in the initial structure. Note that this differs from gcc which 5136 // expands virtual bases each time one is encountered in the hierarchy, 5137 // making the encoding type bigger than it really is. 5138 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false); 5139 assert(!base->isEmpty()); 5140 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize()); 5141 } else { 5142 FieldDecl *field = cast<FieldDecl>(dcl); 5143 if (FD) { 5144 S += '"'; 5145 S += field->getNameAsString(); 5146 S += '"'; 5147 } 5148 5149 if (field->isBitField()) { 5150 EncodeBitField(this, S, field->getType(), field); 5151 CurOffs += field->getBitWidthValue(*this); 5152 } else { 5153 QualType qt = field->getType(); 5154 getLegacyIntegralTypeEncoding(qt); 5155 getObjCEncodingForTypeImpl(qt, S, false, true, FD, 5156 /*OutermostType*/false, 5157 /*EncodingProperty*/false, 5158 /*StructField*/true); 5159 CurOffs += getTypeSize(field->getType()); 5160 } 5161 } 5162 } 5163 } 5164 5165 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, 5166 std::string& S) const { 5167 if (QT & Decl::OBJC_TQ_In) 5168 S += 'n'; 5169 if (QT & Decl::OBJC_TQ_Inout) 5170 S += 'N'; 5171 if (QT & Decl::OBJC_TQ_Out) 5172 S += 'o'; 5173 if (QT & Decl::OBJC_TQ_Bycopy) 5174 S += 'O'; 5175 if (QT & Decl::OBJC_TQ_Byref) 5176 S += 'R'; 5177 if (QT & Decl::OBJC_TQ_Oneway) 5178 S += 'V'; 5179 } 5180 5181 TypedefDecl *ASTContext::getObjCIdDecl() const { 5182 if (!ObjCIdDecl) { 5183 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0); 5184 T = getObjCObjectPointerType(T); 5185 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T); 5186 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this), 5187 getTranslationUnitDecl(), 5188 SourceLocation(), SourceLocation(), 5189 &Idents.get("id"), IdInfo); 5190 } 5191 5192 return ObjCIdDecl; 5193 } 5194 5195 TypedefDecl *ASTContext::getObjCSelDecl() const { 5196 if (!ObjCSelDecl) { 5197 QualType SelT = getPointerType(ObjCBuiltinSelTy); 5198 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT); 5199 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this), 5200 getTranslationUnitDecl(), 5201 SourceLocation(), SourceLocation(), 5202 &Idents.get("SEL"), SelInfo); 5203 } 5204 return ObjCSelDecl; 5205 } 5206 5207 TypedefDecl *ASTContext::getObjCClassDecl() const { 5208 if (!ObjCClassDecl) { 5209 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0); 5210 T = getObjCObjectPointerType(T); 5211 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T); 5212 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this), 5213 getTranslationUnitDecl(), 5214 SourceLocation(), SourceLocation(), 5215 &Idents.get("Class"), ClassInfo); 5216 } 5217 5218 return ObjCClassDecl; 5219 } 5220 5221 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const { 5222 if (!ObjCProtocolClassDecl) { 5223 ObjCProtocolClassDecl 5224 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(), 5225 SourceLocation(), 5226 &Idents.get("Protocol"), 5227 /*PrevDecl=*/0, 5228 SourceLocation(), true); 5229 } 5230 5231 return ObjCProtocolClassDecl; 5232 } 5233 5234 //===----------------------------------------------------------------------===// 5235 // __builtin_va_list Construction Functions 5236 //===----------------------------------------------------------------------===// 5237 5238 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) { 5239 // typedef char* __builtin_va_list; 5240 QualType CharPtrType = Context->getPointerType(Context->CharTy); 5241 TypeSourceInfo *TInfo 5242 = Context->getTrivialTypeSourceInfo(CharPtrType); 5243 5244 TypedefDecl *VaListTypeDecl 5245 = TypedefDecl::Create(const_cast<ASTContext &>(*Context), 5246 Context->getTranslationUnitDecl(), 5247 SourceLocation(), SourceLocation(), 5248 &Context->Idents.get("__builtin_va_list"), 5249 TInfo); 5250 return VaListTypeDecl; 5251 } 5252 5253 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) { 5254 // typedef void* __builtin_va_list; 5255 QualType VoidPtrType = Context->getPointerType(Context->VoidTy); 5256 TypeSourceInfo *TInfo 5257 = Context->getTrivialTypeSourceInfo(VoidPtrType); 5258 5259 TypedefDecl *VaListTypeDecl 5260 = TypedefDecl::Create(const_cast<ASTContext &>(*Context), 5261 Context->getTranslationUnitDecl(), 5262 SourceLocation(), SourceLocation(), 5263 &Context->Idents.get("__builtin_va_list"), 5264 TInfo); 5265 return VaListTypeDecl; 5266 } 5267 5268 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) { 5269 // typedef struct __va_list_tag { 5270 RecordDecl *VaListTagDecl; 5271 5272 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct, 5273 Context->getTranslationUnitDecl(), 5274 &Context->Idents.get("__va_list_tag")); 5275 VaListTagDecl->startDefinition(); 5276 5277 const size_t NumFields = 5; 5278 QualType FieldTypes[NumFields]; 5279 const char *FieldNames[NumFields]; 5280 5281 // unsigned char gpr; 5282 FieldTypes[0] = Context->UnsignedCharTy; 5283 FieldNames[0] = "gpr"; 5284 5285 // unsigned char fpr; 5286 FieldTypes[1] = Context->UnsignedCharTy; 5287 FieldNames[1] = "fpr"; 5288 5289 // unsigned short reserved; 5290 FieldTypes[2] = Context->UnsignedShortTy; 5291 FieldNames[2] = "reserved"; 5292 5293 // void* overflow_arg_area; 5294 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 5295 FieldNames[3] = "overflow_arg_area"; 5296 5297 // void* reg_save_area; 5298 FieldTypes[4] = Context->getPointerType(Context->VoidTy); 5299 FieldNames[4] = "reg_save_area"; 5300 5301 // Create fields 5302 for (unsigned i = 0; i < NumFields; ++i) { 5303 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl, 5304 SourceLocation(), 5305 SourceLocation(), 5306 &Context->Idents.get(FieldNames[i]), 5307 FieldTypes[i], /*TInfo=*/0, 5308 /*BitWidth=*/0, 5309 /*Mutable=*/false, 5310 ICIS_NoInit); 5311 Field->setAccess(AS_public); 5312 VaListTagDecl->addDecl(Field); 5313 } 5314 VaListTagDecl->completeDefinition(); 5315 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 5316 Context->VaListTagTy = VaListTagType; 5317 5318 // } __va_list_tag; 5319 TypedefDecl *VaListTagTypedefDecl 5320 = TypedefDecl::Create(const_cast<ASTContext &>(*Context), 5321 Context->getTranslationUnitDecl(), 5322 SourceLocation(), SourceLocation(), 5323 &Context->Idents.get("__va_list_tag"), 5324 Context->getTrivialTypeSourceInfo(VaListTagType)); 5325 QualType VaListTagTypedefType = 5326 Context->getTypedefType(VaListTagTypedefDecl); 5327 5328 // typedef __va_list_tag __builtin_va_list[1]; 5329 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 5330 QualType VaListTagArrayType 5331 = Context->getConstantArrayType(VaListTagTypedefType, 5332 Size, ArrayType::Normal, 0); 5333 TypeSourceInfo *TInfo 5334 = Context->getTrivialTypeSourceInfo(VaListTagArrayType); 5335 TypedefDecl *VaListTypedefDecl 5336 = TypedefDecl::Create(const_cast<ASTContext &>(*Context), 5337 Context->getTranslationUnitDecl(), 5338 SourceLocation(), SourceLocation(), 5339 &Context->Idents.get("__builtin_va_list"), 5340 TInfo); 5341 5342 return VaListTypedefDecl; 5343 } 5344 5345 static TypedefDecl * 5346 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) { 5347 // typedef struct __va_list_tag { 5348 RecordDecl *VaListTagDecl; 5349 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct, 5350 Context->getTranslationUnitDecl(), 5351 &Context->Idents.get("__va_list_tag")); 5352 VaListTagDecl->startDefinition(); 5353 5354 const size_t NumFields = 4; 5355 QualType FieldTypes[NumFields]; 5356 const char *FieldNames[NumFields]; 5357 5358 // unsigned gp_offset; 5359 FieldTypes[0] = Context->UnsignedIntTy; 5360 FieldNames[0] = "gp_offset"; 5361 5362 // unsigned fp_offset; 5363 FieldTypes[1] = Context->UnsignedIntTy; 5364 FieldNames[1] = "fp_offset"; 5365 5366 // void* overflow_arg_area; 5367 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 5368 FieldNames[2] = "overflow_arg_area"; 5369 5370 // void* reg_save_area; 5371 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 5372 FieldNames[3] = "reg_save_area"; 5373 5374 // Create fields 5375 for (unsigned i = 0; i < NumFields; ++i) { 5376 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 5377 VaListTagDecl, 5378 SourceLocation(), 5379 SourceLocation(), 5380 &Context->Idents.get(FieldNames[i]), 5381 FieldTypes[i], /*TInfo=*/0, 5382 /*BitWidth=*/0, 5383 /*Mutable=*/false, 5384 ICIS_NoInit); 5385 Field->setAccess(AS_public); 5386 VaListTagDecl->addDecl(Field); 5387 } 5388 VaListTagDecl->completeDefinition(); 5389 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 5390 Context->VaListTagTy = VaListTagType; 5391 5392 // } __va_list_tag; 5393 TypedefDecl *VaListTagTypedefDecl 5394 = TypedefDecl::Create(const_cast<ASTContext &>(*Context), 5395 Context->getTranslationUnitDecl(), 5396 SourceLocation(), SourceLocation(), 5397 &Context->Idents.get("__va_list_tag"), 5398 Context->getTrivialTypeSourceInfo(VaListTagType)); 5399 QualType VaListTagTypedefType = 5400 Context->getTypedefType(VaListTagTypedefDecl); 5401 5402 // typedef __va_list_tag __builtin_va_list[1]; 5403 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 5404 QualType VaListTagArrayType 5405 = Context->getConstantArrayType(VaListTagTypedefType, 5406 Size, ArrayType::Normal,0); 5407 TypeSourceInfo *TInfo 5408 = Context->getTrivialTypeSourceInfo(VaListTagArrayType); 5409 TypedefDecl *VaListTypedefDecl 5410 = TypedefDecl::Create(const_cast<ASTContext &>(*Context), 5411 Context->getTranslationUnitDecl(), 5412 SourceLocation(), SourceLocation(), 5413 &Context->Idents.get("__builtin_va_list"), 5414 TInfo); 5415 5416 return VaListTypedefDecl; 5417 } 5418 5419 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) { 5420 // typedef int __builtin_va_list[4]; 5421 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4); 5422 QualType IntArrayType 5423 = Context->getConstantArrayType(Context->IntTy, 5424 Size, ArrayType::Normal, 0); 5425 TypedefDecl *VaListTypedefDecl 5426 = TypedefDecl::Create(const_cast<ASTContext &>(*Context), 5427 Context->getTranslationUnitDecl(), 5428 SourceLocation(), SourceLocation(), 5429 &Context->Idents.get("__builtin_va_list"), 5430 Context->getTrivialTypeSourceInfo(IntArrayType)); 5431 5432 return VaListTypedefDecl; 5433 } 5434 5435 static TypedefDecl *CreateVaListDecl(const ASTContext *Context, 5436 TargetInfo::BuiltinVaListKind Kind) { 5437 switch (Kind) { 5438 case TargetInfo::CharPtrBuiltinVaList: 5439 return CreateCharPtrBuiltinVaListDecl(Context); 5440 case TargetInfo::VoidPtrBuiltinVaList: 5441 return CreateVoidPtrBuiltinVaListDecl(Context); 5442 case TargetInfo::PowerABIBuiltinVaList: 5443 return CreatePowerABIBuiltinVaListDecl(Context); 5444 case TargetInfo::X86_64ABIBuiltinVaList: 5445 return CreateX86_64ABIBuiltinVaListDecl(Context); 5446 case TargetInfo::PNaClABIBuiltinVaList: 5447 return CreatePNaClABIBuiltinVaListDecl(Context); 5448 } 5449 5450 llvm_unreachable("Unhandled __builtin_va_list type kind"); 5451 } 5452 5453 TypedefDecl *ASTContext::getBuiltinVaListDecl() const { 5454 if (!BuiltinVaListDecl) 5455 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind()); 5456 5457 return BuiltinVaListDecl; 5458 } 5459 5460 QualType ASTContext::getVaListTagType() const { 5461 // Force the creation of VaListTagTy by building the __builtin_va_list 5462 // declaration. 5463 if (VaListTagTy.isNull()) 5464 (void) getBuiltinVaListDecl(); 5465 5466 return VaListTagTy; 5467 } 5468 5469 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) { 5470 assert(ObjCConstantStringType.isNull() && 5471 "'NSConstantString' type already set!"); 5472 5473 ObjCConstantStringType = getObjCInterfaceType(Decl); 5474 } 5475 5476 /// \brief Retrieve the template name that corresponds to a non-empty 5477 /// lookup. 5478 TemplateName 5479 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin, 5480 UnresolvedSetIterator End) const { 5481 unsigned size = End - Begin; 5482 assert(size > 1 && "set is not overloaded!"); 5483 5484 void *memory = Allocate(sizeof(OverloadedTemplateStorage) + 5485 size * sizeof(FunctionTemplateDecl*)); 5486 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size); 5487 5488 NamedDecl **Storage = OT->getStorage(); 5489 for (UnresolvedSetIterator I = Begin; I != End; ++I) { 5490 NamedDecl *D = *I; 5491 assert(isa<FunctionTemplateDecl>(D) || 5492 (isa<UsingShadowDecl>(D) && 5493 isa<FunctionTemplateDecl>(D->getUnderlyingDecl()))); 5494 *Storage++ = D; 5495 } 5496 5497 return TemplateName(OT); 5498 } 5499 5500 /// \brief Retrieve the template name that represents a qualified 5501 /// template name such as \c std::vector. 5502 TemplateName 5503 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, 5504 bool TemplateKeyword, 5505 TemplateDecl *Template) const { 5506 assert(NNS && "Missing nested-name-specifier in qualified template name"); 5507 5508 // FIXME: Canonicalization? 5509 llvm::FoldingSetNodeID ID; 5510 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template); 5511 5512 void *InsertPos = 0; 5513 QualifiedTemplateName *QTN = 5514 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 5515 if (!QTN) { 5516 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>()) 5517 QualifiedTemplateName(NNS, TemplateKeyword, Template); 5518 QualifiedTemplateNames.InsertNode(QTN, InsertPos); 5519 } 5520 5521 return TemplateName(QTN); 5522 } 5523 5524 /// \brief Retrieve the template name that represents a dependent 5525 /// template name such as \c MetaFun::template apply. 5526 TemplateName 5527 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 5528 const IdentifierInfo *Name) const { 5529 assert((!NNS || NNS->isDependent()) && 5530 "Nested name specifier must be dependent"); 5531 5532 llvm::FoldingSetNodeID ID; 5533 DependentTemplateName::Profile(ID, NNS, Name); 5534 5535 void *InsertPos = 0; 5536 DependentTemplateName *QTN = 5537 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 5538 5539 if (QTN) 5540 return TemplateName(QTN); 5541 5542 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 5543 if (CanonNNS == NNS) { 5544 QTN = new (*this, llvm::alignOf<DependentTemplateName>()) 5545 DependentTemplateName(NNS, Name); 5546 } else { 5547 TemplateName Canon = getDependentTemplateName(CanonNNS, Name); 5548 QTN = new (*this, llvm::alignOf<DependentTemplateName>()) 5549 DependentTemplateName(NNS, Name, Canon); 5550 DependentTemplateName *CheckQTN = 5551 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 5552 assert(!CheckQTN && "Dependent type name canonicalization broken"); 5553 (void)CheckQTN; 5554 } 5555 5556 DependentTemplateNames.InsertNode(QTN, InsertPos); 5557 return TemplateName(QTN); 5558 } 5559 5560 /// \brief Retrieve the template name that represents a dependent 5561 /// template name such as \c MetaFun::template operator+. 5562 TemplateName 5563 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 5564 OverloadedOperatorKind Operator) const { 5565 assert((!NNS || NNS->isDependent()) && 5566 "Nested name specifier must be dependent"); 5567 5568 llvm::FoldingSetNodeID ID; 5569 DependentTemplateName::Profile(ID, NNS, Operator); 5570 5571 void *InsertPos = 0; 5572 DependentTemplateName *QTN 5573 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 5574 5575 if (QTN) 5576 return TemplateName(QTN); 5577 5578 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 5579 if (CanonNNS == NNS) { 5580 QTN = new (*this, llvm::alignOf<DependentTemplateName>()) 5581 DependentTemplateName(NNS, Operator); 5582 } else { 5583 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator); 5584 QTN = new (*this, llvm::alignOf<DependentTemplateName>()) 5585 DependentTemplateName(NNS, Operator, Canon); 5586 5587 DependentTemplateName *CheckQTN 5588 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 5589 assert(!CheckQTN && "Dependent template name canonicalization broken"); 5590 (void)CheckQTN; 5591 } 5592 5593 DependentTemplateNames.InsertNode(QTN, InsertPos); 5594 return TemplateName(QTN); 5595 } 5596 5597 TemplateName 5598 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param, 5599 TemplateName replacement) const { 5600 llvm::FoldingSetNodeID ID; 5601 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement); 5602 5603 void *insertPos = 0; 5604 SubstTemplateTemplateParmStorage *subst 5605 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos); 5606 5607 if (!subst) { 5608 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement); 5609 SubstTemplateTemplateParms.InsertNode(subst, insertPos); 5610 } 5611 5612 return TemplateName(subst); 5613 } 5614 5615 TemplateName 5616 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param, 5617 const TemplateArgument &ArgPack) const { 5618 ASTContext &Self = const_cast<ASTContext &>(*this); 5619 llvm::FoldingSetNodeID ID; 5620 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack); 5621 5622 void *InsertPos = 0; 5623 SubstTemplateTemplateParmPackStorage *Subst 5624 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos); 5625 5626 if (!Subst) { 5627 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param, 5628 ArgPack.pack_size(), 5629 ArgPack.pack_begin()); 5630 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos); 5631 } 5632 5633 return TemplateName(Subst); 5634 } 5635 5636 /// getFromTargetType - Given one of the integer types provided by 5637 /// TargetInfo, produce the corresponding type. The unsigned @p Type 5638 /// is actually a value of type @c TargetInfo::IntType. 5639 CanQualType ASTContext::getFromTargetType(unsigned Type) const { 5640 switch (Type) { 5641 case TargetInfo::NoInt: return CanQualType(); 5642 case TargetInfo::SignedShort: return ShortTy; 5643 case TargetInfo::UnsignedShort: return UnsignedShortTy; 5644 case TargetInfo::SignedInt: return IntTy; 5645 case TargetInfo::UnsignedInt: return UnsignedIntTy; 5646 case TargetInfo::SignedLong: return LongTy; 5647 case TargetInfo::UnsignedLong: return UnsignedLongTy; 5648 case TargetInfo::SignedLongLong: return LongLongTy; 5649 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy; 5650 } 5651 5652 llvm_unreachable("Unhandled TargetInfo::IntType value"); 5653 } 5654 5655 //===----------------------------------------------------------------------===// 5656 // Type Predicates. 5657 //===----------------------------------------------------------------------===// 5658 5659 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's 5660 /// garbage collection attribute. 5661 /// 5662 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const { 5663 if (getLangOpts().getGC() == LangOptions::NonGC) 5664 return Qualifiers::GCNone; 5665 5666 assert(getLangOpts().ObjC1); 5667 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr(); 5668 5669 // Default behaviour under objective-C's gc is for ObjC pointers 5670 // (or pointers to them) be treated as though they were declared 5671 // as __strong. 5672 if (GCAttrs == Qualifiers::GCNone) { 5673 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) 5674 return Qualifiers::Strong; 5675 else if (Ty->isPointerType()) 5676 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType()); 5677 } else { 5678 // It's not valid to set GC attributes on anything that isn't a 5679 // pointer. 5680 #ifndef NDEBUG 5681 QualType CT = Ty->getCanonicalTypeInternal(); 5682 while (const ArrayType *AT = dyn_cast<ArrayType>(CT)) 5683 CT = AT->getElementType(); 5684 assert(CT->isAnyPointerType() || CT->isBlockPointerType()); 5685 #endif 5686 } 5687 return GCAttrs; 5688 } 5689 5690 //===----------------------------------------------------------------------===// 5691 // Type Compatibility Testing 5692 //===----------------------------------------------------------------------===// 5693 5694 /// areCompatVectorTypes - Return true if the two specified vector types are 5695 /// compatible. 5696 static bool areCompatVectorTypes(const VectorType *LHS, 5697 const VectorType *RHS) { 5698 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 5699 return LHS->getElementType() == RHS->getElementType() && 5700 LHS->getNumElements() == RHS->getNumElements(); 5701 } 5702 5703 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec, 5704 QualType SecondVec) { 5705 assert(FirstVec->isVectorType() && "FirstVec should be a vector type"); 5706 assert(SecondVec->isVectorType() && "SecondVec should be a vector type"); 5707 5708 if (hasSameUnqualifiedType(FirstVec, SecondVec)) 5709 return true; 5710 5711 // Treat Neon vector types and most AltiVec vector types as if they are the 5712 // equivalent GCC vector types. 5713 const VectorType *First = FirstVec->getAs<VectorType>(); 5714 const VectorType *Second = SecondVec->getAs<VectorType>(); 5715 if (First->getNumElements() == Second->getNumElements() && 5716 hasSameType(First->getElementType(), Second->getElementType()) && 5717 First->getVectorKind() != VectorType::AltiVecPixel && 5718 First->getVectorKind() != VectorType::AltiVecBool && 5719 Second->getVectorKind() != VectorType::AltiVecPixel && 5720 Second->getVectorKind() != VectorType::AltiVecBool) 5721 return true; 5722 5723 return false; 5724 } 5725 5726 //===----------------------------------------------------------------------===// 5727 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's. 5728 //===----------------------------------------------------------------------===// 5729 5730 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the 5731 /// inheritance hierarchy of 'rProto'. 5732 bool 5733 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, 5734 ObjCProtocolDecl *rProto) const { 5735 if (declaresSameEntity(lProto, rProto)) 5736 return true; 5737 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(), 5738 E = rProto->protocol_end(); PI != E; ++PI) 5739 if (ProtocolCompatibleWithProtocol(lProto, *PI)) 5740 return true; 5741 return false; 5742 } 5743 5744 /// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...> 5745 /// return true if lhs's protocols conform to rhs's protocol; false 5746 /// otherwise. 5747 bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) { 5748 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType()) 5749 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false); 5750 return false; 5751 } 5752 5753 /// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and 5754 /// Class<p1, ...>. 5755 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs, 5756 QualType rhs) { 5757 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>(); 5758 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 5759 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible"); 5760 5761 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(), 5762 E = lhsQID->qual_end(); I != E; ++I) { 5763 bool match = false; 5764 ObjCProtocolDecl *lhsProto = *I; 5765 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(), 5766 E = rhsOPT->qual_end(); J != E; ++J) { 5767 ObjCProtocolDecl *rhsProto = *J; 5768 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) { 5769 match = true; 5770 break; 5771 } 5772 } 5773 if (!match) 5774 return false; 5775 } 5776 return true; 5777 } 5778 5779 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an 5780 /// ObjCQualifiedIDType. 5781 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs, 5782 bool compare) { 5783 // Allow id<P..> and an 'id' or void* type in all cases. 5784 if (lhs->isVoidPointerType() || 5785 lhs->isObjCIdType() || lhs->isObjCClassType()) 5786 return true; 5787 else if (rhs->isVoidPointerType() || 5788 rhs->isObjCIdType() || rhs->isObjCClassType()) 5789 return true; 5790 5791 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) { 5792 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 5793 5794 if (!rhsOPT) return false; 5795 5796 if (rhsOPT->qual_empty()) { 5797 // If the RHS is a unqualified interface pointer "NSString*", 5798 // make sure we check the class hierarchy. 5799 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) { 5800 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(), 5801 E = lhsQID->qual_end(); I != E; ++I) { 5802 // when comparing an id<P> on lhs with a static type on rhs, 5803 // see if static class implements all of id's protocols, directly or 5804 // through its super class and categories. 5805 if (!rhsID->ClassImplementsProtocol(*I, true)) 5806 return false; 5807 } 5808 } 5809 // If there are no qualifiers and no interface, we have an 'id'. 5810 return true; 5811 } 5812 // Both the right and left sides have qualifiers. 5813 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(), 5814 E = lhsQID->qual_end(); I != E; ++I) { 5815 ObjCProtocolDecl *lhsProto = *I; 5816 bool match = false; 5817 5818 // when comparing an id<P> on lhs with a static type on rhs, 5819 // see if static class implements all of id's protocols, directly or 5820 // through its super class and categories. 5821 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(), 5822 E = rhsOPT->qual_end(); J != E; ++J) { 5823 ObjCProtocolDecl *rhsProto = *J; 5824 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 5825 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 5826 match = true; 5827 break; 5828 } 5829 } 5830 // If the RHS is a qualified interface pointer "NSString<P>*", 5831 // make sure we check the class hierarchy. 5832 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) { 5833 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(), 5834 E = lhsQID->qual_end(); I != E; ++I) { 5835 // when comparing an id<P> on lhs with a static type on rhs, 5836 // see if static class implements all of id's protocols, directly or 5837 // through its super class and categories. 5838 if (rhsID->ClassImplementsProtocol(*I, true)) { 5839 match = true; 5840 break; 5841 } 5842 } 5843 } 5844 if (!match) 5845 return false; 5846 } 5847 5848 return true; 5849 } 5850 5851 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType(); 5852 assert(rhsQID && "One of the LHS/RHS should be id<x>"); 5853 5854 if (const ObjCObjectPointerType *lhsOPT = 5855 lhs->getAsObjCInterfacePointerType()) { 5856 // If both the right and left sides have qualifiers. 5857 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(), 5858 E = lhsOPT->qual_end(); I != E; ++I) { 5859 ObjCProtocolDecl *lhsProto = *I; 5860 bool match = false; 5861 5862 // when comparing an id<P> on rhs with a static type on lhs, 5863 // see if static class implements all of id's protocols, directly or 5864 // through its super class and categories. 5865 // First, lhs protocols in the qualifier list must be found, direct 5866 // or indirect in rhs's qualifier list or it is a mismatch. 5867 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(), 5868 E = rhsQID->qual_end(); J != E; ++J) { 5869 ObjCProtocolDecl *rhsProto = *J; 5870 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 5871 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 5872 match = true; 5873 break; 5874 } 5875 } 5876 if (!match) 5877 return false; 5878 } 5879 5880 // Static class's protocols, or its super class or category protocols 5881 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch. 5882 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) { 5883 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols; 5884 CollectInheritedProtocols(lhsID, LHSInheritedProtocols); 5885 // This is rather dubious but matches gcc's behavior. If lhs has 5886 // no type qualifier and its class has no static protocol(s) 5887 // assume that it is mismatch. 5888 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty()) 5889 return false; 5890 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I = 5891 LHSInheritedProtocols.begin(), 5892 E = LHSInheritedProtocols.end(); I != E; ++I) { 5893 bool match = false; 5894 ObjCProtocolDecl *lhsProto = (*I); 5895 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(), 5896 E = rhsQID->qual_end(); J != E; ++J) { 5897 ObjCProtocolDecl *rhsProto = *J; 5898 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 5899 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 5900 match = true; 5901 break; 5902 } 5903 } 5904 if (!match) 5905 return false; 5906 } 5907 } 5908 return true; 5909 } 5910 return false; 5911 } 5912 5913 /// canAssignObjCInterfaces - Return true if the two interface types are 5914 /// compatible for assignment from RHS to LHS. This handles validation of any 5915 /// protocol qualifiers on the LHS or RHS. 5916 /// 5917 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, 5918 const ObjCObjectPointerType *RHSOPT) { 5919 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 5920 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 5921 5922 // If either type represents the built-in 'id' or 'Class' types, return true. 5923 if (LHS->isObjCUnqualifiedIdOrClass() || 5924 RHS->isObjCUnqualifiedIdOrClass()) 5925 return true; 5926 5927 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) 5928 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0), 5929 QualType(RHSOPT,0), 5930 false); 5931 5932 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) 5933 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0), 5934 QualType(RHSOPT,0)); 5935 5936 // If we have 2 user-defined types, fall into that path. 5937 if (LHS->getInterface() && RHS->getInterface()) 5938 return canAssignObjCInterfaces(LHS, RHS); 5939 5940 return false; 5941 } 5942 5943 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written 5944 /// for providing type-safety for objective-c pointers used to pass/return 5945 /// arguments in block literals. When passed as arguments, passing 'A*' where 5946 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is 5947 /// not OK. For the return type, the opposite is not OK. 5948 bool ASTContext::canAssignObjCInterfacesInBlockPointer( 5949 const ObjCObjectPointerType *LHSOPT, 5950 const ObjCObjectPointerType *RHSOPT, 5951 bool BlockReturnType) { 5952 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType()) 5953 return true; 5954 5955 if (LHSOPT->isObjCBuiltinType()) { 5956 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType(); 5957 } 5958 5959 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) 5960 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0), 5961 QualType(RHSOPT,0), 5962 false); 5963 5964 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType(); 5965 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType(); 5966 if (LHS && RHS) { // We have 2 user-defined types. 5967 if (LHS != RHS) { 5968 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl())) 5969 return BlockReturnType; 5970 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl())) 5971 return !BlockReturnType; 5972 } 5973 else 5974 return true; 5975 } 5976 return false; 5977 } 5978 5979 /// getIntersectionOfProtocols - This routine finds the intersection of set 5980 /// of protocols inherited from two distinct objective-c pointer objects. 5981 /// It is used to build composite qualifier list of the composite type of 5982 /// the conditional expression involving two objective-c pointer objects. 5983 static 5984 void getIntersectionOfProtocols(ASTContext &Context, 5985 const ObjCObjectPointerType *LHSOPT, 5986 const ObjCObjectPointerType *RHSOPT, 5987 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) { 5988 5989 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 5990 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 5991 assert(LHS->getInterface() && "LHS must have an interface base"); 5992 assert(RHS->getInterface() && "RHS must have an interface base"); 5993 5994 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet; 5995 unsigned LHSNumProtocols = LHS->getNumProtocols(); 5996 if (LHSNumProtocols > 0) 5997 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end()); 5998 else { 5999 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols; 6000 Context.CollectInheritedProtocols(LHS->getInterface(), 6001 LHSInheritedProtocols); 6002 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(), 6003 LHSInheritedProtocols.end()); 6004 } 6005 6006 unsigned RHSNumProtocols = RHS->getNumProtocols(); 6007 if (RHSNumProtocols > 0) { 6008 ObjCProtocolDecl **RHSProtocols = 6009 const_cast<ObjCProtocolDecl **>(RHS->qual_begin()); 6010 for (unsigned i = 0; i < RHSNumProtocols; ++i) 6011 if (InheritedProtocolSet.count(RHSProtocols[i])) 6012 IntersectionOfProtocols.push_back(RHSProtocols[i]); 6013 } else { 6014 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols; 6015 Context.CollectInheritedProtocols(RHS->getInterface(), 6016 RHSInheritedProtocols); 6017 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I = 6018 RHSInheritedProtocols.begin(), 6019 E = RHSInheritedProtocols.end(); I != E; ++I) 6020 if (InheritedProtocolSet.count((*I))) 6021 IntersectionOfProtocols.push_back((*I)); 6022 } 6023 } 6024 6025 /// areCommonBaseCompatible - Returns common base class of the two classes if 6026 /// one found. Note that this is O'2 algorithm. But it will be called as the 6027 /// last type comparison in a ?-exp of ObjC pointer types before a 6028 /// warning is issued. So, its invokation is extremely rare. 6029 QualType ASTContext::areCommonBaseCompatible( 6030 const ObjCObjectPointerType *Lptr, 6031 const ObjCObjectPointerType *Rptr) { 6032 const ObjCObjectType *LHS = Lptr->getObjectType(); 6033 const ObjCObjectType *RHS = Rptr->getObjectType(); 6034 const ObjCInterfaceDecl* LDecl = LHS->getInterface(); 6035 const ObjCInterfaceDecl* RDecl = RHS->getInterface(); 6036 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl))) 6037 return QualType(); 6038 6039 do { 6040 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl)); 6041 if (canAssignObjCInterfaces(LHS, RHS)) { 6042 SmallVector<ObjCProtocolDecl *, 8> Protocols; 6043 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols); 6044 6045 QualType Result = QualType(LHS, 0); 6046 if (!Protocols.empty()) 6047 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size()); 6048 Result = getObjCObjectPointerType(Result); 6049 return Result; 6050 } 6051 } while ((LDecl = LDecl->getSuperClass())); 6052 6053 return QualType(); 6054 } 6055 6056 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS, 6057 const ObjCObjectType *RHS) { 6058 assert(LHS->getInterface() && "LHS is not an interface type"); 6059 assert(RHS->getInterface() && "RHS is not an interface type"); 6060 6061 // Verify that the base decls are compatible: the RHS must be a subclass of 6062 // the LHS. 6063 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface())) 6064 return false; 6065 6066 // RHS must have a superset of the protocols in the LHS. If the LHS is not 6067 // protocol qualified at all, then we are good. 6068 if (LHS->getNumProtocols() == 0) 6069 return true; 6070 6071 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, 6072 // more detailed analysis is required. 6073 if (RHS->getNumProtocols() == 0) { 6074 // OK, if LHS is a superclass of RHS *and* 6075 // this superclass is assignment compatible with LHS. 6076 // false otherwise. 6077 bool IsSuperClass = 6078 LHS->getInterface()->isSuperClassOf(RHS->getInterface()); 6079 if (IsSuperClass) { 6080 // OK if conversion of LHS to SuperClass results in narrowing of types 6081 // ; i.e., SuperClass may implement at least one of the protocols 6082 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok. 6083 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>. 6084 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols; 6085 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols); 6086 // If super class has no protocols, it is not a match. 6087 if (SuperClassInheritedProtocols.empty()) 6088 return false; 6089 6090 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(), 6091 LHSPE = LHS->qual_end(); 6092 LHSPI != LHSPE; LHSPI++) { 6093 bool SuperImplementsProtocol = false; 6094 ObjCProtocolDecl *LHSProto = (*LHSPI); 6095 6096 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I = 6097 SuperClassInheritedProtocols.begin(), 6098 E = SuperClassInheritedProtocols.end(); I != E; ++I) { 6099 ObjCProtocolDecl *SuperClassProto = (*I); 6100 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) { 6101 SuperImplementsProtocol = true; 6102 break; 6103 } 6104 } 6105 if (!SuperImplementsProtocol) 6106 return false; 6107 } 6108 return true; 6109 } 6110 return false; 6111 } 6112 6113 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(), 6114 LHSPE = LHS->qual_end(); 6115 LHSPI != LHSPE; LHSPI++) { 6116 bool RHSImplementsProtocol = false; 6117 6118 // If the RHS doesn't implement the protocol on the left, the types 6119 // are incompatible. 6120 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(), 6121 RHSPE = RHS->qual_end(); 6122 RHSPI != RHSPE; RHSPI++) { 6123 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) { 6124 RHSImplementsProtocol = true; 6125 break; 6126 } 6127 } 6128 // FIXME: For better diagnostics, consider passing back the protocol name. 6129 if (!RHSImplementsProtocol) 6130 return false; 6131 } 6132 // The RHS implements all protocols listed on the LHS. 6133 return true; 6134 } 6135 6136 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) { 6137 // get the "pointed to" types 6138 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>(); 6139 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>(); 6140 6141 if (!LHSOPT || !RHSOPT) 6142 return false; 6143 6144 return canAssignObjCInterfaces(LHSOPT, RHSOPT) || 6145 canAssignObjCInterfaces(RHSOPT, LHSOPT); 6146 } 6147 6148 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) { 6149 return canAssignObjCInterfaces( 6150 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(), 6151 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>()); 6152 } 6153 6154 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible, 6155 /// both shall have the identically qualified version of a compatible type. 6156 /// C99 6.2.7p1: Two types have compatible types if their types are the 6157 /// same. See 6.7.[2,3,5] for additional rules. 6158 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS, 6159 bool CompareUnqualified) { 6160 if (getLangOpts().CPlusPlus) 6161 return hasSameType(LHS, RHS); 6162 6163 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull(); 6164 } 6165 6166 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) { 6167 return typesAreCompatible(LHS, RHS); 6168 } 6169 6170 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) { 6171 return !mergeTypes(LHS, RHS, true).isNull(); 6172 } 6173 6174 /// mergeTransparentUnionType - if T is a transparent union type and a member 6175 /// of T is compatible with SubType, return the merged type, else return 6176 /// QualType() 6177 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType, 6178 bool OfBlockPointer, 6179 bool Unqualified) { 6180 if (const RecordType *UT = T->getAsUnionType()) { 6181 RecordDecl *UD = UT->getDecl(); 6182 if (UD->hasAttr<TransparentUnionAttr>()) { 6183 for (RecordDecl::field_iterator it = UD->field_begin(), 6184 itend = UD->field_end(); it != itend; ++it) { 6185 QualType ET = it->getType().getUnqualifiedType(); 6186 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified); 6187 if (!MT.isNull()) 6188 return MT; 6189 } 6190 } 6191 } 6192 6193 return QualType(); 6194 } 6195 6196 /// mergeFunctionArgumentTypes - merge two types which appear as function 6197 /// argument types 6198 QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs, 6199 bool OfBlockPointer, 6200 bool Unqualified) { 6201 // GNU extension: two types are compatible if they appear as a function 6202 // argument, one of the types is a transparent union type and the other 6203 // type is compatible with a union member 6204 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer, 6205 Unqualified); 6206 if (!lmerge.isNull()) 6207 return lmerge; 6208 6209 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer, 6210 Unqualified); 6211 if (!rmerge.isNull()) 6212 return rmerge; 6213 6214 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified); 6215 } 6216 6217 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, 6218 bool OfBlockPointer, 6219 bool Unqualified) { 6220 const FunctionType *lbase = lhs->getAs<FunctionType>(); 6221 const FunctionType *rbase = rhs->getAs<FunctionType>(); 6222 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase); 6223 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase); 6224 bool allLTypes = true; 6225 bool allRTypes = true; 6226 6227 // Check return type 6228 QualType retType; 6229 if (OfBlockPointer) { 6230 QualType RHS = rbase->getResultType(); 6231 QualType LHS = lbase->getResultType(); 6232 bool UnqualifiedResult = Unqualified; 6233 if (!UnqualifiedResult) 6234 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers()); 6235 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true); 6236 } 6237 else 6238 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false, 6239 Unqualified); 6240 if (retType.isNull()) return QualType(); 6241 6242 if (Unqualified) 6243 retType = retType.getUnqualifiedType(); 6244 6245 CanQualType LRetType = getCanonicalType(lbase->getResultType()); 6246 CanQualType RRetType = getCanonicalType(rbase->getResultType()); 6247 if (Unqualified) { 6248 LRetType = LRetType.getUnqualifiedType(); 6249 RRetType = RRetType.getUnqualifiedType(); 6250 } 6251 6252 if (getCanonicalType(retType) != LRetType) 6253 allLTypes = false; 6254 if (getCanonicalType(retType) != RRetType) 6255 allRTypes = false; 6256 6257 // FIXME: double check this 6258 // FIXME: should we error if lbase->getRegParmAttr() != 0 && 6259 // rbase->getRegParmAttr() != 0 && 6260 // lbase->getRegParmAttr() != rbase->getRegParmAttr()? 6261 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo(); 6262 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo(); 6263 6264 // Compatible functions must have compatible calling conventions 6265 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC())) 6266 return QualType(); 6267 6268 // Regparm is part of the calling convention. 6269 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm()) 6270 return QualType(); 6271 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm()) 6272 return QualType(); 6273 6274 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult()) 6275 return QualType(); 6276 6277 // functypes which return are preferred over those that do not. 6278 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn()) 6279 allLTypes = false; 6280 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()) 6281 allRTypes = false; 6282 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'. 6283 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn(); 6284 6285 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn); 6286 6287 if (lproto && rproto) { // two C99 style function prototypes 6288 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() && 6289 "C++ shouldn't be here"); 6290 unsigned lproto_nargs = lproto->getNumArgs(); 6291 unsigned rproto_nargs = rproto->getNumArgs(); 6292 6293 // Compatible functions must have the same number of arguments 6294 if (lproto_nargs != rproto_nargs) 6295 return QualType(); 6296 6297 // Variadic and non-variadic functions aren't compatible 6298 if (lproto->isVariadic() != rproto->isVariadic()) 6299 return QualType(); 6300 6301 if (lproto->getTypeQuals() != rproto->getTypeQuals()) 6302 return QualType(); 6303 6304 if (LangOpts.ObjCAutoRefCount && 6305 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto)) 6306 return QualType(); 6307 6308 // Check argument compatibility 6309 SmallVector<QualType, 10> types; 6310 for (unsigned i = 0; i < lproto_nargs; i++) { 6311 QualType largtype = lproto->getArgType(i).getUnqualifiedType(); 6312 QualType rargtype = rproto->getArgType(i).getUnqualifiedType(); 6313 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype, 6314 OfBlockPointer, 6315 Unqualified); 6316 if (argtype.isNull()) return QualType(); 6317 6318 if (Unqualified) 6319 argtype = argtype.getUnqualifiedType(); 6320 6321 types.push_back(argtype); 6322 if (Unqualified) { 6323 largtype = largtype.getUnqualifiedType(); 6324 rargtype = rargtype.getUnqualifiedType(); 6325 } 6326 6327 if (getCanonicalType(argtype) != getCanonicalType(largtype)) 6328 allLTypes = false; 6329 if (getCanonicalType(argtype) != getCanonicalType(rargtype)) 6330 allRTypes = false; 6331 } 6332 6333 if (allLTypes) return lhs; 6334 if (allRTypes) return rhs; 6335 6336 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo(); 6337 EPI.ExtInfo = einfo; 6338 return getFunctionType(retType, types.begin(), types.size(), EPI); 6339 } 6340 6341 if (lproto) allRTypes = false; 6342 if (rproto) allLTypes = false; 6343 6344 const FunctionProtoType *proto = lproto ? lproto : rproto; 6345 if (proto) { 6346 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here"); 6347 if (proto->isVariadic()) return QualType(); 6348 // Check that the types are compatible with the types that 6349 // would result from default argument promotions (C99 6.7.5.3p15). 6350 // The only types actually affected are promotable integer 6351 // types and floats, which would be passed as a different 6352 // type depending on whether the prototype is visible. 6353 unsigned proto_nargs = proto->getNumArgs(); 6354 for (unsigned i = 0; i < proto_nargs; ++i) { 6355 QualType argTy = proto->getArgType(i); 6356 6357 // Look at the promotion type of enum types, since that is the type used 6358 // to pass enum values. 6359 if (const EnumType *Enum = argTy->getAs<EnumType>()) 6360 argTy = Enum->getDecl()->getPromotionType(); 6361 6362 if (argTy->isPromotableIntegerType() || 6363 getCanonicalType(argTy).getUnqualifiedType() == FloatTy) 6364 return QualType(); 6365 } 6366 6367 if (allLTypes) return lhs; 6368 if (allRTypes) return rhs; 6369 6370 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo(); 6371 EPI.ExtInfo = einfo; 6372 return getFunctionType(retType, proto->arg_type_begin(), 6373 proto->getNumArgs(), EPI); 6374 } 6375 6376 if (allLTypes) return lhs; 6377 if (allRTypes) return rhs; 6378 return getFunctionNoProtoType(retType, einfo); 6379 } 6380 6381 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, 6382 bool OfBlockPointer, 6383 bool Unqualified, bool BlockReturnType) { 6384 // C++ [expr]: If an expression initially has the type "reference to T", the 6385 // type is adjusted to "T" prior to any further analysis, the expression 6386 // designates the object or function denoted by the reference, and the 6387 // expression is an lvalue unless the reference is an rvalue reference and 6388 // the expression is a function call (possibly inside parentheses). 6389 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?"); 6390 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?"); 6391 6392 if (Unqualified) { 6393 LHS = LHS.getUnqualifiedType(); 6394 RHS = RHS.getUnqualifiedType(); 6395 } 6396 6397 QualType LHSCan = getCanonicalType(LHS), 6398 RHSCan = getCanonicalType(RHS); 6399 6400 // If two types are identical, they are compatible. 6401 if (LHSCan == RHSCan) 6402 return LHS; 6403 6404 // If the qualifiers are different, the types aren't compatible... mostly. 6405 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 6406 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 6407 if (LQuals != RQuals) { 6408 // If any of these qualifiers are different, we have a type 6409 // mismatch. 6410 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 6411 LQuals.getAddressSpace() != RQuals.getAddressSpace() || 6412 LQuals.getObjCLifetime() != RQuals.getObjCLifetime()) 6413 return QualType(); 6414 6415 // Exactly one GC qualifier difference is allowed: __strong is 6416 // okay if the other type has no GC qualifier but is an Objective 6417 // C object pointer (i.e. implicitly strong by default). We fix 6418 // this by pretending that the unqualified type was actually 6419 // qualified __strong. 6420 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 6421 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 6422 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 6423 6424 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 6425 return QualType(); 6426 6427 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) { 6428 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong)); 6429 } 6430 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) { 6431 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS); 6432 } 6433 return QualType(); 6434 } 6435 6436 // Okay, qualifiers are equal. 6437 6438 Type::TypeClass LHSClass = LHSCan->getTypeClass(); 6439 Type::TypeClass RHSClass = RHSCan->getTypeClass(); 6440 6441 // We want to consider the two function types to be the same for these 6442 // comparisons, just force one to the other. 6443 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto; 6444 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto; 6445 6446 // Same as above for arrays 6447 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray) 6448 LHSClass = Type::ConstantArray; 6449 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray) 6450 RHSClass = Type::ConstantArray; 6451 6452 // ObjCInterfaces are just specialized ObjCObjects. 6453 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject; 6454 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject; 6455 6456 // Canonicalize ExtVector -> Vector. 6457 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector; 6458 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector; 6459 6460 // If the canonical type classes don't match. 6461 if (LHSClass != RHSClass) { 6462 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char, 6463 // a signed integer type, or an unsigned integer type. 6464 // Compatibility is based on the underlying type, not the promotion 6465 // type. 6466 if (const EnumType* ETy = LHS->getAs<EnumType>()) { 6467 QualType TINT = ETy->getDecl()->getIntegerType(); 6468 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType())) 6469 return RHS; 6470 } 6471 if (const EnumType* ETy = RHS->getAs<EnumType>()) { 6472 QualType TINT = ETy->getDecl()->getIntegerType(); 6473 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType())) 6474 return LHS; 6475 } 6476 // allow block pointer type to match an 'id' type. 6477 if (OfBlockPointer && !BlockReturnType) { 6478 if (LHS->isObjCIdType() && RHS->isBlockPointerType()) 6479 return LHS; 6480 if (RHS->isObjCIdType() && LHS->isBlockPointerType()) 6481 return RHS; 6482 } 6483 6484 return QualType(); 6485 } 6486 6487 // The canonical type classes match. 6488 switch (LHSClass) { 6489 #define TYPE(Class, Base) 6490 #define ABSTRACT_TYPE(Class, Base) 6491 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 6492 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 6493 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 6494 #include "clang/AST/TypeNodes.def" 6495 llvm_unreachable("Non-canonical and dependent types shouldn't get here"); 6496 6497 case Type::LValueReference: 6498 case Type::RValueReference: 6499 case Type::MemberPointer: 6500 llvm_unreachable("C++ should never be in mergeTypes"); 6501 6502 case Type::ObjCInterface: 6503 case Type::IncompleteArray: 6504 case Type::VariableArray: 6505 case Type::FunctionProto: 6506 case Type::ExtVector: 6507 llvm_unreachable("Types are eliminated above"); 6508 6509 case Type::Pointer: 6510 { 6511 // Merge two pointer types, while trying to preserve typedef info 6512 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType(); 6513 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType(); 6514 if (Unqualified) { 6515 LHSPointee = LHSPointee.getUnqualifiedType(); 6516 RHSPointee = RHSPointee.getUnqualifiedType(); 6517 } 6518 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false, 6519 Unqualified); 6520 if (ResultType.isNull()) return QualType(); 6521 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 6522 return LHS; 6523 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 6524 return RHS; 6525 return getPointerType(ResultType); 6526 } 6527 case Type::BlockPointer: 6528 { 6529 // Merge two block pointer types, while trying to preserve typedef info 6530 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType(); 6531 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType(); 6532 if (Unqualified) { 6533 LHSPointee = LHSPointee.getUnqualifiedType(); 6534 RHSPointee = RHSPointee.getUnqualifiedType(); 6535 } 6536 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer, 6537 Unqualified); 6538 if (ResultType.isNull()) return QualType(); 6539 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 6540 return LHS; 6541 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 6542 return RHS; 6543 return getBlockPointerType(ResultType); 6544 } 6545 case Type::Atomic: 6546 { 6547 // Merge two pointer types, while trying to preserve typedef info 6548 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType(); 6549 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType(); 6550 if (Unqualified) { 6551 LHSValue = LHSValue.getUnqualifiedType(); 6552 RHSValue = RHSValue.getUnqualifiedType(); 6553 } 6554 QualType ResultType = mergeTypes(LHSValue, RHSValue, false, 6555 Unqualified); 6556 if (ResultType.isNull()) return QualType(); 6557 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType)) 6558 return LHS; 6559 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType)) 6560 return RHS; 6561 return getAtomicType(ResultType); 6562 } 6563 case Type::ConstantArray: 6564 { 6565 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS); 6566 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS); 6567 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize()) 6568 return QualType(); 6569 6570 QualType LHSElem = getAsArrayType(LHS)->getElementType(); 6571 QualType RHSElem = getAsArrayType(RHS)->getElementType(); 6572 if (Unqualified) { 6573 LHSElem = LHSElem.getUnqualifiedType(); 6574 RHSElem = RHSElem.getUnqualifiedType(); 6575 } 6576 6577 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified); 6578 if (ResultType.isNull()) return QualType(); 6579 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 6580 return LHS; 6581 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 6582 return RHS; 6583 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(), 6584 ArrayType::ArraySizeModifier(), 0); 6585 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(), 6586 ArrayType::ArraySizeModifier(), 0); 6587 const VariableArrayType* LVAT = getAsVariableArrayType(LHS); 6588 const VariableArrayType* RVAT = getAsVariableArrayType(RHS); 6589 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 6590 return LHS; 6591 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 6592 return RHS; 6593 if (LVAT) { 6594 // FIXME: This isn't correct! But tricky to implement because 6595 // the array's size has to be the size of LHS, but the type 6596 // has to be different. 6597 return LHS; 6598 } 6599 if (RVAT) { 6600 // FIXME: This isn't correct! But tricky to implement because 6601 // the array's size has to be the size of RHS, but the type 6602 // has to be different. 6603 return RHS; 6604 } 6605 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS; 6606 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS; 6607 return getIncompleteArrayType(ResultType, 6608 ArrayType::ArraySizeModifier(), 0); 6609 } 6610 case Type::FunctionNoProto: 6611 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified); 6612 case Type::Record: 6613 case Type::Enum: 6614 return QualType(); 6615 case Type::Builtin: 6616 // Only exactly equal builtin types are compatible, which is tested above. 6617 return QualType(); 6618 case Type::Complex: 6619 // Distinct complex types are incompatible. 6620 return QualType(); 6621 case Type::Vector: 6622 // FIXME: The merged type should be an ExtVector! 6623 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(), 6624 RHSCan->getAs<VectorType>())) 6625 return LHS; 6626 return QualType(); 6627 case Type::ObjCObject: { 6628 // Check if the types are assignment compatible. 6629 // FIXME: This should be type compatibility, e.g. whether 6630 // "LHS x; RHS x;" at global scope is legal. 6631 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>(); 6632 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>(); 6633 if (canAssignObjCInterfaces(LHSIface, RHSIface)) 6634 return LHS; 6635 6636 return QualType(); 6637 } 6638 case Type::ObjCObjectPointer: { 6639 if (OfBlockPointer) { 6640 if (canAssignObjCInterfacesInBlockPointer( 6641 LHS->getAs<ObjCObjectPointerType>(), 6642 RHS->getAs<ObjCObjectPointerType>(), 6643 BlockReturnType)) 6644 return LHS; 6645 return QualType(); 6646 } 6647 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(), 6648 RHS->getAs<ObjCObjectPointerType>())) 6649 return LHS; 6650 6651 return QualType(); 6652 } 6653 } 6654 6655 llvm_unreachable("Invalid Type::Class!"); 6656 } 6657 6658 bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs( 6659 const FunctionProtoType *FromFunctionType, 6660 const FunctionProtoType *ToFunctionType) { 6661 if (FromFunctionType->hasAnyConsumedArgs() != 6662 ToFunctionType->hasAnyConsumedArgs()) 6663 return false; 6664 FunctionProtoType::ExtProtoInfo FromEPI = 6665 FromFunctionType->getExtProtoInfo(); 6666 FunctionProtoType::ExtProtoInfo ToEPI = 6667 ToFunctionType->getExtProtoInfo(); 6668 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments) 6669 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 6670 ArgIdx != NumArgs; ++ArgIdx) { 6671 if (FromEPI.ConsumedArguments[ArgIdx] != 6672 ToEPI.ConsumedArguments[ArgIdx]) 6673 return false; 6674 } 6675 return true; 6676 } 6677 6678 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 6679 /// 'RHS' attributes and returns the merged version; including for function 6680 /// return types. 6681 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) { 6682 QualType LHSCan = getCanonicalType(LHS), 6683 RHSCan = getCanonicalType(RHS); 6684 // If two types are identical, they are compatible. 6685 if (LHSCan == RHSCan) 6686 return LHS; 6687 if (RHSCan->isFunctionType()) { 6688 if (!LHSCan->isFunctionType()) 6689 return QualType(); 6690 QualType OldReturnType = 6691 cast<FunctionType>(RHSCan.getTypePtr())->getResultType(); 6692 QualType NewReturnType = 6693 cast<FunctionType>(LHSCan.getTypePtr())->getResultType(); 6694 QualType ResReturnType = 6695 mergeObjCGCQualifiers(NewReturnType, OldReturnType); 6696 if (ResReturnType.isNull()) 6697 return QualType(); 6698 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) { 6699 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo(); 6700 // In either case, use OldReturnType to build the new function type. 6701 const FunctionType *F = LHS->getAs<FunctionType>(); 6702 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) { 6703 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 6704 EPI.ExtInfo = getFunctionExtInfo(LHS); 6705 QualType ResultType 6706 = getFunctionType(OldReturnType, FPT->arg_type_begin(), 6707 FPT->getNumArgs(), EPI); 6708 return ResultType; 6709 } 6710 } 6711 return QualType(); 6712 } 6713 6714 // If the qualifiers are different, the types can still be merged. 6715 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 6716 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 6717 if (LQuals != RQuals) { 6718 // If any of these qualifiers are different, we have a type mismatch. 6719 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 6720 LQuals.getAddressSpace() != RQuals.getAddressSpace()) 6721 return QualType(); 6722 6723 // Exactly one GC qualifier difference is allowed: __strong is 6724 // okay if the other type has no GC qualifier but is an Objective 6725 // C object pointer (i.e. implicitly strong by default). We fix 6726 // this by pretending that the unqualified type was actually 6727 // qualified __strong. 6728 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 6729 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 6730 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 6731 6732 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 6733 return QualType(); 6734 6735 if (GC_L == Qualifiers::Strong) 6736 return LHS; 6737 if (GC_R == Qualifiers::Strong) 6738 return RHS; 6739 return QualType(); 6740 } 6741 6742 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) { 6743 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType(); 6744 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType(); 6745 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT); 6746 if (ResQT == LHSBaseQT) 6747 return LHS; 6748 if (ResQT == RHSBaseQT) 6749 return RHS; 6750 } 6751 return QualType(); 6752 } 6753 6754 //===----------------------------------------------------------------------===// 6755 // Integer Predicates 6756 //===----------------------------------------------------------------------===// 6757 6758 unsigned ASTContext::getIntWidth(QualType T) const { 6759 if (const EnumType *ET = dyn_cast<EnumType>(T)) 6760 T = ET->getDecl()->getIntegerType(); 6761 if (T->isBooleanType()) 6762 return 1; 6763 // For builtin types, just use the standard type sizing method 6764 return (unsigned)getTypeSize(T); 6765 } 6766 6767 QualType ASTContext::getCorrespondingUnsignedType(QualType T) { 6768 assert(T->hasSignedIntegerRepresentation() && "Unexpected type"); 6769 6770 // Turn <4 x signed int> -> <4 x unsigned int> 6771 if (const VectorType *VTy = T->getAs<VectorType>()) 6772 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()), 6773 VTy->getNumElements(), VTy->getVectorKind()); 6774 6775 // For enums, we return the unsigned version of the base type. 6776 if (const EnumType *ETy = T->getAs<EnumType>()) 6777 T = ETy->getDecl()->getIntegerType(); 6778 6779 const BuiltinType *BTy = T->getAs<BuiltinType>(); 6780 assert(BTy && "Unexpected signed integer type"); 6781 switch (BTy->getKind()) { 6782 case BuiltinType::Char_S: 6783 case BuiltinType::SChar: 6784 return UnsignedCharTy; 6785 case BuiltinType::Short: 6786 return UnsignedShortTy; 6787 case BuiltinType::Int: 6788 return UnsignedIntTy; 6789 case BuiltinType::Long: 6790 return UnsignedLongTy; 6791 case BuiltinType::LongLong: 6792 return UnsignedLongLongTy; 6793 case BuiltinType::Int128: 6794 return UnsignedInt128Ty; 6795 default: 6796 llvm_unreachable("Unexpected signed integer type"); 6797 } 6798 } 6799 6800 ASTMutationListener::~ASTMutationListener() { } 6801 6802 6803 //===----------------------------------------------------------------------===// 6804 // Builtin Type Computation 6805 //===----------------------------------------------------------------------===// 6806 6807 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the 6808 /// pointer over the consumed characters. This returns the resultant type. If 6809 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic 6810 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of 6811 /// a vector of "i*". 6812 /// 6813 /// RequiresICE is filled in on return to indicate whether the value is required 6814 /// to be an Integer Constant Expression. 6815 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, 6816 ASTContext::GetBuiltinTypeError &Error, 6817 bool &RequiresICE, 6818 bool AllowTypeModifiers) { 6819 // Modifiers. 6820 int HowLong = 0; 6821 bool Signed = false, Unsigned = false; 6822 RequiresICE = false; 6823 6824 // Read the prefixed modifiers first. 6825 bool Done = false; 6826 while (!Done) { 6827 switch (*Str++) { 6828 default: Done = true; --Str; break; 6829 case 'I': 6830 RequiresICE = true; 6831 break; 6832 case 'S': 6833 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!"); 6834 assert(!Signed && "Can't use 'S' modifier multiple times!"); 6835 Signed = true; 6836 break; 6837 case 'U': 6838 assert(!Signed && "Can't use both 'S' and 'U' modifiers!"); 6839 assert(!Unsigned && "Can't use 'S' modifier multiple times!"); 6840 Unsigned = true; 6841 break; 6842 case 'L': 6843 assert(HowLong <= 2 && "Can't have LLLL modifier"); 6844 ++HowLong; 6845 break; 6846 } 6847 } 6848 6849 QualType Type; 6850 6851 // Read the base type. 6852 switch (*Str++) { 6853 default: llvm_unreachable("Unknown builtin type letter!"); 6854 case 'v': 6855 assert(HowLong == 0 && !Signed && !Unsigned && 6856 "Bad modifiers used with 'v'!"); 6857 Type = Context.VoidTy; 6858 break; 6859 case 'f': 6860 assert(HowLong == 0 && !Signed && !Unsigned && 6861 "Bad modifiers used with 'f'!"); 6862 Type = Context.FloatTy; 6863 break; 6864 case 'd': 6865 assert(HowLong < 2 && !Signed && !Unsigned && 6866 "Bad modifiers used with 'd'!"); 6867 if (HowLong) 6868 Type = Context.LongDoubleTy; 6869 else 6870 Type = Context.DoubleTy; 6871 break; 6872 case 's': 6873 assert(HowLong == 0 && "Bad modifiers used with 's'!"); 6874 if (Unsigned) 6875 Type = Context.UnsignedShortTy; 6876 else 6877 Type = Context.ShortTy; 6878 break; 6879 case 'i': 6880 if (HowLong == 3) 6881 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty; 6882 else if (HowLong == 2) 6883 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy; 6884 else if (HowLong == 1) 6885 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy; 6886 else 6887 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy; 6888 break; 6889 case 'c': 6890 assert(HowLong == 0 && "Bad modifiers used with 'c'!"); 6891 if (Signed) 6892 Type = Context.SignedCharTy; 6893 else if (Unsigned) 6894 Type = Context.UnsignedCharTy; 6895 else 6896 Type = Context.CharTy; 6897 break; 6898 case 'b': // boolean 6899 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!"); 6900 Type = Context.BoolTy; 6901 break; 6902 case 'z': // size_t. 6903 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!"); 6904 Type = Context.getSizeType(); 6905 break; 6906 case 'F': 6907 Type = Context.getCFConstantStringType(); 6908 break; 6909 case 'G': 6910 Type = Context.getObjCIdType(); 6911 break; 6912 case 'H': 6913 Type = Context.getObjCSelType(); 6914 break; 6915 case 'a': 6916 Type = Context.getBuiltinVaListType(); 6917 assert(!Type.isNull() && "builtin va list type not initialized!"); 6918 break; 6919 case 'A': 6920 // This is a "reference" to a va_list; however, what exactly 6921 // this means depends on how va_list is defined. There are two 6922 // different kinds of va_list: ones passed by value, and ones 6923 // passed by reference. An example of a by-value va_list is 6924 // x86, where va_list is a char*. An example of by-ref va_list 6925 // is x86-64, where va_list is a __va_list_tag[1]. For x86, 6926 // we want this argument to be a char*&; for x86-64, we want 6927 // it to be a __va_list_tag*. 6928 Type = Context.getBuiltinVaListType(); 6929 assert(!Type.isNull() && "builtin va list type not initialized!"); 6930 if (Type->isArrayType()) 6931 Type = Context.getArrayDecayedType(Type); 6932 else 6933 Type = Context.getLValueReferenceType(Type); 6934 break; 6935 case 'V': { 6936 char *End; 6937 unsigned NumElements = strtoul(Str, &End, 10); 6938 assert(End != Str && "Missing vector size"); 6939 Str = End; 6940 6941 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 6942 RequiresICE, false); 6943 assert(!RequiresICE && "Can't require vector ICE"); 6944 6945 // TODO: No way to make AltiVec vectors in builtins yet. 6946 Type = Context.getVectorType(ElementType, NumElements, 6947 VectorType::GenericVector); 6948 break; 6949 } 6950 case 'E': { 6951 char *End; 6952 6953 unsigned NumElements = strtoul(Str, &End, 10); 6954 assert(End != Str && "Missing vector size"); 6955 6956 Str = End; 6957 6958 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 6959 false); 6960 Type = Context.getExtVectorType(ElementType, NumElements); 6961 break; 6962 } 6963 case 'X': { 6964 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 6965 false); 6966 assert(!RequiresICE && "Can't require complex ICE"); 6967 Type = Context.getComplexType(ElementType); 6968 break; 6969 } 6970 case 'Y' : { 6971 Type = Context.getPointerDiffType(); 6972 break; 6973 } 6974 case 'P': 6975 Type = Context.getFILEType(); 6976 if (Type.isNull()) { 6977 Error = ASTContext::GE_Missing_stdio; 6978 return QualType(); 6979 } 6980 break; 6981 case 'J': 6982 if (Signed) 6983 Type = Context.getsigjmp_bufType(); 6984 else 6985 Type = Context.getjmp_bufType(); 6986 6987 if (Type.isNull()) { 6988 Error = ASTContext::GE_Missing_setjmp; 6989 return QualType(); 6990 } 6991 break; 6992 case 'K': 6993 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!"); 6994 Type = Context.getucontext_tType(); 6995 6996 if (Type.isNull()) { 6997 Error = ASTContext::GE_Missing_ucontext; 6998 return QualType(); 6999 } 7000 break; 7001 } 7002 7003 // If there are modifiers and if we're allowed to parse them, go for it. 7004 Done = !AllowTypeModifiers; 7005 while (!Done) { 7006 switch (char c = *Str++) { 7007 default: Done = true; --Str; break; 7008 case '*': 7009 case '&': { 7010 // Both pointers and references can have their pointee types 7011 // qualified with an address space. 7012 char *End; 7013 unsigned AddrSpace = strtoul(Str, &End, 10); 7014 if (End != Str && AddrSpace != 0) { 7015 Type = Context.getAddrSpaceQualType(Type, AddrSpace); 7016 Str = End; 7017 } 7018 if (c == '*') 7019 Type = Context.getPointerType(Type); 7020 else 7021 Type = Context.getLValueReferenceType(Type); 7022 break; 7023 } 7024 // FIXME: There's no way to have a built-in with an rvalue ref arg. 7025 case 'C': 7026 Type = Type.withConst(); 7027 break; 7028 case 'D': 7029 Type = Context.getVolatileType(Type); 7030 break; 7031 case 'R': 7032 Type = Type.withRestrict(); 7033 break; 7034 } 7035 } 7036 7037 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) && 7038 "Integer constant 'I' type must be an integer"); 7039 7040 return Type; 7041 } 7042 7043 /// GetBuiltinType - Return the type for the specified builtin. 7044 QualType ASTContext::GetBuiltinType(unsigned Id, 7045 GetBuiltinTypeError &Error, 7046 unsigned *IntegerConstantArgs) const { 7047 const char *TypeStr = BuiltinInfo.GetTypeString(Id); 7048 7049 SmallVector<QualType, 8> ArgTypes; 7050 7051 bool RequiresICE = false; 7052 Error = GE_None; 7053 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error, 7054 RequiresICE, true); 7055 if (Error != GE_None) 7056 return QualType(); 7057 7058 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE"); 7059 7060 while (TypeStr[0] && TypeStr[0] != '.') { 7061 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true); 7062 if (Error != GE_None) 7063 return QualType(); 7064 7065 // If this argument is required to be an IntegerConstantExpression and the 7066 // caller cares, fill in the bitmask we return. 7067 if (RequiresICE && IntegerConstantArgs) 7068 *IntegerConstantArgs |= 1 << ArgTypes.size(); 7069 7070 // Do array -> pointer decay. The builtin should use the decayed type. 7071 if (Ty->isArrayType()) 7072 Ty = getArrayDecayedType(Ty); 7073 7074 ArgTypes.push_back(Ty); 7075 } 7076 7077 assert((TypeStr[0] != '.' || TypeStr[1] == 0) && 7078 "'.' should only occur at end of builtin type list!"); 7079 7080 FunctionType::ExtInfo EI; 7081 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true); 7082 7083 bool Variadic = (TypeStr[0] == '.'); 7084 7085 // We really shouldn't be making a no-proto type here, especially in C++. 7086 if (ArgTypes.empty() && Variadic) 7087 return getFunctionNoProtoType(ResType, EI); 7088 7089 FunctionProtoType::ExtProtoInfo EPI; 7090 EPI.ExtInfo = EI; 7091 EPI.Variadic = Variadic; 7092 7093 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI); 7094 } 7095 7096 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) { 7097 GVALinkage External = GVA_StrongExternal; 7098 7099 Linkage L = FD->getLinkage(); 7100 switch (L) { 7101 case NoLinkage: 7102 case InternalLinkage: 7103 case UniqueExternalLinkage: 7104 return GVA_Internal; 7105 7106 case ExternalLinkage: 7107 switch (FD->getTemplateSpecializationKind()) { 7108 case TSK_Undeclared: 7109 case TSK_ExplicitSpecialization: 7110 External = GVA_StrongExternal; 7111 break; 7112 7113 case TSK_ExplicitInstantiationDefinition: 7114 return GVA_ExplicitTemplateInstantiation; 7115 7116 case TSK_ExplicitInstantiationDeclaration: 7117 case TSK_ImplicitInstantiation: 7118 External = GVA_TemplateInstantiation; 7119 break; 7120 } 7121 } 7122 7123 if (!FD->isInlined()) 7124 return External; 7125 7126 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) { 7127 // GNU or C99 inline semantics. Determine whether this symbol should be 7128 // externally visible. 7129 if (FD->isInlineDefinitionExternallyVisible()) 7130 return External; 7131 7132 // C99 inline semantics, where the symbol is not externally visible. 7133 return GVA_C99Inline; 7134 } 7135 7136 // C++0x [temp.explicit]p9: 7137 // [ Note: The intent is that an inline function that is the subject of 7138 // an explicit instantiation declaration will still be implicitly 7139 // instantiated when used so that the body can be considered for 7140 // inlining, but that no out-of-line copy of the inline function would be 7141 // generated in the translation unit. -- end note ] 7142 if (FD->getTemplateSpecializationKind() 7143 == TSK_ExplicitInstantiationDeclaration) 7144 return GVA_C99Inline; 7145 7146 return GVA_CXXInline; 7147 } 7148 7149 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) { 7150 // If this is a static data member, compute the kind of template 7151 // specialization. Otherwise, this variable is not part of a 7152 // template. 7153 TemplateSpecializationKind TSK = TSK_Undeclared; 7154 if (VD->isStaticDataMember()) 7155 TSK = VD->getTemplateSpecializationKind(); 7156 7157 Linkage L = VD->getLinkage(); 7158 if (L == ExternalLinkage && getLangOpts().CPlusPlus && 7159 VD->getType()->getLinkage() == UniqueExternalLinkage) 7160 L = UniqueExternalLinkage; 7161 7162 switch (L) { 7163 case NoLinkage: 7164 case InternalLinkage: 7165 case UniqueExternalLinkage: 7166 return GVA_Internal; 7167 7168 case ExternalLinkage: 7169 switch (TSK) { 7170 case TSK_Undeclared: 7171 case TSK_ExplicitSpecialization: 7172 return GVA_StrongExternal; 7173 7174 case TSK_ExplicitInstantiationDeclaration: 7175 llvm_unreachable("Variable should not be instantiated"); 7176 // Fall through to treat this like any other instantiation. 7177 7178 case TSK_ExplicitInstantiationDefinition: 7179 return GVA_ExplicitTemplateInstantiation; 7180 7181 case TSK_ImplicitInstantiation: 7182 return GVA_TemplateInstantiation; 7183 } 7184 } 7185 7186 llvm_unreachable("Invalid Linkage!"); 7187 } 7188 7189 bool ASTContext::DeclMustBeEmitted(const Decl *D) { 7190 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 7191 if (!VD->isFileVarDecl()) 7192 return false; 7193 } else if (!isa<FunctionDecl>(D)) 7194 return false; 7195 7196 // Weak references don't produce any output by themselves. 7197 if (D->hasAttr<WeakRefAttr>()) 7198 return false; 7199 7200 // Aliases and used decls are required. 7201 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>()) 7202 return true; 7203 7204 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 7205 // Forward declarations aren't required. 7206 if (!FD->doesThisDeclarationHaveABody()) 7207 return FD->doesDeclarationForceExternallyVisibleDefinition(); 7208 7209 // Constructors and destructors are required. 7210 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>()) 7211 return true; 7212 7213 // The key function for a class is required. 7214 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 7215 const CXXRecordDecl *RD = MD->getParent(); 7216 if (MD->isOutOfLine() && RD->isDynamicClass()) { 7217 const CXXMethodDecl *KeyFunc = getKeyFunction(RD); 7218 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl()) 7219 return true; 7220 } 7221 } 7222 7223 GVALinkage Linkage = GetGVALinkageForFunction(FD); 7224 7225 // static, static inline, always_inline, and extern inline functions can 7226 // always be deferred. Normal inline functions can be deferred in C99/C++. 7227 // Implicit template instantiations can also be deferred in C++. 7228 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline || 7229 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation) 7230 return false; 7231 return true; 7232 } 7233 7234 const VarDecl *VD = cast<VarDecl>(D); 7235 assert(VD->isFileVarDecl() && "Expected file scoped var"); 7236 7237 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) 7238 return false; 7239 7240 // Structs that have non-trivial constructors or destructors are required. 7241 7242 // FIXME: Handle references. 7243 // FIXME: Be more selective about which constructors we care about. 7244 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) { 7245 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 7246 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() && 7247 RD->hasTrivialCopyConstructor() && 7248 RD->hasTrivialMoveConstructor() && 7249 RD->hasTrivialDestructor())) 7250 return true; 7251 } 7252 } 7253 7254 GVALinkage L = GetGVALinkageForVariable(VD); 7255 if (L == GVA_Internal || L == GVA_TemplateInstantiation) { 7256 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this))) 7257 return false; 7258 } 7259 7260 return true; 7261 } 7262 7263 CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) { 7264 // Pass through to the C++ ABI object 7265 return ABI->getDefaultMethodCallConv(isVariadic); 7266 } 7267 7268 CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const { 7269 if (CC == CC_C && !LangOpts.MRTD && getTargetInfo().getCXXABI() != CXXABI_Microsoft) 7270 return CC_Default; 7271 return CC; 7272 } 7273 7274 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const { 7275 // Pass through to the C++ ABI object 7276 return ABI->isNearlyEmpty(RD); 7277 } 7278 7279 MangleContext *ASTContext::createMangleContext() { 7280 switch (Target->getCXXABI()) { 7281 case CXXABI_ARM: 7282 case CXXABI_Itanium: 7283 return createItaniumMangleContext(*this, getDiagnostics()); 7284 case CXXABI_Microsoft: 7285 return createMicrosoftMangleContext(*this, getDiagnostics()); 7286 } 7287 llvm_unreachable("Unsupported ABI"); 7288 } 7289 7290 CXXABI::~CXXABI() {} 7291 7292 size_t ASTContext::getSideTableAllocatedMemory() const { 7293 return ASTRecordLayouts.getMemorySize() 7294 + llvm::capacity_in_bytes(ObjCLayouts) 7295 + llvm::capacity_in_bytes(KeyFunctions) 7296 + llvm::capacity_in_bytes(ObjCImpls) 7297 + llvm::capacity_in_bytes(BlockVarCopyInits) 7298 + llvm::capacity_in_bytes(DeclAttrs) 7299 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember) 7300 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl) 7301 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) 7302 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) 7303 + llvm::capacity_in_bytes(OverriddenMethods) 7304 + llvm::capacity_in_bytes(Types) 7305 + llvm::capacity_in_bytes(VariableArrayTypes) 7306 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern); 7307 } 7308 7309 unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) { 7310 CXXRecordDecl *Lambda = CallOperator->getParent(); 7311 return LambdaMangleContexts[Lambda->getDeclContext()] 7312 .getManglingNumber(CallOperator); 7313 } 7314 7315 7316 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) { 7317 ParamIndices[D] = index; 7318 } 7319 7320 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const { 7321 ParameterIndexTable::const_iterator I = ParamIndices.find(D); 7322 assert(I != ParamIndices.end() && 7323 "ParmIndices lacks entry set by ParmVarDecl"); 7324 return I->second; 7325 } 7326