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