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