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