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