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