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