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