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