ASTContext.cpp revision 1a973447d0524b6dbb67605c33481687b24cd862
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} 710 711ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM, 712 const TargetInfo *t, 713 IdentifierTable &idents, SelectorTable &sels, 714 Builtin::Context &builtins, 715 unsigned size_reserve, 716 bool DelayInitialization) 717 : FunctionProtoTypes(this_()), 718 TemplateSpecializationTypes(this_()), 719 DependentTemplateSpecializationTypes(this_()), 720 SubstTemplateTemplateParmPacks(this_()), 721 GlobalNestedNameSpecifier(0), 722 Int128Decl(0), UInt128Decl(0), Float128StubDecl(0), 723 BuiltinVaListDecl(0), 724 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0), 725 BOOLDecl(0), 726 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0), 727 FILEDecl(0), 728 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0), 729 BlockDescriptorType(0), BlockDescriptorExtendedType(0), 730 cudaConfigureCallDecl(0), 731 NullTypeSourceInfo(QualType()), 732 FirstLocalImport(), LastLocalImport(), 733 SourceMgr(SM), LangOpts(LOpts), 734 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts), 735 Idents(idents), Selectors(sels), 736 BuiltinInfo(builtins), 737 DeclarationNames(*this), 738 ExternalSource(0), Listener(0), 739 Comments(SM), CommentsLoaded(false), 740 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), 741 LastSDM(0, 0) 742{ 743 if (size_reserve > 0) Types.reserve(size_reserve); 744 TUDecl = TranslationUnitDecl::Create(*this); 745 746 if (!DelayInitialization) { 747 assert(t && "No target supplied for ASTContext initialization"); 748 InitBuiltinTypes(*t); 749 } 750} 751 752ASTContext::~ASTContext() { 753 // Release the DenseMaps associated with DeclContext objects. 754 // FIXME: Is this the ideal solution? 755 ReleaseDeclContextMaps(); 756 757 // Call all of the deallocation functions on all of their targets. 758 for (DeallocationMap::const_iterator I = Deallocations.begin(), 759 E = Deallocations.end(); I != E; ++I) 760 for (unsigned J = 0, N = I->second.size(); J != N; ++J) 761 (I->first)((I->second)[J]); 762 763 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed 764 // because they can contain DenseMaps. 765 for (llvm::DenseMap<const ObjCContainerDecl*, 766 const ASTRecordLayout*>::iterator 767 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) 768 // Increment in loop to prevent using deallocated memory. 769 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second)) 770 R->Destroy(*this); 771 772 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator 773 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) { 774 // Increment in loop to prevent using deallocated memory. 775 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second)) 776 R->Destroy(*this); 777 } 778 779 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(), 780 AEnd = DeclAttrs.end(); 781 A != AEnd; ++A) 782 A->second->~AttrVec(); 783 784 for (llvm::DenseMap<const DeclContext *, MangleNumberingContext *>::iterator 785 I = MangleNumberingContexts.begin(), 786 E = MangleNumberingContexts.end(); 787 I != E; ++I) 788 delete I->second; 789} 790 791void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) { 792 Deallocations[Callback].push_back(Data); 793} 794 795void 796ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) { 797 ExternalSource.reset(Source.take()); 798} 799 800void ASTContext::PrintStats() const { 801 llvm::errs() << "\n*** AST Context Stats:\n"; 802 llvm::errs() << " " << Types.size() << " types total.\n"; 803 804 unsigned counts[] = { 805#define TYPE(Name, Parent) 0, 806#define ABSTRACT_TYPE(Name, Parent) 807#include "clang/AST/TypeNodes.def" 808 0 // Extra 809 }; 810 811 for (unsigned i = 0, e = Types.size(); i != e; ++i) { 812 Type *T = Types[i]; 813 counts[(unsigned)T->getTypeClass()]++; 814 } 815 816 unsigned Idx = 0; 817 unsigned TotalBytes = 0; 818#define TYPE(Name, Parent) \ 819 if (counts[Idx]) \ 820 llvm::errs() << " " << counts[Idx] << " " << #Name \ 821 << " types\n"; \ 822 TotalBytes += counts[Idx] * sizeof(Name##Type); \ 823 ++Idx; 824#define ABSTRACT_TYPE(Name, Parent) 825#include "clang/AST/TypeNodes.def" 826 827 llvm::errs() << "Total bytes = " << TotalBytes << "\n"; 828 829 // Implicit special member functions. 830 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/" 831 << NumImplicitDefaultConstructors 832 << " implicit default constructors created\n"; 833 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/" 834 << NumImplicitCopyConstructors 835 << " implicit copy constructors created\n"; 836 if (getLangOpts().CPlusPlus) 837 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/" 838 << NumImplicitMoveConstructors 839 << " implicit move constructors created\n"; 840 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/" 841 << NumImplicitCopyAssignmentOperators 842 << " implicit copy assignment operators created\n"; 843 if (getLangOpts().CPlusPlus) 844 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/" 845 << NumImplicitMoveAssignmentOperators 846 << " implicit move assignment operators created\n"; 847 llvm::errs() << NumImplicitDestructorsDeclared << "/" 848 << NumImplicitDestructors 849 << " implicit destructors created\n"; 850 851 if (ExternalSource.get()) { 852 llvm::errs() << "\n"; 853 ExternalSource->PrintStats(); 854 } 855 856 BumpAlloc.PrintStats(); 857} 858 859TypedefDecl *ASTContext::getInt128Decl() const { 860 if (!Int128Decl) { 861 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty); 862 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this), 863 getTranslationUnitDecl(), 864 SourceLocation(), 865 SourceLocation(), 866 &Idents.get("__int128_t"), 867 TInfo); 868 } 869 870 return Int128Decl; 871} 872 873TypedefDecl *ASTContext::getUInt128Decl() const { 874 if (!UInt128Decl) { 875 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty); 876 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this), 877 getTranslationUnitDecl(), 878 SourceLocation(), 879 SourceLocation(), 880 &Idents.get("__uint128_t"), 881 TInfo); 882 } 883 884 return UInt128Decl; 885} 886 887TypeDecl *ASTContext::getFloat128StubType() const { 888 assert(LangOpts.CPlusPlus && "should only be called for c++"); 889 if (!Float128StubDecl) { 890 Float128StubDecl = CXXRecordDecl::Create(const_cast<ASTContext &>(*this), 891 TTK_Struct, 892 getTranslationUnitDecl(), 893 SourceLocation(), 894 SourceLocation(), 895 &Idents.get("__float128")); 896 } 897 898 return Float128StubDecl; 899} 900 901void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) { 902 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K); 903 R = CanQualType::CreateUnsafe(QualType(Ty, 0)); 904 Types.push_back(Ty); 905} 906 907void ASTContext::InitBuiltinTypes(const TargetInfo &Target) { 908 assert((!this->Target || this->Target == &Target) && 909 "Incorrect target reinitialization"); 910 assert(VoidTy.isNull() && "Context reinitialized?"); 911 912 this->Target = &Target; 913 914 ABI.reset(createCXXABI(Target)); 915 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts); 916 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts); 917 918 // C99 6.2.5p19. 919 InitBuiltinType(VoidTy, BuiltinType::Void); 920 921 // C99 6.2.5p2. 922 InitBuiltinType(BoolTy, BuiltinType::Bool); 923 // C99 6.2.5p3. 924 if (LangOpts.CharIsSigned) 925 InitBuiltinType(CharTy, BuiltinType::Char_S); 926 else 927 InitBuiltinType(CharTy, BuiltinType::Char_U); 928 // C99 6.2.5p4. 929 InitBuiltinType(SignedCharTy, BuiltinType::SChar); 930 InitBuiltinType(ShortTy, BuiltinType::Short); 931 InitBuiltinType(IntTy, BuiltinType::Int); 932 InitBuiltinType(LongTy, BuiltinType::Long); 933 InitBuiltinType(LongLongTy, BuiltinType::LongLong); 934 935 // C99 6.2.5p6. 936 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar); 937 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort); 938 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt); 939 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong); 940 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong); 941 942 // C99 6.2.5p10. 943 InitBuiltinType(FloatTy, BuiltinType::Float); 944 InitBuiltinType(DoubleTy, BuiltinType::Double); 945 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble); 946 947 // GNU extension, 128-bit integers. 948 InitBuiltinType(Int128Ty, BuiltinType::Int128); 949 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128); 950 951 // C++ 3.9.1p5 952 if (TargetInfo::isTypeSigned(Target.getWCharType())) 953 InitBuiltinType(WCharTy, BuiltinType::WChar_S); 954 else // -fshort-wchar makes wchar_t be unsigned. 955 InitBuiltinType(WCharTy, BuiltinType::WChar_U); 956 if (LangOpts.CPlusPlus && LangOpts.WChar) 957 WideCharTy = WCharTy; 958 else { 959 // C99 (or C++ using -fno-wchar). 960 WideCharTy = getFromTargetType(Target.getWCharType()); 961 } 962 963 WIntTy = getFromTargetType(Target.getWIntType()); 964 965 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 966 InitBuiltinType(Char16Ty, BuiltinType::Char16); 967 else // C99 968 Char16Ty = getFromTargetType(Target.getChar16Type()); 969 970 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 971 InitBuiltinType(Char32Ty, BuiltinType::Char32); 972 else // C99 973 Char32Ty = getFromTargetType(Target.getChar32Type()); 974 975 // Placeholder type for type-dependent expressions whose type is 976 // completely unknown. No code should ever check a type against 977 // DependentTy and users should never see it; however, it is here to 978 // help diagnose failures to properly check for type-dependent 979 // expressions. 980 InitBuiltinType(DependentTy, BuiltinType::Dependent); 981 982 // Placeholder type for functions. 983 InitBuiltinType(OverloadTy, BuiltinType::Overload); 984 985 // Placeholder type for bound members. 986 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember); 987 988 // Placeholder type for pseudo-objects. 989 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject); 990 991 // "any" type; useful for debugger-like clients. 992 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny); 993 994 // Placeholder type for unbridged ARC casts. 995 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast); 996 997 // Placeholder type for builtin functions. 998 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn); 999 1000 // C99 6.2.5p11. 1001 FloatComplexTy = getComplexType(FloatTy); 1002 DoubleComplexTy = getComplexType(DoubleTy); 1003 LongDoubleComplexTy = getComplexType(LongDoubleTy); 1004 1005 // Builtin types for 'id', 'Class', and 'SEL'. 1006 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId); 1007 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass); 1008 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel); 1009 1010 if (LangOpts.OpenCL) { 1011 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d); 1012 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray); 1013 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer); 1014 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d); 1015 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray); 1016 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d); 1017 1018 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler); 1019 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent); 1020 } 1021 1022 // Builtin type for __objc_yes and __objc_no 1023 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ? 1024 SignedCharTy : BoolTy); 1025 1026 ObjCConstantStringType = QualType(); 1027 1028 ObjCSuperType = QualType(); 1029 1030 // void * type 1031 VoidPtrTy = getPointerType(VoidTy); 1032 1033 // nullptr type (C++0x 2.14.7) 1034 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr); 1035 1036 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16 1037 InitBuiltinType(HalfTy, BuiltinType::Half); 1038 1039 // Builtin type used to help define __builtin_va_list. 1040 VaListTagTy = QualType(); 1041} 1042 1043DiagnosticsEngine &ASTContext::getDiagnostics() const { 1044 return SourceMgr.getDiagnostics(); 1045} 1046 1047AttrVec& ASTContext::getDeclAttrs(const Decl *D) { 1048 AttrVec *&Result = DeclAttrs[D]; 1049 if (!Result) { 1050 void *Mem = Allocate(sizeof(AttrVec)); 1051 Result = new (Mem) AttrVec; 1052 } 1053 1054 return *Result; 1055} 1056 1057/// \brief Erase the attributes corresponding to the given declaration. 1058void ASTContext::eraseDeclAttrs(const Decl *D) { 1059 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D); 1060 if (Pos != DeclAttrs.end()) { 1061 Pos->second->~AttrVec(); 1062 DeclAttrs.erase(Pos); 1063 } 1064} 1065 1066// FIXME: Remove ? 1067MemberSpecializationInfo * 1068ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) { 1069 assert(Var->isStaticDataMember() && "Not a static data member"); 1070 return getTemplateOrSpecializationInfo(Var) 1071 .dyn_cast<MemberSpecializationInfo *>(); 1072} 1073 1074ASTContext::TemplateOrSpecializationInfo 1075ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) { 1076 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos = 1077 TemplateOrInstantiation.find(Var); 1078 if (Pos == TemplateOrInstantiation.end()) 1079 return TemplateOrSpecializationInfo(); 1080 1081 return Pos->second; 1082} 1083 1084void 1085ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, 1086 TemplateSpecializationKind TSK, 1087 SourceLocation PointOfInstantiation) { 1088 assert(Inst->isStaticDataMember() && "Not a static data member"); 1089 assert(Tmpl->isStaticDataMember() && "Not a static data member"); 1090 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo( 1091 Tmpl, TSK, PointOfInstantiation)); 1092} 1093 1094void 1095ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst, 1096 TemplateOrSpecializationInfo TSI) { 1097 assert(!TemplateOrInstantiation[Inst] && 1098 "Already noted what the variable was instantiated from"); 1099 TemplateOrInstantiation[Inst] = TSI; 1100} 1101 1102FunctionDecl *ASTContext::getClassScopeSpecializationPattern( 1103 const FunctionDecl *FD){ 1104 assert(FD && "Specialization is 0"); 1105 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos 1106 = ClassScopeSpecializationPattern.find(FD); 1107 if (Pos == ClassScopeSpecializationPattern.end()) 1108 return 0; 1109 1110 return Pos->second; 1111} 1112 1113void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD, 1114 FunctionDecl *Pattern) { 1115 assert(FD && "Specialization is 0"); 1116 assert(Pattern && "Class scope specialization pattern is 0"); 1117 ClassScopeSpecializationPattern[FD] = Pattern; 1118} 1119 1120NamedDecl * 1121ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) { 1122 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos 1123 = InstantiatedFromUsingDecl.find(UUD); 1124 if (Pos == InstantiatedFromUsingDecl.end()) 1125 return 0; 1126 1127 return Pos->second; 1128} 1129 1130void 1131ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) { 1132 assert((isa<UsingDecl>(Pattern) || 1133 isa<UnresolvedUsingValueDecl>(Pattern) || 1134 isa<UnresolvedUsingTypenameDecl>(Pattern)) && 1135 "pattern decl is not a using decl"); 1136 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists"); 1137 InstantiatedFromUsingDecl[Inst] = Pattern; 1138} 1139 1140UsingShadowDecl * 1141ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) { 1142 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos 1143 = InstantiatedFromUsingShadowDecl.find(Inst); 1144 if (Pos == InstantiatedFromUsingShadowDecl.end()) 1145 return 0; 1146 1147 return Pos->second; 1148} 1149 1150void 1151ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, 1152 UsingShadowDecl *Pattern) { 1153 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists"); 1154 InstantiatedFromUsingShadowDecl[Inst] = Pattern; 1155} 1156 1157FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) { 1158 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos 1159 = InstantiatedFromUnnamedFieldDecl.find(Field); 1160 if (Pos == InstantiatedFromUnnamedFieldDecl.end()) 1161 return 0; 1162 1163 return Pos->second; 1164} 1165 1166void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, 1167 FieldDecl *Tmpl) { 1168 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed"); 1169 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed"); 1170 assert(!InstantiatedFromUnnamedFieldDecl[Inst] && 1171 "Already noted what unnamed field was instantiated from"); 1172 1173 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl; 1174} 1175 1176ASTContext::overridden_cxx_method_iterator 1177ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const { 1178 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos 1179 = OverriddenMethods.find(Method->getCanonicalDecl()); 1180 if (Pos == OverriddenMethods.end()) 1181 return 0; 1182 1183 return Pos->second.begin(); 1184} 1185 1186ASTContext::overridden_cxx_method_iterator 1187ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const { 1188 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos 1189 = OverriddenMethods.find(Method->getCanonicalDecl()); 1190 if (Pos == OverriddenMethods.end()) 1191 return 0; 1192 1193 return Pos->second.end(); 1194} 1195 1196unsigned 1197ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const { 1198 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos 1199 = OverriddenMethods.find(Method->getCanonicalDecl()); 1200 if (Pos == OverriddenMethods.end()) 1201 return 0; 1202 1203 return Pos->second.size(); 1204} 1205 1206void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method, 1207 const CXXMethodDecl *Overridden) { 1208 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl()); 1209 OverriddenMethods[Method].push_back(Overridden); 1210} 1211 1212void ASTContext::getOverriddenMethods( 1213 const NamedDecl *D, 1214 SmallVectorImpl<const NamedDecl *> &Overridden) const { 1215 assert(D); 1216 1217 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) { 1218 Overridden.append(overridden_methods_begin(CXXMethod), 1219 overridden_methods_end(CXXMethod)); 1220 return; 1221 } 1222 1223 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D); 1224 if (!Method) 1225 return; 1226 1227 SmallVector<const ObjCMethodDecl *, 8> OverDecls; 1228 Method->getOverriddenMethods(OverDecls); 1229 Overridden.append(OverDecls.begin(), OverDecls.end()); 1230} 1231 1232void ASTContext::addedLocalImportDecl(ImportDecl *Import) { 1233 assert(!Import->NextLocalImport && "Import declaration already in the chain"); 1234 assert(!Import->isFromASTFile() && "Non-local import declaration"); 1235 if (!FirstLocalImport) { 1236 FirstLocalImport = Import; 1237 LastLocalImport = Import; 1238 return; 1239 } 1240 1241 LastLocalImport->NextLocalImport = Import; 1242 LastLocalImport = Import; 1243} 1244 1245//===----------------------------------------------------------------------===// 1246// Type Sizing and Analysis 1247//===----------------------------------------------------------------------===// 1248 1249/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified 1250/// scalar floating point type. 1251const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const { 1252 const BuiltinType *BT = T->getAs<BuiltinType>(); 1253 assert(BT && "Not a floating point type!"); 1254 switch (BT->getKind()) { 1255 default: llvm_unreachable("Not a floating point type!"); 1256 case BuiltinType::Half: return Target->getHalfFormat(); 1257 case BuiltinType::Float: return Target->getFloatFormat(); 1258 case BuiltinType::Double: return Target->getDoubleFormat(); 1259 case BuiltinType::LongDouble: return Target->getLongDoubleFormat(); 1260 } 1261} 1262 1263CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const { 1264 unsigned Align = Target->getCharWidth(); 1265 1266 bool UseAlignAttrOnly = false; 1267 if (unsigned AlignFromAttr = D->getMaxAlignment()) { 1268 Align = AlignFromAttr; 1269 1270 // __attribute__((aligned)) can increase or decrease alignment 1271 // *except* on a struct or struct member, where it only increases 1272 // alignment unless 'packed' is also specified. 1273 // 1274 // It is an error for alignas to decrease alignment, so we can 1275 // ignore that possibility; Sema should diagnose it. 1276 if (isa<FieldDecl>(D)) { 1277 UseAlignAttrOnly = D->hasAttr<PackedAttr>() || 1278 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 1279 } else { 1280 UseAlignAttrOnly = true; 1281 } 1282 } 1283 else if (isa<FieldDecl>(D)) 1284 UseAlignAttrOnly = 1285 D->hasAttr<PackedAttr>() || 1286 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 1287 1288 // If we're using the align attribute only, just ignore everything 1289 // else about the declaration and its type. 1290 if (UseAlignAttrOnly) { 1291 // do nothing 1292 1293 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 1294 QualType T = VD->getType(); 1295 if (const ReferenceType* RT = T->getAs<ReferenceType>()) { 1296 if (ForAlignof) 1297 T = RT->getPointeeType(); 1298 else 1299 T = getPointerType(RT->getPointeeType()); 1300 } 1301 if (!T->isIncompleteType() && !T->isFunctionType()) { 1302 // Adjust alignments of declarations with array type by the 1303 // large-array alignment on the target. 1304 if (const ArrayType *arrayType = getAsArrayType(T)) { 1305 unsigned MinWidth = Target->getLargeArrayMinWidth(); 1306 if (!ForAlignof && MinWidth) { 1307 if (isa<VariableArrayType>(arrayType)) 1308 Align = std::max(Align, Target->getLargeArrayAlign()); 1309 else if (isa<ConstantArrayType>(arrayType) && 1310 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType))) 1311 Align = std::max(Align, Target->getLargeArrayAlign()); 1312 } 1313 1314 // Walk through any array types while we're at it. 1315 T = getBaseElementType(arrayType); 1316 } 1317 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr())); 1318 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1319 if (VD->hasGlobalStorage()) 1320 Align = std::max(Align, getTargetInfo().getMinGlobalAlign()); 1321 } 1322 } 1323 1324 // Fields can be subject to extra alignment constraints, like if 1325 // the field is packed, the struct is packed, or the struct has a 1326 // a max-field-alignment constraint (#pragma pack). So calculate 1327 // the actual alignment of the field within the struct, and then 1328 // (as we're expected to) constrain that by the alignment of the type. 1329 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 1330 const RecordDecl *Parent = Field->getParent(); 1331 // We can only produce a sensible answer if the record is valid. 1332 if (!Parent->isInvalidDecl()) { 1333 const ASTRecordLayout &Layout = getASTRecordLayout(Parent); 1334 1335 // Start with the record's overall alignment. 1336 unsigned FieldAlign = toBits(Layout.getAlignment()); 1337 1338 // Use the GCD of that and the offset within the record. 1339 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex()); 1340 if (Offset > 0) { 1341 // Alignment is always a power of 2, so the GCD will be a power of 2, 1342 // which means we get to do this crazy thing instead of Euclid's. 1343 uint64_t LowBitOfOffset = Offset & (~Offset + 1); 1344 if (LowBitOfOffset < FieldAlign) 1345 FieldAlign = static_cast<unsigned>(LowBitOfOffset); 1346 } 1347 1348 Align = std::min(Align, FieldAlign); 1349 } 1350 } 1351 } 1352 1353 return toCharUnitsFromBits(Align); 1354} 1355 1356// getTypeInfoDataSizeInChars - Return the size of a type, in 1357// chars. If the type is a record, its data size is returned. This is 1358// the size of the memcpy that's performed when assigning this type 1359// using a trivial copy/move assignment operator. 1360std::pair<CharUnits, CharUnits> 1361ASTContext::getTypeInfoDataSizeInChars(QualType T) const { 1362 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T); 1363 1364 // In C++, objects can sometimes be allocated into the tail padding 1365 // of a base-class subobject. We decide whether that's possible 1366 // during class layout, so here we can just trust the layout results. 1367 if (getLangOpts().CPlusPlus) { 1368 if (const RecordType *RT = T->getAs<RecordType>()) { 1369 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl()); 1370 sizeAndAlign.first = layout.getDataSize(); 1371 } 1372 } 1373 1374 return sizeAndAlign; 1375} 1376 1377/// getConstantArrayInfoInChars - Performing the computation in CharUnits 1378/// instead of in bits prevents overflowing the uint64_t for some large arrays. 1379std::pair<CharUnits, CharUnits> 1380static getConstantArrayInfoInChars(const ASTContext &Context, 1381 const ConstantArrayType *CAT) { 1382 std::pair<CharUnits, CharUnits> EltInfo = 1383 Context.getTypeInfoInChars(CAT->getElementType()); 1384 uint64_t Size = CAT->getSize().getZExtValue(); 1385 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <= 1386 (uint64_t)(-1)/Size) && 1387 "Overflow in array type char size evaluation"); 1388 uint64_t Width = EltInfo.first.getQuantity() * Size; 1389 unsigned Align = EltInfo.second.getQuantity(); 1390 Width = llvm::RoundUpToAlignment(Width, Align); 1391 return std::make_pair(CharUnits::fromQuantity(Width), 1392 CharUnits::fromQuantity(Align)); 1393} 1394 1395std::pair<CharUnits, CharUnits> 1396ASTContext::getTypeInfoInChars(const Type *T) const { 1397 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T)) 1398 return getConstantArrayInfoInChars(*this, CAT); 1399 std::pair<uint64_t, unsigned> Info = getTypeInfo(T); 1400 return std::make_pair(toCharUnitsFromBits(Info.first), 1401 toCharUnitsFromBits(Info.second)); 1402} 1403 1404std::pair<CharUnits, CharUnits> 1405ASTContext::getTypeInfoInChars(QualType T) const { 1406 return getTypeInfoInChars(T.getTypePtr()); 1407} 1408 1409std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const { 1410 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T); 1411 if (it != MemoizedTypeInfo.end()) 1412 return it->second; 1413 1414 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T); 1415 MemoizedTypeInfo.insert(std::make_pair(T, Info)); 1416 return Info; 1417} 1418 1419/// getTypeInfoImpl - Return the size of the specified type, in bits. This 1420/// method does not work on incomplete types. 1421/// 1422/// FIXME: Pointers into different addr spaces could have different sizes and 1423/// alignment requirements: getPointerInfo should take an AddrSpace, this 1424/// should take a QualType, &c. 1425std::pair<uint64_t, unsigned> 1426ASTContext::getTypeInfoImpl(const Type *T) const { 1427 uint64_t Width=0; 1428 unsigned Align=8; 1429 switch (T->getTypeClass()) { 1430#define TYPE(Class, Base) 1431#define ABSTRACT_TYPE(Class, Base) 1432#define NON_CANONICAL_TYPE(Class, Base) 1433#define DEPENDENT_TYPE(Class, Base) case Type::Class: 1434#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \ 1435 case Type::Class: \ 1436 assert(!T->isDependentType() && "should not see dependent types here"); \ 1437 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr()); 1438#include "clang/AST/TypeNodes.def" 1439 llvm_unreachable("Should not see dependent types"); 1440 1441 case Type::FunctionNoProto: 1442 case Type::FunctionProto: 1443 // GCC extension: alignof(function) = 32 bits 1444 Width = 0; 1445 Align = 32; 1446 break; 1447 1448 case Type::IncompleteArray: 1449 case Type::VariableArray: 1450 Width = 0; 1451 Align = getTypeAlign(cast<ArrayType>(T)->getElementType()); 1452 break; 1453 1454 case Type::ConstantArray: { 1455 const ConstantArrayType *CAT = cast<ConstantArrayType>(T); 1456 1457 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType()); 1458 uint64_t Size = CAT->getSize().getZExtValue(); 1459 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) && 1460 "Overflow in array type bit size evaluation"); 1461 Width = EltInfo.first*Size; 1462 Align = EltInfo.second; 1463 Width = llvm::RoundUpToAlignment(Width, Align); 1464 break; 1465 } 1466 case Type::ExtVector: 1467 case Type::Vector: { 1468 const VectorType *VT = cast<VectorType>(T); 1469 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType()); 1470 Width = EltInfo.first*VT->getNumElements(); 1471 Align = Width; 1472 // If the alignment is not a power of 2, round up to the next power of 2. 1473 // This happens for non-power-of-2 length vectors. 1474 if (Align & (Align-1)) { 1475 Align = llvm::NextPowerOf2(Align); 1476 Width = llvm::RoundUpToAlignment(Width, Align); 1477 } 1478 // Adjust the alignment based on the target max. 1479 uint64_t TargetVectorAlign = Target->getMaxVectorAlign(); 1480 if (TargetVectorAlign && TargetVectorAlign < Align) 1481 Align = TargetVectorAlign; 1482 break; 1483 } 1484 1485 case Type::Builtin: 1486 switch (cast<BuiltinType>(T)->getKind()) { 1487 default: llvm_unreachable("Unknown builtin type!"); 1488 case BuiltinType::Void: 1489 // GCC extension: alignof(void) = 8 bits. 1490 Width = 0; 1491 Align = 8; 1492 break; 1493 1494 case BuiltinType::Bool: 1495 Width = Target->getBoolWidth(); 1496 Align = Target->getBoolAlign(); 1497 break; 1498 case BuiltinType::Char_S: 1499 case BuiltinType::Char_U: 1500 case BuiltinType::UChar: 1501 case BuiltinType::SChar: 1502 Width = Target->getCharWidth(); 1503 Align = Target->getCharAlign(); 1504 break; 1505 case BuiltinType::WChar_S: 1506 case BuiltinType::WChar_U: 1507 Width = Target->getWCharWidth(); 1508 Align = Target->getWCharAlign(); 1509 break; 1510 case BuiltinType::Char16: 1511 Width = Target->getChar16Width(); 1512 Align = Target->getChar16Align(); 1513 break; 1514 case BuiltinType::Char32: 1515 Width = Target->getChar32Width(); 1516 Align = Target->getChar32Align(); 1517 break; 1518 case BuiltinType::UShort: 1519 case BuiltinType::Short: 1520 Width = Target->getShortWidth(); 1521 Align = Target->getShortAlign(); 1522 break; 1523 case BuiltinType::UInt: 1524 case BuiltinType::Int: 1525 Width = Target->getIntWidth(); 1526 Align = Target->getIntAlign(); 1527 break; 1528 case BuiltinType::ULong: 1529 case BuiltinType::Long: 1530 Width = Target->getLongWidth(); 1531 Align = Target->getLongAlign(); 1532 break; 1533 case BuiltinType::ULongLong: 1534 case BuiltinType::LongLong: 1535 Width = Target->getLongLongWidth(); 1536 Align = Target->getLongLongAlign(); 1537 break; 1538 case BuiltinType::Int128: 1539 case BuiltinType::UInt128: 1540 Width = 128; 1541 Align = 128; // int128_t is 128-bit aligned on all targets. 1542 break; 1543 case BuiltinType::Half: 1544 Width = Target->getHalfWidth(); 1545 Align = Target->getHalfAlign(); 1546 break; 1547 case BuiltinType::Float: 1548 Width = Target->getFloatWidth(); 1549 Align = Target->getFloatAlign(); 1550 break; 1551 case BuiltinType::Double: 1552 Width = Target->getDoubleWidth(); 1553 Align = Target->getDoubleAlign(); 1554 break; 1555 case BuiltinType::LongDouble: 1556 Width = Target->getLongDoubleWidth(); 1557 Align = Target->getLongDoubleAlign(); 1558 break; 1559 case BuiltinType::NullPtr: 1560 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t) 1561 Align = Target->getPointerAlign(0); // == sizeof(void*) 1562 break; 1563 case BuiltinType::ObjCId: 1564 case BuiltinType::ObjCClass: 1565 case BuiltinType::ObjCSel: 1566 Width = Target->getPointerWidth(0); 1567 Align = Target->getPointerAlign(0); 1568 break; 1569 case BuiltinType::OCLSampler: 1570 // Samplers are modeled as integers. 1571 Width = Target->getIntWidth(); 1572 Align = Target->getIntAlign(); 1573 break; 1574 case BuiltinType::OCLEvent: 1575 case BuiltinType::OCLImage1d: 1576 case BuiltinType::OCLImage1dArray: 1577 case BuiltinType::OCLImage1dBuffer: 1578 case BuiltinType::OCLImage2d: 1579 case BuiltinType::OCLImage2dArray: 1580 case BuiltinType::OCLImage3d: 1581 // Currently these types are pointers to opaque types. 1582 Width = Target->getPointerWidth(0); 1583 Align = Target->getPointerAlign(0); 1584 break; 1585 } 1586 break; 1587 case Type::ObjCObjectPointer: 1588 Width = Target->getPointerWidth(0); 1589 Align = Target->getPointerAlign(0); 1590 break; 1591 case Type::BlockPointer: { 1592 unsigned AS = getTargetAddressSpace( 1593 cast<BlockPointerType>(T)->getPointeeType()); 1594 Width = Target->getPointerWidth(AS); 1595 Align = Target->getPointerAlign(AS); 1596 break; 1597 } 1598 case Type::LValueReference: 1599 case Type::RValueReference: { 1600 // alignof and sizeof should never enter this code path here, so we go 1601 // the pointer route. 1602 unsigned AS = getTargetAddressSpace( 1603 cast<ReferenceType>(T)->getPointeeType()); 1604 Width = Target->getPointerWidth(AS); 1605 Align = Target->getPointerAlign(AS); 1606 break; 1607 } 1608 case Type::Pointer: { 1609 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType()); 1610 Width = Target->getPointerWidth(AS); 1611 Align = Target->getPointerAlign(AS); 1612 break; 1613 } 1614 case Type::MemberPointer: { 1615 const MemberPointerType *MPT = cast<MemberPointerType>(T); 1616 llvm::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT); 1617 break; 1618 } 1619 case Type::Complex: { 1620 // Complex types have the same alignment as their elements, but twice the 1621 // size. 1622 std::pair<uint64_t, unsigned> EltInfo = 1623 getTypeInfo(cast<ComplexType>(T)->getElementType()); 1624 Width = EltInfo.first*2; 1625 Align = EltInfo.second; 1626 break; 1627 } 1628 case Type::ObjCObject: 1629 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr()); 1630 case Type::Decayed: 1631 return getTypeInfo(cast<DecayedType>(T)->getDecayedType().getTypePtr()); 1632 case Type::ObjCInterface: { 1633 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T); 1634 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 1635 Width = toBits(Layout.getSize()); 1636 Align = toBits(Layout.getAlignment()); 1637 break; 1638 } 1639 case Type::Record: 1640 case Type::Enum: { 1641 const TagType *TT = cast<TagType>(T); 1642 1643 if (TT->getDecl()->isInvalidDecl()) { 1644 Width = 8; 1645 Align = 8; 1646 break; 1647 } 1648 1649 if (const EnumType *ET = dyn_cast<EnumType>(TT)) 1650 return getTypeInfo(ET->getDecl()->getIntegerType()); 1651 1652 const RecordType *RT = cast<RecordType>(TT); 1653 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl()); 1654 Width = toBits(Layout.getSize()); 1655 Align = toBits(Layout.getAlignment()); 1656 break; 1657 } 1658 1659 case Type::SubstTemplateTypeParm: 1660 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)-> 1661 getReplacementType().getTypePtr()); 1662 1663 case Type::Auto: { 1664 const AutoType *A = cast<AutoType>(T); 1665 assert(!A->getDeducedType().isNull() && 1666 "cannot request the size of an undeduced or dependent auto type"); 1667 return getTypeInfo(A->getDeducedType().getTypePtr()); 1668 } 1669 1670 case Type::Paren: 1671 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr()); 1672 1673 case Type::Typedef: { 1674 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl(); 1675 std::pair<uint64_t, unsigned> Info 1676 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr()); 1677 // If the typedef has an aligned attribute on it, it overrides any computed 1678 // alignment we have. This violates the GCC documentation (which says that 1679 // attribute(aligned) can only round up) but matches its implementation. 1680 if (unsigned AttrAlign = Typedef->getMaxAlignment()) 1681 Align = AttrAlign; 1682 else 1683 Align = Info.second; 1684 Width = Info.first; 1685 break; 1686 } 1687 1688 case Type::Elaborated: 1689 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr()); 1690 1691 case Type::Attributed: 1692 return getTypeInfo( 1693 cast<AttributedType>(T)->getEquivalentType().getTypePtr()); 1694 1695 case Type::Atomic: { 1696 // Start with the base type information. 1697 std::pair<uint64_t, unsigned> Info 1698 = getTypeInfo(cast<AtomicType>(T)->getValueType()); 1699 Width = Info.first; 1700 Align = Info.second; 1701 1702 // If the size of the type doesn't exceed the platform's max 1703 // atomic promotion width, make the size and alignment more 1704 // favorable to atomic operations: 1705 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) { 1706 // Round the size up to a power of 2. 1707 if (!llvm::isPowerOf2_64(Width)) 1708 Width = llvm::NextPowerOf2(Width); 1709 1710 // Set the alignment equal to the size. 1711 Align = static_cast<unsigned>(Width); 1712 } 1713 } 1714 1715 } 1716 1717 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2"); 1718 return std::make_pair(Width, Align); 1719} 1720 1721/// toCharUnitsFromBits - Convert a size in bits to a size in characters. 1722CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const { 1723 return CharUnits::fromQuantity(BitSize / getCharWidth()); 1724} 1725 1726/// toBits - Convert a size in characters to a size in characters. 1727int64_t ASTContext::toBits(CharUnits CharSize) const { 1728 return CharSize.getQuantity() * getCharWidth(); 1729} 1730 1731/// getTypeSizeInChars - Return the size of the specified type, in characters. 1732/// This method does not work on incomplete types. 1733CharUnits ASTContext::getTypeSizeInChars(QualType T) const { 1734 return getTypeInfoInChars(T).first; 1735} 1736CharUnits ASTContext::getTypeSizeInChars(const Type *T) const { 1737 return getTypeInfoInChars(T).first; 1738} 1739 1740/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in 1741/// characters. This method does not work on incomplete types. 1742CharUnits ASTContext::getTypeAlignInChars(QualType T) const { 1743 return toCharUnitsFromBits(getTypeAlign(T)); 1744} 1745CharUnits ASTContext::getTypeAlignInChars(const Type *T) const { 1746 return toCharUnitsFromBits(getTypeAlign(T)); 1747} 1748 1749/// getPreferredTypeAlign - Return the "preferred" alignment of the specified 1750/// type for the current target in bits. This can be different than the ABI 1751/// alignment in cases where it is beneficial for performance to overalign 1752/// a data type. 1753unsigned ASTContext::getPreferredTypeAlign(const Type *T) const { 1754 unsigned ABIAlign = getTypeAlign(T); 1755 1756 // Double and long long should be naturally aligned if possible. 1757 if (const ComplexType* CT = T->getAs<ComplexType>()) 1758 T = CT->getElementType().getTypePtr(); 1759 if (T->isSpecificBuiltinType(BuiltinType::Double) || 1760 T->isSpecificBuiltinType(BuiltinType::LongLong) || 1761 T->isSpecificBuiltinType(BuiltinType::ULongLong)) 1762 return std::max(ABIAlign, (unsigned)getTypeSize(T)); 1763 1764 return ABIAlign; 1765} 1766 1767/// getAlignOfGlobalVar - Return the alignment in bits that should be given 1768/// to a global variable of the specified type. 1769unsigned ASTContext::getAlignOfGlobalVar(QualType T) const { 1770 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign()); 1771} 1772 1773/// getAlignOfGlobalVarInChars - Return the alignment in characters that 1774/// should be given to a global variable of the specified type. 1775CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const { 1776 return toCharUnitsFromBits(getAlignOfGlobalVar(T)); 1777} 1778 1779/// DeepCollectObjCIvars - 1780/// This routine first collects all declared, but not synthesized, ivars in 1781/// super class and then collects all ivars, including those synthesized for 1782/// current class. This routine is used for implementation of current class 1783/// when all ivars, declared and synthesized are known. 1784/// 1785void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, 1786 bool leafClass, 1787 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const { 1788 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass()) 1789 DeepCollectObjCIvars(SuperClass, false, Ivars); 1790 if (!leafClass) { 1791 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(), 1792 E = OI->ivar_end(); I != E; ++I) 1793 Ivars.push_back(*I); 1794 } else { 1795 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI); 1796 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv; 1797 Iv= Iv->getNextIvar()) 1798 Ivars.push_back(Iv); 1799 } 1800} 1801 1802/// CollectInheritedProtocols - Collect all protocols in current class and 1803/// those inherited by it. 1804void ASTContext::CollectInheritedProtocols(const Decl *CDecl, 1805 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) { 1806 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) { 1807 // We can use protocol_iterator here instead of 1808 // all_referenced_protocol_iterator since we are walking all categories. 1809 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(), 1810 PE = OI->all_referenced_protocol_end(); P != PE; ++P) { 1811 ObjCProtocolDecl *Proto = (*P); 1812 Protocols.insert(Proto->getCanonicalDecl()); 1813 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(), 1814 PE = Proto->protocol_end(); P != PE; ++P) { 1815 Protocols.insert((*P)->getCanonicalDecl()); 1816 CollectInheritedProtocols(*P, Protocols); 1817 } 1818 } 1819 1820 // Categories of this Interface. 1821 for (ObjCInterfaceDecl::visible_categories_iterator 1822 Cat = OI->visible_categories_begin(), 1823 CatEnd = OI->visible_categories_end(); 1824 Cat != CatEnd; ++Cat) { 1825 CollectInheritedProtocols(*Cat, Protocols); 1826 } 1827 1828 if (ObjCInterfaceDecl *SD = OI->getSuperClass()) 1829 while (SD) { 1830 CollectInheritedProtocols(SD, Protocols); 1831 SD = SD->getSuperClass(); 1832 } 1833 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) { 1834 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(), 1835 PE = OC->protocol_end(); P != PE; ++P) { 1836 ObjCProtocolDecl *Proto = (*P); 1837 Protocols.insert(Proto->getCanonicalDecl()); 1838 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(), 1839 PE = Proto->protocol_end(); P != PE; ++P) 1840 CollectInheritedProtocols(*P, Protocols); 1841 } 1842 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) { 1843 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(), 1844 PE = OP->protocol_end(); P != PE; ++P) { 1845 ObjCProtocolDecl *Proto = (*P); 1846 Protocols.insert(Proto->getCanonicalDecl()); 1847 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(), 1848 PE = Proto->protocol_end(); P != PE; ++P) 1849 CollectInheritedProtocols(*P, Protocols); 1850 } 1851 } 1852} 1853 1854unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const { 1855 unsigned count = 0; 1856 // Count ivars declared in class extension. 1857 for (ObjCInterfaceDecl::known_extensions_iterator 1858 Ext = OI->known_extensions_begin(), 1859 ExtEnd = OI->known_extensions_end(); 1860 Ext != ExtEnd; ++Ext) { 1861 count += Ext->ivar_size(); 1862 } 1863 1864 // Count ivar defined in this class's implementation. This 1865 // includes synthesized ivars. 1866 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) 1867 count += ImplDecl->ivar_size(); 1868 1869 return count; 1870} 1871 1872bool ASTContext::isSentinelNullExpr(const Expr *E) { 1873 if (!E) 1874 return false; 1875 1876 // nullptr_t is always treated as null. 1877 if (E->getType()->isNullPtrType()) return true; 1878 1879 if (E->getType()->isAnyPointerType() && 1880 E->IgnoreParenCasts()->isNullPointerConstant(*this, 1881 Expr::NPC_ValueDependentIsNull)) 1882 return true; 1883 1884 // Unfortunately, __null has type 'int'. 1885 if (isa<GNUNullExpr>(E)) return true; 1886 1887 return false; 1888} 1889 1890/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists. 1891ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) { 1892 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 1893 I = ObjCImpls.find(D); 1894 if (I != ObjCImpls.end()) 1895 return cast<ObjCImplementationDecl>(I->second); 1896 return 0; 1897} 1898/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists. 1899ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) { 1900 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 1901 I = ObjCImpls.find(D); 1902 if (I != ObjCImpls.end()) 1903 return cast<ObjCCategoryImplDecl>(I->second); 1904 return 0; 1905} 1906 1907/// \brief Set the implementation of ObjCInterfaceDecl. 1908void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD, 1909 ObjCImplementationDecl *ImplD) { 1910 assert(IFaceD && ImplD && "Passed null params"); 1911 ObjCImpls[IFaceD] = ImplD; 1912} 1913/// \brief Set the implementation of ObjCCategoryDecl. 1914void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD, 1915 ObjCCategoryImplDecl *ImplD) { 1916 assert(CatD && ImplD && "Passed null params"); 1917 ObjCImpls[CatD] = ImplD; 1918} 1919 1920const ObjCInterfaceDecl *ASTContext::getObjContainingInterface( 1921 const NamedDecl *ND) const { 1922 if (const ObjCInterfaceDecl *ID = 1923 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext())) 1924 return ID; 1925 if (const ObjCCategoryDecl *CD = 1926 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext())) 1927 return CD->getClassInterface(); 1928 if (const ObjCImplDecl *IMD = 1929 dyn_cast<ObjCImplDecl>(ND->getDeclContext())) 1930 return IMD->getClassInterface(); 1931 1932 return 0; 1933} 1934 1935/// \brief Get the copy initialization expression of VarDecl,or NULL if 1936/// none exists. 1937Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) { 1938 assert(VD && "Passed null params"); 1939 assert(VD->hasAttr<BlocksAttr>() && 1940 "getBlockVarCopyInits - not __block var"); 1941 llvm::DenseMap<const VarDecl*, Expr*>::iterator 1942 I = BlockVarCopyInits.find(VD); 1943 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0; 1944} 1945 1946/// \brief Set the copy inialization expression of a block var decl. 1947void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) { 1948 assert(VD && Init && "Passed null params"); 1949 assert(VD->hasAttr<BlocksAttr>() && 1950 "setBlockVarCopyInits - not __block var"); 1951 BlockVarCopyInits[VD] = Init; 1952} 1953 1954TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T, 1955 unsigned DataSize) const { 1956 if (!DataSize) 1957 DataSize = TypeLoc::getFullDataSizeForType(T); 1958 else 1959 assert(DataSize == TypeLoc::getFullDataSizeForType(T) && 1960 "incorrect data size provided to CreateTypeSourceInfo!"); 1961 1962 TypeSourceInfo *TInfo = 1963 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8); 1964 new (TInfo) TypeSourceInfo(T); 1965 return TInfo; 1966} 1967 1968TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T, 1969 SourceLocation L) const { 1970 TypeSourceInfo *DI = CreateTypeSourceInfo(T); 1971 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L); 1972 return DI; 1973} 1974 1975const ASTRecordLayout & 1976ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const { 1977 return getObjCLayout(D, 0); 1978} 1979 1980const ASTRecordLayout & 1981ASTContext::getASTObjCImplementationLayout( 1982 const ObjCImplementationDecl *D) const { 1983 return getObjCLayout(D->getClassInterface(), D); 1984} 1985 1986//===----------------------------------------------------------------------===// 1987// Type creation/memoization methods 1988//===----------------------------------------------------------------------===// 1989 1990QualType 1991ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const { 1992 unsigned fastQuals = quals.getFastQualifiers(); 1993 quals.removeFastQualifiers(); 1994 1995 // Check if we've already instantiated this type. 1996 llvm::FoldingSetNodeID ID; 1997 ExtQuals::Profile(ID, baseType, quals); 1998 void *insertPos = 0; 1999 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) { 2000 assert(eq->getQualifiers() == quals); 2001 return QualType(eq, fastQuals); 2002 } 2003 2004 // If the base type is not canonical, make the appropriate canonical type. 2005 QualType canon; 2006 if (!baseType->isCanonicalUnqualified()) { 2007 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split(); 2008 canonSplit.Quals.addConsistentQualifiers(quals); 2009 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals); 2010 2011 // Re-find the insert position. 2012 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos); 2013 } 2014 2015 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals); 2016 ExtQualNodes.InsertNode(eq, insertPos); 2017 return QualType(eq, fastQuals); 2018} 2019 2020QualType 2021ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const { 2022 QualType CanT = getCanonicalType(T); 2023 if (CanT.getAddressSpace() == AddressSpace) 2024 return T; 2025 2026 // If we are composing extended qualifiers together, merge together 2027 // into one ExtQuals node. 2028 QualifierCollector Quals; 2029 const Type *TypeNode = Quals.strip(T); 2030 2031 // If this type already has an address space specified, it cannot get 2032 // another one. 2033 assert(!Quals.hasAddressSpace() && 2034 "Type cannot be in multiple addr spaces!"); 2035 Quals.addAddressSpace(AddressSpace); 2036 2037 return getExtQualType(TypeNode, Quals); 2038} 2039 2040QualType ASTContext::getObjCGCQualType(QualType T, 2041 Qualifiers::GC GCAttr) const { 2042 QualType CanT = getCanonicalType(T); 2043 if (CanT.getObjCGCAttr() == GCAttr) 2044 return T; 2045 2046 if (const PointerType *ptr = T->getAs<PointerType>()) { 2047 QualType Pointee = ptr->getPointeeType(); 2048 if (Pointee->isAnyPointerType()) { 2049 QualType ResultType = getObjCGCQualType(Pointee, GCAttr); 2050 return getPointerType(ResultType); 2051 } 2052 } 2053 2054 // If we are composing extended qualifiers together, merge together 2055 // into one ExtQuals node. 2056 QualifierCollector Quals; 2057 const Type *TypeNode = Quals.strip(T); 2058 2059 // If this type already has an ObjCGC specified, it cannot get 2060 // another one. 2061 assert(!Quals.hasObjCGCAttr() && 2062 "Type cannot have multiple ObjCGCs!"); 2063 Quals.addObjCGCAttr(GCAttr); 2064 2065 return getExtQualType(TypeNode, Quals); 2066} 2067 2068const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T, 2069 FunctionType::ExtInfo Info) { 2070 if (T->getExtInfo() == Info) 2071 return T; 2072 2073 QualType Result; 2074 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) { 2075 Result = getFunctionNoProtoType(FNPT->getResultType(), Info); 2076 } else { 2077 const FunctionProtoType *FPT = cast<FunctionProtoType>(T); 2078 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 2079 EPI.ExtInfo = Info; 2080 Result = getFunctionType(FPT->getResultType(), FPT->getArgTypes(), EPI); 2081 } 2082 2083 return cast<FunctionType>(Result.getTypePtr()); 2084} 2085 2086void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD, 2087 QualType ResultType) { 2088 FD = FD->getMostRecentDecl(); 2089 while (true) { 2090 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>(); 2091 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 2092 FD->setType(getFunctionType(ResultType, FPT->getArgTypes(), EPI)); 2093 if (FunctionDecl *Next = FD->getPreviousDecl()) 2094 FD = Next; 2095 else 2096 break; 2097 } 2098 if (ASTMutationListener *L = getASTMutationListener()) 2099 L->DeducedReturnType(FD, ResultType); 2100} 2101 2102/// getComplexType - Return the uniqued reference to the type for a complex 2103/// number with the specified element type. 2104QualType ASTContext::getComplexType(QualType T) const { 2105 // Unique pointers, to guarantee there is only one pointer of a particular 2106 // structure. 2107 llvm::FoldingSetNodeID ID; 2108 ComplexType::Profile(ID, T); 2109 2110 void *InsertPos = 0; 2111 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos)) 2112 return QualType(CT, 0); 2113 2114 // If the pointee type isn't canonical, this won't be a canonical type either, 2115 // so fill in the canonical type field. 2116 QualType Canonical; 2117 if (!T.isCanonical()) { 2118 Canonical = getComplexType(getCanonicalType(T)); 2119 2120 // Get the new insert position for the node we care about. 2121 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos); 2122 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 2123 } 2124 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical); 2125 Types.push_back(New); 2126 ComplexTypes.InsertNode(New, InsertPos); 2127 return QualType(New, 0); 2128} 2129 2130/// getPointerType - Return the uniqued reference to the type for a pointer to 2131/// the specified type. 2132QualType ASTContext::getPointerType(QualType T) const { 2133 // Unique pointers, to guarantee there is only one pointer of a particular 2134 // structure. 2135 llvm::FoldingSetNodeID ID; 2136 PointerType::Profile(ID, T); 2137 2138 void *InsertPos = 0; 2139 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 2140 return QualType(PT, 0); 2141 2142 // If the pointee type isn't canonical, this won't be a canonical type either, 2143 // so fill in the canonical type field. 2144 QualType Canonical; 2145 if (!T.isCanonical()) { 2146 Canonical = getPointerType(getCanonicalType(T)); 2147 2148 // Get the new insert position for the node we care about. 2149 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos); 2150 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 2151 } 2152 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical); 2153 Types.push_back(New); 2154 PointerTypes.InsertNode(New, InsertPos); 2155 return QualType(New, 0); 2156} 2157 2158QualType ASTContext::getDecayedType(QualType T) const { 2159 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay"); 2160 2161 llvm::FoldingSetNodeID ID; 2162 DecayedType::Profile(ID, T); 2163 void *InsertPos = 0; 2164 if (DecayedType *DT = DecayedTypes.FindNodeOrInsertPos(ID, InsertPos)) 2165 return QualType(DT, 0); 2166 2167 QualType Decayed; 2168 2169 // C99 6.7.5.3p7: 2170 // A declaration of a parameter as "array of type" shall be 2171 // adjusted to "qualified pointer to type", where the type 2172 // qualifiers (if any) are those specified within the [ and ] of 2173 // the array type derivation. 2174 if (T->isArrayType()) 2175 Decayed = getArrayDecayedType(T); 2176 2177 // C99 6.7.5.3p8: 2178 // A declaration of a parameter as "function returning type" 2179 // shall be adjusted to "pointer to function returning type", as 2180 // in 6.3.2.1. 2181 if (T->isFunctionType()) 2182 Decayed = getPointerType(T); 2183 2184 QualType Canonical = getCanonicalType(Decayed); 2185 2186 // Get the new insert position for the node we care about. 2187 DecayedType *NewIP = DecayedTypes.FindNodeOrInsertPos(ID, InsertPos); 2188 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 2189 2190 DecayedType *New = 2191 new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical); 2192 Types.push_back(New); 2193 DecayedTypes.InsertNode(New, InsertPos); 2194 return QualType(New, 0); 2195} 2196 2197/// getBlockPointerType - Return the uniqued reference to the type for 2198/// a pointer to the specified block. 2199QualType ASTContext::getBlockPointerType(QualType T) const { 2200 assert(T->isFunctionType() && "block of function types only"); 2201 // Unique pointers, to guarantee there is only one block of a particular 2202 // structure. 2203 llvm::FoldingSetNodeID ID; 2204 BlockPointerType::Profile(ID, T); 2205 2206 void *InsertPos = 0; 2207 if (BlockPointerType *PT = 2208 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 2209 return QualType(PT, 0); 2210 2211 // If the block pointee type isn't canonical, this won't be a canonical 2212 // type either so fill in the canonical type field. 2213 QualType Canonical; 2214 if (!T.isCanonical()) { 2215 Canonical = getBlockPointerType(getCanonicalType(T)); 2216 2217 // Get the new insert position for the node we care about. 2218 BlockPointerType *NewIP = 2219 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 2220 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 2221 } 2222 BlockPointerType *New 2223 = new (*this, TypeAlignment) BlockPointerType(T, Canonical); 2224 Types.push_back(New); 2225 BlockPointerTypes.InsertNode(New, InsertPos); 2226 return QualType(New, 0); 2227} 2228 2229/// getLValueReferenceType - Return the uniqued reference to the type for an 2230/// lvalue reference to the specified type. 2231QualType 2232ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const { 2233 assert(getCanonicalType(T) != OverloadTy && 2234 "Unresolved overloaded function type"); 2235 2236 // Unique pointers, to guarantee there is only one pointer of a particular 2237 // structure. 2238 llvm::FoldingSetNodeID ID; 2239 ReferenceType::Profile(ID, T, SpelledAsLValue); 2240 2241 void *InsertPos = 0; 2242 if (LValueReferenceType *RT = 2243 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 2244 return QualType(RT, 0); 2245 2246 const ReferenceType *InnerRef = T->getAs<ReferenceType>(); 2247 2248 // If the referencee type isn't canonical, this won't be a canonical type 2249 // either, so fill in the canonical type field. 2250 QualType Canonical; 2251 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) { 2252 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 2253 Canonical = getLValueReferenceType(getCanonicalType(PointeeType)); 2254 2255 // Get the new insert position for the node we care about. 2256 LValueReferenceType *NewIP = 2257 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 2258 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 2259 } 2260 2261 LValueReferenceType *New 2262 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical, 2263 SpelledAsLValue); 2264 Types.push_back(New); 2265 LValueReferenceTypes.InsertNode(New, InsertPos); 2266 2267 return QualType(New, 0); 2268} 2269 2270/// getRValueReferenceType - Return the uniqued reference to the type for an 2271/// rvalue reference to the specified type. 2272QualType ASTContext::getRValueReferenceType(QualType T) const { 2273 // Unique pointers, to guarantee there is only one pointer of a particular 2274 // structure. 2275 llvm::FoldingSetNodeID ID; 2276 ReferenceType::Profile(ID, T, false); 2277 2278 void *InsertPos = 0; 2279 if (RValueReferenceType *RT = 2280 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 2281 return QualType(RT, 0); 2282 2283 const ReferenceType *InnerRef = T->getAs<ReferenceType>(); 2284 2285 // If the referencee type isn't canonical, this won't be a canonical type 2286 // either, so fill in the canonical type field. 2287 QualType Canonical; 2288 if (InnerRef || !T.isCanonical()) { 2289 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 2290 Canonical = getRValueReferenceType(getCanonicalType(PointeeType)); 2291 2292 // Get the new insert position for the node we care about. 2293 RValueReferenceType *NewIP = 2294 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 2295 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 2296 } 2297 2298 RValueReferenceType *New 2299 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical); 2300 Types.push_back(New); 2301 RValueReferenceTypes.InsertNode(New, InsertPos); 2302 return QualType(New, 0); 2303} 2304 2305/// getMemberPointerType - Return the uniqued reference to the type for a 2306/// member pointer to the specified type, in the specified class. 2307QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const { 2308 // Unique pointers, to guarantee there is only one pointer of a particular 2309 // structure. 2310 llvm::FoldingSetNodeID ID; 2311 MemberPointerType::Profile(ID, T, Cls); 2312 2313 void *InsertPos = 0; 2314 if (MemberPointerType *PT = 2315 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 2316 return QualType(PT, 0); 2317 2318 // If the pointee or class type isn't canonical, this won't be a canonical 2319 // type either, so fill in the canonical type field. 2320 QualType Canonical; 2321 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) { 2322 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls)); 2323 2324 // Get the new insert position for the node we care about. 2325 MemberPointerType *NewIP = 2326 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 2327 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 2328 } 2329 MemberPointerType *New 2330 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical); 2331 Types.push_back(New); 2332 MemberPointerTypes.InsertNode(New, InsertPos); 2333 return QualType(New, 0); 2334} 2335 2336/// getConstantArrayType - Return the unique reference to the type for an 2337/// array of the specified element type. 2338QualType ASTContext::getConstantArrayType(QualType EltTy, 2339 const llvm::APInt &ArySizeIn, 2340 ArrayType::ArraySizeModifier ASM, 2341 unsigned IndexTypeQuals) const { 2342 assert((EltTy->isDependentType() || 2343 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) && 2344 "Constant array of VLAs is illegal!"); 2345 2346 // Convert the array size into a canonical width matching the pointer size for 2347 // the target. 2348 llvm::APInt ArySize(ArySizeIn); 2349 ArySize = 2350 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy))); 2351 2352 llvm::FoldingSetNodeID ID; 2353 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals); 2354 2355 void *InsertPos = 0; 2356 if (ConstantArrayType *ATP = 2357 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 2358 return QualType(ATP, 0); 2359 2360 // If the element type isn't canonical or has qualifiers, this won't 2361 // be a canonical type either, so fill in the canonical type field. 2362 QualType Canon; 2363 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) { 2364 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 2365 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, 2366 ASM, IndexTypeQuals); 2367 Canon = getQualifiedType(Canon, canonSplit.Quals); 2368 2369 // Get the new insert position for the node we care about. 2370 ConstantArrayType *NewIP = 2371 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 2372 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 2373 } 2374 2375 ConstantArrayType *New = new(*this,TypeAlignment) 2376 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals); 2377 ConstantArrayTypes.InsertNode(New, InsertPos); 2378 Types.push_back(New); 2379 return QualType(New, 0); 2380} 2381 2382/// getVariableArrayDecayedType - Turns the given type, which may be 2383/// variably-modified, into the corresponding type with all the known 2384/// sizes replaced with [*]. 2385QualType ASTContext::getVariableArrayDecayedType(QualType type) const { 2386 // Vastly most common case. 2387 if (!type->isVariablyModifiedType()) return type; 2388 2389 QualType result; 2390 2391 SplitQualType split = type.getSplitDesugaredType(); 2392 const Type *ty = split.Ty; 2393 switch (ty->getTypeClass()) { 2394#define TYPE(Class, Base) 2395#define ABSTRACT_TYPE(Class, Base) 2396#define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 2397#include "clang/AST/TypeNodes.def" 2398 llvm_unreachable("didn't desugar past all non-canonical types?"); 2399 2400 // These types should never be variably-modified. 2401 case Type::Builtin: 2402 case Type::Complex: 2403 case Type::Vector: 2404 case Type::ExtVector: 2405 case Type::DependentSizedExtVector: 2406 case Type::ObjCObject: 2407 case Type::ObjCInterface: 2408 case Type::ObjCObjectPointer: 2409 case Type::Record: 2410 case Type::Enum: 2411 case Type::UnresolvedUsing: 2412 case Type::TypeOfExpr: 2413 case Type::TypeOf: 2414 case Type::Decltype: 2415 case Type::UnaryTransform: 2416 case Type::DependentName: 2417 case Type::InjectedClassName: 2418 case Type::TemplateSpecialization: 2419 case Type::DependentTemplateSpecialization: 2420 case Type::TemplateTypeParm: 2421 case Type::SubstTemplateTypeParmPack: 2422 case Type::Auto: 2423 case Type::PackExpansion: 2424 llvm_unreachable("type should never be variably-modified"); 2425 2426 // These types can be variably-modified but should never need to 2427 // further decay. 2428 case Type::FunctionNoProto: 2429 case Type::FunctionProto: 2430 case Type::BlockPointer: 2431 case Type::MemberPointer: 2432 return type; 2433 2434 // These types can be variably-modified. All these modifications 2435 // preserve structure except as noted by comments. 2436 // TODO: if we ever care about optimizing VLAs, there are no-op 2437 // optimizations available here. 2438 case Type::Pointer: 2439 result = getPointerType(getVariableArrayDecayedType( 2440 cast<PointerType>(ty)->getPointeeType())); 2441 break; 2442 2443 case Type::LValueReference: { 2444 const LValueReferenceType *lv = cast<LValueReferenceType>(ty); 2445 result = getLValueReferenceType( 2446 getVariableArrayDecayedType(lv->getPointeeType()), 2447 lv->isSpelledAsLValue()); 2448 break; 2449 } 2450 2451 case Type::RValueReference: { 2452 const RValueReferenceType *lv = cast<RValueReferenceType>(ty); 2453 result = getRValueReferenceType( 2454 getVariableArrayDecayedType(lv->getPointeeType())); 2455 break; 2456 } 2457 2458 case Type::Atomic: { 2459 const AtomicType *at = cast<AtomicType>(ty); 2460 result = getAtomicType(getVariableArrayDecayedType(at->getValueType())); 2461 break; 2462 } 2463 2464 case Type::ConstantArray: { 2465 const ConstantArrayType *cat = cast<ConstantArrayType>(ty); 2466 result = getConstantArrayType( 2467 getVariableArrayDecayedType(cat->getElementType()), 2468 cat->getSize(), 2469 cat->getSizeModifier(), 2470 cat->getIndexTypeCVRQualifiers()); 2471 break; 2472 } 2473 2474 case Type::DependentSizedArray: { 2475 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty); 2476 result = getDependentSizedArrayType( 2477 getVariableArrayDecayedType(dat->getElementType()), 2478 dat->getSizeExpr(), 2479 dat->getSizeModifier(), 2480 dat->getIndexTypeCVRQualifiers(), 2481 dat->getBracketsRange()); 2482 break; 2483 } 2484 2485 // Turn incomplete types into [*] types. 2486 case Type::IncompleteArray: { 2487 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty); 2488 result = getVariableArrayType( 2489 getVariableArrayDecayedType(iat->getElementType()), 2490 /*size*/ 0, 2491 ArrayType::Normal, 2492 iat->getIndexTypeCVRQualifiers(), 2493 SourceRange()); 2494 break; 2495 } 2496 2497 // Turn VLA types into [*] types. 2498 case Type::VariableArray: { 2499 const VariableArrayType *vat = cast<VariableArrayType>(ty); 2500 result = getVariableArrayType( 2501 getVariableArrayDecayedType(vat->getElementType()), 2502 /*size*/ 0, 2503 ArrayType::Star, 2504 vat->getIndexTypeCVRQualifiers(), 2505 vat->getBracketsRange()); 2506 break; 2507 } 2508 } 2509 2510 // Apply the top-level qualifiers from the original. 2511 return getQualifiedType(result, split.Quals); 2512} 2513 2514/// getVariableArrayType - Returns a non-unique reference to the type for a 2515/// variable array of the specified element type. 2516QualType ASTContext::getVariableArrayType(QualType EltTy, 2517 Expr *NumElts, 2518 ArrayType::ArraySizeModifier ASM, 2519 unsigned IndexTypeQuals, 2520 SourceRange Brackets) const { 2521 // Since we don't unique expressions, it isn't possible to unique VLA's 2522 // that have an expression provided for their size. 2523 QualType Canon; 2524 2525 // Be sure to pull qualifiers off the element type. 2526 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) { 2527 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 2528 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM, 2529 IndexTypeQuals, Brackets); 2530 Canon = getQualifiedType(Canon, canonSplit.Quals); 2531 } 2532 2533 VariableArrayType *New = new(*this, TypeAlignment) 2534 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets); 2535 2536 VariableArrayTypes.push_back(New); 2537 Types.push_back(New); 2538 return QualType(New, 0); 2539} 2540 2541/// getDependentSizedArrayType - Returns a non-unique reference to 2542/// the type for a dependently-sized array of the specified element 2543/// type. 2544QualType ASTContext::getDependentSizedArrayType(QualType elementType, 2545 Expr *numElements, 2546 ArrayType::ArraySizeModifier ASM, 2547 unsigned elementTypeQuals, 2548 SourceRange brackets) const { 2549 assert((!numElements || numElements->isTypeDependent() || 2550 numElements->isValueDependent()) && 2551 "Size must be type- or value-dependent!"); 2552 2553 // Dependently-sized array types that do not have a specified number 2554 // of elements will have their sizes deduced from a dependent 2555 // initializer. We do no canonicalization here at all, which is okay 2556 // because they can't be used in most locations. 2557 if (!numElements) { 2558 DependentSizedArrayType *newType 2559 = new (*this, TypeAlignment) 2560 DependentSizedArrayType(*this, elementType, QualType(), 2561 numElements, ASM, elementTypeQuals, 2562 brackets); 2563 Types.push_back(newType); 2564 return QualType(newType, 0); 2565 } 2566 2567 // Otherwise, we actually build a new type every time, but we 2568 // also build a canonical type. 2569 2570 SplitQualType canonElementType = getCanonicalType(elementType).split(); 2571 2572 void *insertPos = 0; 2573 llvm::FoldingSetNodeID ID; 2574 DependentSizedArrayType::Profile(ID, *this, 2575 QualType(canonElementType.Ty, 0), 2576 ASM, elementTypeQuals, numElements); 2577 2578 // Look for an existing type with these properties. 2579 DependentSizedArrayType *canonTy = 2580 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos); 2581 2582 // If we don't have one, build one. 2583 if (!canonTy) { 2584 canonTy = new (*this, TypeAlignment) 2585 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0), 2586 QualType(), numElements, ASM, elementTypeQuals, 2587 brackets); 2588 DependentSizedArrayTypes.InsertNode(canonTy, insertPos); 2589 Types.push_back(canonTy); 2590 } 2591 2592 // Apply qualifiers from the element type to the array. 2593 QualType canon = getQualifiedType(QualType(canonTy,0), 2594 canonElementType.Quals); 2595 2596 // If we didn't need extra canonicalization for the element type, 2597 // then just use that as our result. 2598 if (QualType(canonElementType.Ty, 0) == elementType) 2599 return canon; 2600 2601 // Otherwise, we need to build a type which follows the spelling 2602 // of the element type. 2603 DependentSizedArrayType *sugaredType 2604 = new (*this, TypeAlignment) 2605 DependentSizedArrayType(*this, elementType, canon, numElements, 2606 ASM, elementTypeQuals, brackets); 2607 Types.push_back(sugaredType); 2608 return QualType(sugaredType, 0); 2609} 2610 2611QualType ASTContext::getIncompleteArrayType(QualType elementType, 2612 ArrayType::ArraySizeModifier ASM, 2613 unsigned elementTypeQuals) const { 2614 llvm::FoldingSetNodeID ID; 2615 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals); 2616 2617 void *insertPos = 0; 2618 if (IncompleteArrayType *iat = 2619 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos)) 2620 return QualType(iat, 0); 2621 2622 // If the element type isn't canonical, this won't be a canonical type 2623 // either, so fill in the canonical type field. We also have to pull 2624 // qualifiers off the element type. 2625 QualType canon; 2626 2627 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) { 2628 SplitQualType canonSplit = getCanonicalType(elementType).split(); 2629 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0), 2630 ASM, elementTypeQuals); 2631 canon = getQualifiedType(canon, canonSplit.Quals); 2632 2633 // Get the new insert position for the node we care about. 2634 IncompleteArrayType *existing = 2635 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos); 2636 assert(!existing && "Shouldn't be in the map!"); (void) existing; 2637 } 2638 2639 IncompleteArrayType *newType = new (*this, TypeAlignment) 2640 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals); 2641 2642 IncompleteArrayTypes.InsertNode(newType, insertPos); 2643 Types.push_back(newType); 2644 return QualType(newType, 0); 2645} 2646 2647/// getVectorType - Return the unique reference to a vector type of 2648/// the specified element type and size. VectorType must be a built-in type. 2649QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts, 2650 VectorType::VectorKind VecKind) const { 2651 assert(vecType->isBuiltinType()); 2652 2653 // Check if we've already instantiated a vector of this type. 2654 llvm::FoldingSetNodeID ID; 2655 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind); 2656 2657 void *InsertPos = 0; 2658 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 2659 return QualType(VTP, 0); 2660 2661 // If the element type isn't canonical, this won't be a canonical type either, 2662 // so fill in the canonical type field. 2663 QualType Canonical; 2664 if (!vecType.isCanonical()) { 2665 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind); 2666 2667 // Get the new insert position for the node we care about. 2668 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 2669 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 2670 } 2671 VectorType *New = new (*this, TypeAlignment) 2672 VectorType(vecType, NumElts, Canonical, VecKind); 2673 VectorTypes.InsertNode(New, InsertPos); 2674 Types.push_back(New); 2675 return QualType(New, 0); 2676} 2677 2678/// getExtVectorType - Return the unique reference to an extended vector type of 2679/// the specified element type and size. VectorType must be a built-in type. 2680QualType 2681ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const { 2682 assert(vecType->isBuiltinType() || vecType->isDependentType()); 2683 2684 // Check if we've already instantiated a vector of this type. 2685 llvm::FoldingSetNodeID ID; 2686 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, 2687 VectorType::GenericVector); 2688 void *InsertPos = 0; 2689 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 2690 return QualType(VTP, 0); 2691 2692 // If the element type isn't canonical, this won't be a canonical type either, 2693 // so fill in the canonical type field. 2694 QualType Canonical; 2695 if (!vecType.isCanonical()) { 2696 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts); 2697 2698 // Get the new insert position for the node we care about. 2699 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 2700 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 2701 } 2702 ExtVectorType *New = new (*this, TypeAlignment) 2703 ExtVectorType(vecType, NumElts, Canonical); 2704 VectorTypes.InsertNode(New, InsertPos); 2705 Types.push_back(New); 2706 return QualType(New, 0); 2707} 2708 2709QualType 2710ASTContext::getDependentSizedExtVectorType(QualType vecType, 2711 Expr *SizeExpr, 2712 SourceLocation AttrLoc) const { 2713 llvm::FoldingSetNodeID ID; 2714 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType), 2715 SizeExpr); 2716 2717 void *InsertPos = 0; 2718 DependentSizedExtVectorType *Canon 2719 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 2720 DependentSizedExtVectorType *New; 2721 if (Canon) { 2722 // We already have a canonical version of this array type; use it as 2723 // the canonical type for a newly-built type. 2724 New = new (*this, TypeAlignment) 2725 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0), 2726 SizeExpr, AttrLoc); 2727 } else { 2728 QualType CanonVecTy = getCanonicalType(vecType); 2729 if (CanonVecTy == vecType) { 2730 New = new (*this, TypeAlignment) 2731 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr, 2732 AttrLoc); 2733 2734 DependentSizedExtVectorType *CanonCheck 2735 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 2736 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken"); 2737 (void)CanonCheck; 2738 DependentSizedExtVectorTypes.InsertNode(New, InsertPos); 2739 } else { 2740 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr, 2741 SourceLocation()); 2742 New = new (*this, TypeAlignment) 2743 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc); 2744 } 2745 } 2746 2747 Types.push_back(New); 2748 return QualType(New, 0); 2749} 2750 2751/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'. 2752/// 2753QualType 2754ASTContext::getFunctionNoProtoType(QualType ResultTy, 2755 const FunctionType::ExtInfo &Info) const { 2756 const CallingConv CallConv = Info.getCC(); 2757 2758 // Unique functions, to guarantee there is only one function of a particular 2759 // structure. 2760 llvm::FoldingSetNodeID ID; 2761 FunctionNoProtoType::Profile(ID, ResultTy, Info); 2762 2763 void *InsertPos = 0; 2764 if (FunctionNoProtoType *FT = 2765 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 2766 return QualType(FT, 0); 2767 2768 QualType Canonical; 2769 if (!ResultTy.isCanonical()) { 2770 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info); 2771 2772 // Get the new insert position for the node we care about. 2773 FunctionNoProtoType *NewIP = 2774 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 2775 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 2776 } 2777 2778 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv); 2779 FunctionNoProtoType *New = new (*this, TypeAlignment) 2780 FunctionNoProtoType(ResultTy, Canonical, newInfo); 2781 Types.push_back(New); 2782 FunctionNoProtoTypes.InsertNode(New, InsertPos); 2783 return QualType(New, 0); 2784} 2785 2786/// \brief Determine whether \p T is canonical as the result type of a function. 2787static bool isCanonicalResultType(QualType T) { 2788 return T.isCanonical() && 2789 (T.getObjCLifetime() == Qualifiers::OCL_None || 2790 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone); 2791} 2792 2793/// getFunctionType - Return a normal function type with a typed argument 2794/// list. isVariadic indicates whether the argument list includes '...'. 2795QualType 2796ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray, 2797 const FunctionProtoType::ExtProtoInfo &EPI) const { 2798 size_t NumArgs = ArgArray.size(); 2799 2800 // Unique functions, to guarantee there is only one function of a particular 2801 // structure. 2802 llvm::FoldingSetNodeID ID; 2803 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI, 2804 *this); 2805 2806 void *InsertPos = 0; 2807 if (FunctionProtoType *FTP = 2808 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 2809 return QualType(FTP, 0); 2810 2811 // Determine whether the type being created is already canonical or not. 2812 bool isCanonical = 2813 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) && 2814 !EPI.HasTrailingReturn; 2815 for (unsigned i = 0; i != NumArgs && isCanonical; ++i) 2816 if (!ArgArray[i].isCanonicalAsParam()) 2817 isCanonical = false; 2818 2819 // If this type isn't canonical, get the canonical version of it. 2820 // The exception spec is not part of the canonical type. 2821 QualType Canonical; 2822 if (!isCanonical) { 2823 SmallVector<QualType, 16> CanonicalArgs; 2824 CanonicalArgs.reserve(NumArgs); 2825 for (unsigned i = 0; i != NumArgs; ++i) 2826 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i])); 2827 2828 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI; 2829 CanonicalEPI.HasTrailingReturn = false; 2830 CanonicalEPI.ExceptionSpecType = EST_None; 2831 CanonicalEPI.NumExceptions = 0; 2832 2833 // Result types do not have ARC lifetime qualifiers. 2834 QualType CanResultTy = getCanonicalType(ResultTy); 2835 if (ResultTy.getQualifiers().hasObjCLifetime()) { 2836 Qualifiers Qs = CanResultTy.getQualifiers(); 2837 Qs.removeObjCLifetime(); 2838 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs); 2839 } 2840 2841 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI); 2842 2843 // Get the new insert position for the node we care about. 2844 FunctionProtoType *NewIP = 2845 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 2846 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 2847 } 2848 2849 // FunctionProtoType objects are allocated with extra bytes after 2850 // them for three variable size arrays at the end: 2851 // - parameter types 2852 // - exception types 2853 // - consumed-arguments flags 2854 // Instead of the exception types, there could be a noexcept 2855 // expression, or information used to resolve the exception 2856 // specification. 2857 size_t Size = sizeof(FunctionProtoType) + 2858 NumArgs * sizeof(QualType); 2859 if (EPI.ExceptionSpecType == EST_Dynamic) { 2860 Size += EPI.NumExceptions * sizeof(QualType); 2861 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) { 2862 Size += sizeof(Expr*); 2863 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) { 2864 Size += 2 * sizeof(FunctionDecl*); 2865 } else if (EPI.ExceptionSpecType == EST_Unevaluated) { 2866 Size += sizeof(FunctionDecl*); 2867 } 2868 if (EPI.ConsumedArguments) 2869 Size += NumArgs * sizeof(bool); 2870 2871 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment); 2872 FunctionProtoType::ExtProtoInfo newEPI = EPI; 2873 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI); 2874 Types.push_back(FTP); 2875 FunctionProtoTypes.InsertNode(FTP, InsertPos); 2876 return QualType(FTP, 0); 2877} 2878 2879#ifndef NDEBUG 2880static bool NeedsInjectedClassNameType(const RecordDecl *D) { 2881 if (!isa<CXXRecordDecl>(D)) return false; 2882 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D); 2883 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) 2884 return true; 2885 if (RD->getDescribedClassTemplate() && 2886 !isa<ClassTemplateSpecializationDecl>(RD)) 2887 return true; 2888 return false; 2889} 2890#endif 2891 2892/// getInjectedClassNameType - Return the unique reference to the 2893/// injected class name type for the specified templated declaration. 2894QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl, 2895 QualType TST) const { 2896 assert(NeedsInjectedClassNameType(Decl)); 2897 if (Decl->TypeForDecl) { 2898 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 2899 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) { 2900 assert(PrevDecl->TypeForDecl && "previous declaration has no type"); 2901 Decl->TypeForDecl = PrevDecl->TypeForDecl; 2902 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 2903 } else { 2904 Type *newType = 2905 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST); 2906 Decl->TypeForDecl = newType; 2907 Types.push_back(newType); 2908 } 2909 return QualType(Decl->TypeForDecl, 0); 2910} 2911 2912/// getTypeDeclType - Return the unique reference to the type for the 2913/// specified type declaration. 2914QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const { 2915 assert(Decl && "Passed null for Decl param"); 2916 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case"); 2917 2918 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl)) 2919 return getTypedefType(Typedef); 2920 2921 assert(!isa<TemplateTypeParmDecl>(Decl) && 2922 "Template type parameter types are always available."); 2923 2924 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) { 2925 assert(!Record->getPreviousDecl() && 2926 "struct/union has previous declaration"); 2927 assert(!NeedsInjectedClassNameType(Record)); 2928 return getRecordType(Record); 2929 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) { 2930 assert(!Enum->getPreviousDecl() && 2931 "enum has previous declaration"); 2932 return getEnumType(Enum); 2933 } else if (const UnresolvedUsingTypenameDecl *Using = 2934 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) { 2935 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using); 2936 Decl->TypeForDecl = newType; 2937 Types.push_back(newType); 2938 } else 2939 llvm_unreachable("TypeDecl without a type?"); 2940 2941 return QualType(Decl->TypeForDecl, 0); 2942} 2943 2944/// getTypedefType - Return the unique reference to the type for the 2945/// specified typedef name decl. 2946QualType 2947ASTContext::getTypedefType(const TypedefNameDecl *Decl, 2948 QualType Canonical) const { 2949 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 2950 2951 if (Canonical.isNull()) 2952 Canonical = getCanonicalType(Decl->getUnderlyingType()); 2953 TypedefType *newType = new(*this, TypeAlignment) 2954 TypedefType(Type::Typedef, Decl, Canonical); 2955 Decl->TypeForDecl = newType; 2956 Types.push_back(newType); 2957 return QualType(newType, 0); 2958} 2959 2960QualType ASTContext::getRecordType(const RecordDecl *Decl) const { 2961 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 2962 2963 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl()) 2964 if (PrevDecl->TypeForDecl) 2965 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 2966 2967 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl); 2968 Decl->TypeForDecl = newType; 2969 Types.push_back(newType); 2970 return QualType(newType, 0); 2971} 2972 2973QualType ASTContext::getEnumType(const EnumDecl *Decl) const { 2974 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 2975 2976 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl()) 2977 if (PrevDecl->TypeForDecl) 2978 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 2979 2980 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl); 2981 Decl->TypeForDecl = newType; 2982 Types.push_back(newType); 2983 return QualType(newType, 0); 2984} 2985 2986QualType ASTContext::getAttributedType(AttributedType::Kind attrKind, 2987 QualType modifiedType, 2988 QualType equivalentType) { 2989 llvm::FoldingSetNodeID id; 2990 AttributedType::Profile(id, attrKind, modifiedType, equivalentType); 2991 2992 void *insertPos = 0; 2993 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos); 2994 if (type) return QualType(type, 0); 2995 2996 QualType canon = getCanonicalType(equivalentType); 2997 type = new (*this, TypeAlignment) 2998 AttributedType(canon, attrKind, modifiedType, equivalentType); 2999 3000 Types.push_back(type); 3001 AttributedTypes.InsertNode(type, insertPos); 3002 3003 return QualType(type, 0); 3004} 3005 3006 3007/// \brief Retrieve a substitution-result type. 3008QualType 3009ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm, 3010 QualType Replacement) const { 3011 assert(Replacement.isCanonical() 3012 && "replacement types must always be canonical"); 3013 3014 llvm::FoldingSetNodeID ID; 3015 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement); 3016 void *InsertPos = 0; 3017 SubstTemplateTypeParmType *SubstParm 3018 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 3019 3020 if (!SubstParm) { 3021 SubstParm = new (*this, TypeAlignment) 3022 SubstTemplateTypeParmType(Parm, Replacement); 3023 Types.push_back(SubstParm); 3024 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos); 3025 } 3026 3027 return QualType(SubstParm, 0); 3028} 3029 3030/// \brief Retrieve a 3031QualType ASTContext::getSubstTemplateTypeParmPackType( 3032 const TemplateTypeParmType *Parm, 3033 const TemplateArgument &ArgPack) { 3034#ifndef NDEBUG 3035 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(), 3036 PEnd = ArgPack.pack_end(); 3037 P != PEnd; ++P) { 3038 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type"); 3039 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type"); 3040 } 3041#endif 3042 3043 llvm::FoldingSetNodeID ID; 3044 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack); 3045 void *InsertPos = 0; 3046 if (SubstTemplateTypeParmPackType *SubstParm 3047 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos)) 3048 return QualType(SubstParm, 0); 3049 3050 QualType Canon; 3051 if (!Parm->isCanonicalUnqualified()) { 3052 Canon = getCanonicalType(QualType(Parm, 0)); 3053 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon), 3054 ArgPack); 3055 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos); 3056 } 3057 3058 SubstTemplateTypeParmPackType *SubstParm 3059 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon, 3060 ArgPack); 3061 Types.push_back(SubstParm); 3062 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos); 3063 return QualType(SubstParm, 0); 3064} 3065 3066/// \brief Retrieve the template type parameter type for a template 3067/// parameter or parameter pack with the given depth, index, and (optionally) 3068/// name. 3069QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index, 3070 bool ParameterPack, 3071 TemplateTypeParmDecl *TTPDecl) const { 3072 llvm::FoldingSetNodeID ID; 3073 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl); 3074 void *InsertPos = 0; 3075 TemplateTypeParmType *TypeParm 3076 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 3077 3078 if (TypeParm) 3079 return QualType(TypeParm, 0); 3080 3081 if (TTPDecl) { 3082 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack); 3083 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon); 3084 3085 TemplateTypeParmType *TypeCheck 3086 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 3087 assert(!TypeCheck && "Template type parameter canonical type broken"); 3088 (void)TypeCheck; 3089 } else 3090 TypeParm = new (*this, TypeAlignment) 3091 TemplateTypeParmType(Depth, Index, ParameterPack); 3092 3093 Types.push_back(TypeParm); 3094 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos); 3095 3096 return QualType(TypeParm, 0); 3097} 3098 3099TypeSourceInfo * 3100ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name, 3101 SourceLocation NameLoc, 3102 const TemplateArgumentListInfo &Args, 3103 QualType Underlying) const { 3104 assert(!Name.getAsDependentTemplateName() && 3105 "No dependent template names here!"); 3106 QualType TST = getTemplateSpecializationType(Name, Args, Underlying); 3107 3108 TypeSourceInfo *DI = CreateTypeSourceInfo(TST); 3109 TemplateSpecializationTypeLoc TL = 3110 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>(); 3111 TL.setTemplateKeywordLoc(SourceLocation()); 3112 TL.setTemplateNameLoc(NameLoc); 3113 TL.setLAngleLoc(Args.getLAngleLoc()); 3114 TL.setRAngleLoc(Args.getRAngleLoc()); 3115 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 3116 TL.setArgLocInfo(i, Args[i].getLocInfo()); 3117 return DI; 3118} 3119 3120QualType 3121ASTContext::getTemplateSpecializationType(TemplateName Template, 3122 const TemplateArgumentListInfo &Args, 3123 QualType Underlying) const { 3124 assert(!Template.getAsDependentTemplateName() && 3125 "No dependent template names here!"); 3126 3127 unsigned NumArgs = Args.size(); 3128 3129 SmallVector<TemplateArgument, 4> ArgVec; 3130 ArgVec.reserve(NumArgs); 3131 for (unsigned i = 0; i != NumArgs; ++i) 3132 ArgVec.push_back(Args[i].getArgument()); 3133 3134 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, 3135 Underlying); 3136} 3137 3138#ifndef NDEBUG 3139static bool hasAnyPackExpansions(const TemplateArgument *Args, 3140 unsigned NumArgs) { 3141 for (unsigned I = 0; I != NumArgs; ++I) 3142 if (Args[I].isPackExpansion()) 3143 return true; 3144 3145 return true; 3146} 3147#endif 3148 3149QualType 3150ASTContext::getTemplateSpecializationType(TemplateName Template, 3151 const TemplateArgument *Args, 3152 unsigned NumArgs, 3153 QualType Underlying) const { 3154 assert(!Template.getAsDependentTemplateName() && 3155 "No dependent template names here!"); 3156 // Look through qualified template names. 3157 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 3158 Template = TemplateName(QTN->getTemplateDecl()); 3159 3160 bool IsTypeAlias = 3161 Template.getAsTemplateDecl() && 3162 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl()); 3163 QualType CanonType; 3164 if (!Underlying.isNull()) 3165 CanonType = getCanonicalType(Underlying); 3166 else { 3167 // We can get here with an alias template when the specialization contains 3168 // a pack expansion that does not match up with a parameter pack. 3169 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) && 3170 "Caller must compute aliased type"); 3171 IsTypeAlias = false; 3172 CanonType = getCanonicalTemplateSpecializationType(Template, Args, 3173 NumArgs); 3174 } 3175 3176 // Allocate the (non-canonical) template specialization type, but don't 3177 // try to unique it: these types typically have location information that 3178 // we don't unique and don't want to lose. 3179 void *Mem = Allocate(sizeof(TemplateSpecializationType) + 3180 sizeof(TemplateArgument) * NumArgs + 3181 (IsTypeAlias? sizeof(QualType) : 0), 3182 TypeAlignment); 3183 TemplateSpecializationType *Spec 3184 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType, 3185 IsTypeAlias ? Underlying : QualType()); 3186 3187 Types.push_back(Spec); 3188 return QualType(Spec, 0); 3189} 3190 3191QualType 3192ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template, 3193 const TemplateArgument *Args, 3194 unsigned NumArgs) const { 3195 assert(!Template.getAsDependentTemplateName() && 3196 "No dependent template names here!"); 3197 3198 // Look through qualified template names. 3199 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 3200 Template = TemplateName(QTN->getTemplateDecl()); 3201 3202 // Build the canonical template specialization type. 3203 TemplateName CanonTemplate = getCanonicalTemplateName(Template); 3204 SmallVector<TemplateArgument, 4> CanonArgs; 3205 CanonArgs.reserve(NumArgs); 3206 for (unsigned I = 0; I != NumArgs; ++I) 3207 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I])); 3208 3209 // Determine whether this canonical template specialization type already 3210 // exists. 3211 llvm::FoldingSetNodeID ID; 3212 TemplateSpecializationType::Profile(ID, CanonTemplate, 3213 CanonArgs.data(), NumArgs, *this); 3214 3215 void *InsertPos = 0; 3216 TemplateSpecializationType *Spec 3217 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 3218 3219 if (!Spec) { 3220 // Allocate a new canonical template specialization type. 3221 void *Mem = Allocate((sizeof(TemplateSpecializationType) + 3222 sizeof(TemplateArgument) * NumArgs), 3223 TypeAlignment); 3224 Spec = new (Mem) TemplateSpecializationType(CanonTemplate, 3225 CanonArgs.data(), NumArgs, 3226 QualType(), QualType()); 3227 Types.push_back(Spec); 3228 TemplateSpecializationTypes.InsertNode(Spec, InsertPos); 3229 } 3230 3231 assert(Spec->isDependentType() && 3232 "Non-dependent template-id type must have a canonical type"); 3233 return QualType(Spec, 0); 3234} 3235 3236QualType 3237ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword, 3238 NestedNameSpecifier *NNS, 3239 QualType NamedType) const { 3240 llvm::FoldingSetNodeID ID; 3241 ElaboratedType::Profile(ID, Keyword, NNS, NamedType); 3242 3243 void *InsertPos = 0; 3244 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 3245 if (T) 3246 return QualType(T, 0); 3247 3248 QualType Canon = NamedType; 3249 if (!Canon.isCanonical()) { 3250 Canon = getCanonicalType(NamedType); 3251 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 3252 assert(!CheckT && "Elaborated canonical type broken"); 3253 (void)CheckT; 3254 } 3255 3256 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon); 3257 Types.push_back(T); 3258 ElaboratedTypes.InsertNode(T, InsertPos); 3259 return QualType(T, 0); 3260} 3261 3262QualType 3263ASTContext::getParenType(QualType InnerType) const { 3264 llvm::FoldingSetNodeID ID; 3265 ParenType::Profile(ID, InnerType); 3266 3267 void *InsertPos = 0; 3268 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 3269 if (T) 3270 return QualType(T, 0); 3271 3272 QualType Canon = InnerType; 3273 if (!Canon.isCanonical()) { 3274 Canon = getCanonicalType(InnerType); 3275 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 3276 assert(!CheckT && "Paren canonical type broken"); 3277 (void)CheckT; 3278 } 3279 3280 T = new (*this) ParenType(InnerType, Canon); 3281 Types.push_back(T); 3282 ParenTypes.InsertNode(T, InsertPos); 3283 return QualType(T, 0); 3284} 3285 3286QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword, 3287 NestedNameSpecifier *NNS, 3288 const IdentifierInfo *Name, 3289 QualType Canon) const { 3290 assert(NNS->isDependent() && "nested-name-specifier must be dependent"); 3291 3292 if (Canon.isNull()) { 3293 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 3294 ElaboratedTypeKeyword CanonKeyword = Keyword; 3295 if (Keyword == ETK_None) 3296 CanonKeyword = ETK_Typename; 3297 3298 if (CanonNNS != NNS || CanonKeyword != Keyword) 3299 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name); 3300 } 3301 3302 llvm::FoldingSetNodeID ID; 3303 DependentNameType::Profile(ID, Keyword, NNS, Name); 3304 3305 void *InsertPos = 0; 3306 DependentNameType *T 3307 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos); 3308 if (T) 3309 return QualType(T, 0); 3310 3311 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon); 3312 Types.push_back(T); 3313 DependentNameTypes.InsertNode(T, InsertPos); 3314 return QualType(T, 0); 3315} 3316 3317QualType 3318ASTContext::getDependentTemplateSpecializationType( 3319 ElaboratedTypeKeyword Keyword, 3320 NestedNameSpecifier *NNS, 3321 const IdentifierInfo *Name, 3322 const TemplateArgumentListInfo &Args) const { 3323 // TODO: avoid this copy 3324 SmallVector<TemplateArgument, 16> ArgCopy; 3325 for (unsigned I = 0, E = Args.size(); I != E; ++I) 3326 ArgCopy.push_back(Args[I].getArgument()); 3327 return getDependentTemplateSpecializationType(Keyword, NNS, Name, 3328 ArgCopy.size(), 3329 ArgCopy.data()); 3330} 3331 3332QualType 3333ASTContext::getDependentTemplateSpecializationType( 3334 ElaboratedTypeKeyword Keyword, 3335 NestedNameSpecifier *NNS, 3336 const IdentifierInfo *Name, 3337 unsigned NumArgs, 3338 const TemplateArgument *Args) const { 3339 assert((!NNS || NNS->isDependent()) && 3340 "nested-name-specifier must be dependent"); 3341 3342 llvm::FoldingSetNodeID ID; 3343 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS, 3344 Name, NumArgs, Args); 3345 3346 void *InsertPos = 0; 3347 DependentTemplateSpecializationType *T 3348 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 3349 if (T) 3350 return QualType(T, 0); 3351 3352 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 3353 3354 ElaboratedTypeKeyword CanonKeyword = Keyword; 3355 if (Keyword == ETK_None) CanonKeyword = ETK_Typename; 3356 3357 bool AnyNonCanonArgs = false; 3358 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs); 3359 for (unsigned I = 0; I != NumArgs; ++I) { 3360 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]); 3361 if (!CanonArgs[I].structurallyEquals(Args[I])) 3362 AnyNonCanonArgs = true; 3363 } 3364 3365 QualType Canon; 3366 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) { 3367 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS, 3368 Name, NumArgs, 3369 CanonArgs.data()); 3370 3371 // Find the insert position again. 3372 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 3373 } 3374 3375 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) + 3376 sizeof(TemplateArgument) * NumArgs), 3377 TypeAlignment); 3378 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS, 3379 Name, NumArgs, Args, Canon); 3380 Types.push_back(T); 3381 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos); 3382 return QualType(T, 0); 3383} 3384 3385QualType ASTContext::getPackExpansionType(QualType Pattern, 3386 Optional<unsigned> NumExpansions) { 3387 llvm::FoldingSetNodeID ID; 3388 PackExpansionType::Profile(ID, Pattern, NumExpansions); 3389 3390 assert(Pattern->containsUnexpandedParameterPack() && 3391 "Pack expansions must expand one or more parameter packs"); 3392 void *InsertPos = 0; 3393 PackExpansionType *T 3394 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 3395 if (T) 3396 return QualType(T, 0); 3397 3398 QualType Canon; 3399 if (!Pattern.isCanonical()) { 3400 Canon = getCanonicalType(Pattern); 3401 // The canonical type might not contain an unexpanded parameter pack, if it 3402 // contains an alias template specialization which ignores one of its 3403 // parameters. 3404 if (Canon->containsUnexpandedParameterPack()) { 3405 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions); 3406 3407 // Find the insert position again, in case we inserted an element into 3408 // PackExpansionTypes and invalidated our insert position. 3409 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 3410 } 3411 } 3412 3413 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions); 3414 Types.push_back(T); 3415 PackExpansionTypes.InsertNode(T, InsertPos); 3416 return QualType(T, 0); 3417} 3418 3419/// CmpProtocolNames - Comparison predicate for sorting protocols 3420/// alphabetically. 3421static bool CmpProtocolNames(const ObjCProtocolDecl *LHS, 3422 const ObjCProtocolDecl *RHS) { 3423 return LHS->getDeclName() < RHS->getDeclName(); 3424} 3425 3426static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols, 3427 unsigned NumProtocols) { 3428 if (NumProtocols == 0) return true; 3429 3430 if (Protocols[0]->getCanonicalDecl() != Protocols[0]) 3431 return false; 3432 3433 for (unsigned i = 1; i != NumProtocols; ++i) 3434 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) || 3435 Protocols[i]->getCanonicalDecl() != Protocols[i]) 3436 return false; 3437 return true; 3438} 3439 3440static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols, 3441 unsigned &NumProtocols) { 3442 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols; 3443 3444 // Sort protocols, keyed by name. 3445 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames); 3446 3447 // Canonicalize. 3448 for (unsigned I = 0, N = NumProtocols; I != N; ++I) 3449 Protocols[I] = Protocols[I]->getCanonicalDecl(); 3450 3451 // Remove duplicates. 3452 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd); 3453 NumProtocols = ProtocolsEnd-Protocols; 3454} 3455 3456QualType ASTContext::getObjCObjectType(QualType BaseType, 3457 ObjCProtocolDecl * const *Protocols, 3458 unsigned NumProtocols) const { 3459 // If the base type is an interface and there aren't any protocols 3460 // to add, then the interface type will do just fine. 3461 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType)) 3462 return BaseType; 3463 3464 // Look in the folding set for an existing type. 3465 llvm::FoldingSetNodeID ID; 3466 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols); 3467 void *InsertPos = 0; 3468 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos)) 3469 return QualType(QT, 0); 3470 3471 // Build the canonical type, which has the canonical base type and 3472 // a sorted-and-uniqued list of protocols. 3473 QualType Canonical; 3474 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols); 3475 if (!ProtocolsSorted || !BaseType.isCanonical()) { 3476 if (!ProtocolsSorted) { 3477 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols, 3478 Protocols + NumProtocols); 3479 unsigned UniqueCount = NumProtocols; 3480 3481 SortAndUniqueProtocols(&Sorted[0], UniqueCount); 3482 Canonical = getObjCObjectType(getCanonicalType(BaseType), 3483 &Sorted[0], UniqueCount); 3484 } else { 3485 Canonical = getObjCObjectType(getCanonicalType(BaseType), 3486 Protocols, NumProtocols); 3487 } 3488 3489 // Regenerate InsertPos. 3490 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos); 3491 } 3492 3493 unsigned Size = sizeof(ObjCObjectTypeImpl); 3494 Size += NumProtocols * sizeof(ObjCProtocolDecl *); 3495 void *Mem = Allocate(Size, TypeAlignment); 3496 ObjCObjectTypeImpl *T = 3497 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols); 3498 3499 Types.push_back(T); 3500 ObjCObjectTypes.InsertNode(T, InsertPos); 3501 return QualType(T, 0); 3502} 3503 3504/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for 3505/// the given object type. 3506QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const { 3507 llvm::FoldingSetNodeID ID; 3508 ObjCObjectPointerType::Profile(ID, ObjectT); 3509 3510 void *InsertPos = 0; 3511 if (ObjCObjectPointerType *QT = 3512 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3513 return QualType(QT, 0); 3514 3515 // Find the canonical object type. 3516 QualType Canonical; 3517 if (!ObjectT.isCanonical()) { 3518 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT)); 3519 3520 // Regenerate InsertPos. 3521 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3522 } 3523 3524 // No match. 3525 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment); 3526 ObjCObjectPointerType *QType = 3527 new (Mem) ObjCObjectPointerType(Canonical, ObjectT); 3528 3529 Types.push_back(QType); 3530 ObjCObjectPointerTypes.InsertNode(QType, InsertPos); 3531 return QualType(QType, 0); 3532} 3533 3534/// getObjCInterfaceType - Return the unique reference to the type for the 3535/// specified ObjC interface decl. The list of protocols is optional. 3536QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl, 3537 ObjCInterfaceDecl *PrevDecl) const { 3538 if (Decl->TypeForDecl) 3539 return QualType(Decl->TypeForDecl, 0); 3540 3541 if (PrevDecl) { 3542 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl"); 3543 Decl->TypeForDecl = PrevDecl->TypeForDecl; 3544 return QualType(PrevDecl->TypeForDecl, 0); 3545 } 3546 3547 // Prefer the definition, if there is one. 3548 if (const ObjCInterfaceDecl *Def = Decl->getDefinition()) 3549 Decl = Def; 3550 3551 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment); 3552 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl); 3553 Decl->TypeForDecl = T; 3554 Types.push_back(T); 3555 return QualType(T, 0); 3556} 3557 3558/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique 3559/// TypeOfExprType AST's (since expression's are never shared). For example, 3560/// multiple declarations that refer to "typeof(x)" all contain different 3561/// DeclRefExpr's. This doesn't effect the type checker, since it operates 3562/// on canonical type's (which are always unique). 3563QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const { 3564 TypeOfExprType *toe; 3565 if (tofExpr->isTypeDependent()) { 3566 llvm::FoldingSetNodeID ID; 3567 DependentTypeOfExprType::Profile(ID, *this, tofExpr); 3568 3569 void *InsertPos = 0; 3570 DependentTypeOfExprType *Canon 3571 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos); 3572 if (Canon) { 3573 // We already have a "canonical" version of an identical, dependent 3574 // typeof(expr) type. Use that as our canonical type. 3575 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, 3576 QualType((TypeOfExprType*)Canon, 0)); 3577 } else { 3578 // Build a new, canonical typeof(expr) type. 3579 Canon 3580 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr); 3581 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos); 3582 toe = Canon; 3583 } 3584 } else { 3585 QualType Canonical = getCanonicalType(tofExpr->getType()); 3586 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical); 3587 } 3588 Types.push_back(toe); 3589 return QualType(toe, 0); 3590} 3591 3592/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique 3593/// TypeOfType AST's. The only motivation to unique these nodes would be 3594/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be 3595/// an issue. This doesn't effect the type checker, since it operates 3596/// on canonical type's (which are always unique). 3597QualType ASTContext::getTypeOfType(QualType tofType) const { 3598 QualType Canonical = getCanonicalType(tofType); 3599 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical); 3600 Types.push_back(tot); 3601 return QualType(tot, 0); 3602} 3603 3604 3605/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique 3606/// DecltypeType AST's. The only motivation to unique these nodes would be 3607/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be 3608/// an issue. This doesn't effect the type checker, since it operates 3609/// on canonical types (which are always unique). 3610QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const { 3611 DecltypeType *dt; 3612 3613 // C++0x [temp.type]p2: 3614 // If an expression e involves a template parameter, decltype(e) denotes a 3615 // unique dependent type. Two such decltype-specifiers refer to the same 3616 // type only if their expressions are equivalent (14.5.6.1). 3617 if (e->isInstantiationDependent()) { 3618 llvm::FoldingSetNodeID ID; 3619 DependentDecltypeType::Profile(ID, *this, e); 3620 3621 void *InsertPos = 0; 3622 DependentDecltypeType *Canon 3623 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos); 3624 if (Canon) { 3625 // We already have a "canonical" version of an equivalent, dependent 3626 // decltype type. Use that as our canonical type. 3627 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType, 3628 QualType((DecltypeType*)Canon, 0)); 3629 } else { 3630 // Build a new, canonical typeof(expr) type. 3631 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e); 3632 DependentDecltypeTypes.InsertNode(Canon, InsertPos); 3633 dt = Canon; 3634 } 3635 } else { 3636 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType, 3637 getCanonicalType(UnderlyingType)); 3638 } 3639 Types.push_back(dt); 3640 return QualType(dt, 0); 3641} 3642 3643/// getUnaryTransformationType - We don't unique these, since the memory 3644/// savings are minimal and these are rare. 3645QualType ASTContext::getUnaryTransformType(QualType BaseType, 3646 QualType UnderlyingType, 3647 UnaryTransformType::UTTKind Kind) 3648 const { 3649 UnaryTransformType *Ty = 3650 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType, 3651 Kind, 3652 UnderlyingType->isDependentType() ? 3653 QualType() : getCanonicalType(UnderlyingType)); 3654 Types.push_back(Ty); 3655 return QualType(Ty, 0); 3656} 3657 3658/// getAutoType - Return the uniqued reference to the 'auto' type which has been 3659/// deduced to the given type, or to the canonical undeduced 'auto' type, or the 3660/// canonical deduced-but-dependent 'auto' type. 3661QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto, 3662 bool IsDependent) const { 3663 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent) 3664 return getAutoDeductType(); 3665 3666 // Look in the folding set for an existing type. 3667 void *InsertPos = 0; 3668 llvm::FoldingSetNodeID ID; 3669 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent); 3670 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos)) 3671 return QualType(AT, 0); 3672 3673 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType, 3674 IsDecltypeAuto, 3675 IsDependent); 3676 Types.push_back(AT); 3677 if (InsertPos) 3678 AutoTypes.InsertNode(AT, InsertPos); 3679 return QualType(AT, 0); 3680} 3681 3682/// getAtomicType - Return the uniqued reference to the atomic type for 3683/// the given value type. 3684QualType ASTContext::getAtomicType(QualType T) const { 3685 // Unique pointers, to guarantee there is only one pointer of a particular 3686 // structure. 3687 llvm::FoldingSetNodeID ID; 3688 AtomicType::Profile(ID, T); 3689 3690 void *InsertPos = 0; 3691 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos)) 3692 return QualType(AT, 0); 3693 3694 // If the atomic value type isn't canonical, this won't be a canonical type 3695 // either, so fill in the canonical type field. 3696 QualType Canonical; 3697 if (!T.isCanonical()) { 3698 Canonical = getAtomicType(getCanonicalType(T)); 3699 3700 // Get the new insert position for the node we care about. 3701 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos); 3702 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 3703 } 3704 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical); 3705 Types.push_back(New); 3706 AtomicTypes.InsertNode(New, InsertPos); 3707 return QualType(New, 0); 3708} 3709 3710/// getAutoDeductType - Get type pattern for deducing against 'auto'. 3711QualType ASTContext::getAutoDeductType() const { 3712 if (AutoDeductTy.isNull()) 3713 AutoDeductTy = QualType( 3714 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false, 3715 /*dependent*/false), 3716 0); 3717 return AutoDeductTy; 3718} 3719 3720/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'. 3721QualType ASTContext::getAutoRRefDeductType() const { 3722 if (AutoRRefDeductTy.isNull()) 3723 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType()); 3724 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern"); 3725 return AutoRRefDeductTy; 3726} 3727 3728/// getTagDeclType - Return the unique reference to the type for the 3729/// specified TagDecl (struct/union/class/enum) decl. 3730QualType ASTContext::getTagDeclType(const TagDecl *Decl) const { 3731 assert (Decl); 3732 // FIXME: What is the design on getTagDeclType when it requires casting 3733 // away const? mutable? 3734 return getTypeDeclType(const_cast<TagDecl*>(Decl)); 3735} 3736 3737/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result 3738/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and 3739/// needs to agree with the definition in <stddef.h>. 3740CanQualType ASTContext::getSizeType() const { 3741 return getFromTargetType(Target->getSizeType()); 3742} 3743 3744/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5). 3745CanQualType ASTContext::getIntMaxType() const { 3746 return getFromTargetType(Target->getIntMaxType()); 3747} 3748 3749/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5). 3750CanQualType ASTContext::getUIntMaxType() const { 3751 return getFromTargetType(Target->getUIntMaxType()); 3752} 3753 3754/// getSignedWCharType - Return the type of "signed wchar_t". 3755/// Used when in C++, as a GCC extension. 3756QualType ASTContext::getSignedWCharType() const { 3757 // FIXME: derive from "Target" ? 3758 return WCharTy; 3759} 3760 3761/// getUnsignedWCharType - Return the type of "unsigned wchar_t". 3762/// Used when in C++, as a GCC extension. 3763QualType ASTContext::getUnsignedWCharType() const { 3764 // FIXME: derive from "Target" ? 3765 return UnsignedIntTy; 3766} 3767 3768QualType ASTContext::getIntPtrType() const { 3769 return getFromTargetType(Target->getIntPtrType()); 3770} 3771 3772QualType ASTContext::getUIntPtrType() const { 3773 return getCorrespondingUnsignedType(getIntPtrType()); 3774} 3775 3776/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17) 3777/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9). 3778QualType ASTContext::getPointerDiffType() const { 3779 return getFromTargetType(Target->getPtrDiffType(0)); 3780} 3781 3782/// \brief Return the unique type for "pid_t" defined in 3783/// <sys/types.h>. We need this to compute the correct type for vfork(). 3784QualType ASTContext::getProcessIDType() const { 3785 return getFromTargetType(Target->getProcessIDType()); 3786} 3787 3788//===----------------------------------------------------------------------===// 3789// Type Operators 3790//===----------------------------------------------------------------------===// 3791 3792CanQualType ASTContext::getCanonicalParamType(QualType T) const { 3793 // Push qualifiers into arrays, and then discard any remaining 3794 // qualifiers. 3795 T = getCanonicalType(T); 3796 T = getVariableArrayDecayedType(T); 3797 const Type *Ty = T.getTypePtr(); 3798 QualType Result; 3799 if (isa<ArrayType>(Ty)) { 3800 Result = getArrayDecayedType(QualType(Ty,0)); 3801 } else if (isa<FunctionType>(Ty)) { 3802 Result = getPointerType(QualType(Ty, 0)); 3803 } else { 3804 Result = QualType(Ty, 0); 3805 } 3806 3807 return CanQualType::CreateUnsafe(Result); 3808} 3809 3810QualType ASTContext::getUnqualifiedArrayType(QualType type, 3811 Qualifiers &quals) { 3812 SplitQualType splitType = type.getSplitUnqualifiedType(); 3813 3814 // FIXME: getSplitUnqualifiedType() actually walks all the way to 3815 // the unqualified desugared type and then drops it on the floor. 3816 // We then have to strip that sugar back off with 3817 // getUnqualifiedDesugaredType(), which is silly. 3818 const ArrayType *AT = 3819 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType()); 3820 3821 // If we don't have an array, just use the results in splitType. 3822 if (!AT) { 3823 quals = splitType.Quals; 3824 return QualType(splitType.Ty, 0); 3825 } 3826 3827 // Otherwise, recurse on the array's element type. 3828 QualType elementType = AT->getElementType(); 3829 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals); 3830 3831 // If that didn't change the element type, AT has no qualifiers, so we 3832 // can just use the results in splitType. 3833 if (elementType == unqualElementType) { 3834 assert(quals.empty()); // from the recursive call 3835 quals = splitType.Quals; 3836 return QualType(splitType.Ty, 0); 3837 } 3838 3839 // Otherwise, add in the qualifiers from the outermost type, then 3840 // build the type back up. 3841 quals.addConsistentQualifiers(splitType.Quals); 3842 3843 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) { 3844 return getConstantArrayType(unqualElementType, CAT->getSize(), 3845 CAT->getSizeModifier(), 0); 3846 } 3847 3848 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) { 3849 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0); 3850 } 3851 3852 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) { 3853 return getVariableArrayType(unqualElementType, 3854 VAT->getSizeExpr(), 3855 VAT->getSizeModifier(), 3856 VAT->getIndexTypeCVRQualifiers(), 3857 VAT->getBracketsRange()); 3858 } 3859 3860 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT); 3861 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(), 3862 DSAT->getSizeModifier(), 0, 3863 SourceRange()); 3864} 3865 3866/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that 3867/// may be similar (C++ 4.4), replaces T1 and T2 with the type that 3868/// they point to and return true. If T1 and T2 aren't pointer types 3869/// or pointer-to-member types, or if they are not similar at this 3870/// level, returns false and leaves T1 and T2 unchanged. Top-level 3871/// qualifiers on T1 and T2 are ignored. This function will typically 3872/// be called in a loop that successively "unwraps" pointer and 3873/// pointer-to-member types to compare them at each level. 3874bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) { 3875 const PointerType *T1PtrType = T1->getAs<PointerType>(), 3876 *T2PtrType = T2->getAs<PointerType>(); 3877 if (T1PtrType && T2PtrType) { 3878 T1 = T1PtrType->getPointeeType(); 3879 T2 = T2PtrType->getPointeeType(); 3880 return true; 3881 } 3882 3883 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(), 3884 *T2MPType = T2->getAs<MemberPointerType>(); 3885 if (T1MPType && T2MPType && 3886 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0), 3887 QualType(T2MPType->getClass(), 0))) { 3888 T1 = T1MPType->getPointeeType(); 3889 T2 = T2MPType->getPointeeType(); 3890 return true; 3891 } 3892 3893 if (getLangOpts().ObjC1) { 3894 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(), 3895 *T2OPType = T2->getAs<ObjCObjectPointerType>(); 3896 if (T1OPType && T2OPType) { 3897 T1 = T1OPType->getPointeeType(); 3898 T2 = T2OPType->getPointeeType(); 3899 return true; 3900 } 3901 } 3902 3903 // FIXME: Block pointers, too? 3904 3905 return false; 3906} 3907 3908DeclarationNameInfo 3909ASTContext::getNameForTemplate(TemplateName Name, 3910 SourceLocation NameLoc) const { 3911 switch (Name.getKind()) { 3912 case TemplateName::QualifiedTemplate: 3913 case TemplateName::Template: 3914 // DNInfo work in progress: CHECKME: what about DNLoc? 3915 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(), 3916 NameLoc); 3917 3918 case TemplateName::OverloadedTemplate: { 3919 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate(); 3920 // DNInfo work in progress: CHECKME: what about DNLoc? 3921 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc); 3922 } 3923 3924 case TemplateName::DependentTemplate: { 3925 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 3926 DeclarationName DName; 3927 if (DTN->isIdentifier()) { 3928 DName = DeclarationNames.getIdentifier(DTN->getIdentifier()); 3929 return DeclarationNameInfo(DName, NameLoc); 3930 } else { 3931 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator()); 3932 // DNInfo work in progress: FIXME: source locations? 3933 DeclarationNameLoc DNLoc; 3934 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding(); 3935 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding(); 3936 return DeclarationNameInfo(DName, NameLoc, DNLoc); 3937 } 3938 } 3939 3940 case TemplateName::SubstTemplateTemplateParm: { 3941 SubstTemplateTemplateParmStorage *subst 3942 = Name.getAsSubstTemplateTemplateParm(); 3943 return DeclarationNameInfo(subst->getParameter()->getDeclName(), 3944 NameLoc); 3945 } 3946 3947 case TemplateName::SubstTemplateTemplateParmPack: { 3948 SubstTemplateTemplateParmPackStorage *subst 3949 = Name.getAsSubstTemplateTemplateParmPack(); 3950 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(), 3951 NameLoc); 3952 } 3953 } 3954 3955 llvm_unreachable("bad template name kind!"); 3956} 3957 3958TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const { 3959 switch (Name.getKind()) { 3960 case TemplateName::QualifiedTemplate: 3961 case TemplateName::Template: { 3962 TemplateDecl *Template = Name.getAsTemplateDecl(); 3963 if (TemplateTemplateParmDecl *TTP 3964 = dyn_cast<TemplateTemplateParmDecl>(Template)) 3965 Template = getCanonicalTemplateTemplateParmDecl(TTP); 3966 3967 // The canonical template name is the canonical template declaration. 3968 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl())); 3969 } 3970 3971 case TemplateName::OverloadedTemplate: 3972 llvm_unreachable("cannot canonicalize overloaded template"); 3973 3974 case TemplateName::DependentTemplate: { 3975 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 3976 assert(DTN && "Non-dependent template names must refer to template decls."); 3977 return DTN->CanonicalTemplateName; 3978 } 3979 3980 case TemplateName::SubstTemplateTemplateParm: { 3981 SubstTemplateTemplateParmStorage *subst 3982 = Name.getAsSubstTemplateTemplateParm(); 3983 return getCanonicalTemplateName(subst->getReplacement()); 3984 } 3985 3986 case TemplateName::SubstTemplateTemplateParmPack: { 3987 SubstTemplateTemplateParmPackStorage *subst 3988 = Name.getAsSubstTemplateTemplateParmPack(); 3989 TemplateTemplateParmDecl *canonParameter 3990 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack()); 3991 TemplateArgument canonArgPack 3992 = getCanonicalTemplateArgument(subst->getArgumentPack()); 3993 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack); 3994 } 3995 } 3996 3997 llvm_unreachable("bad template name!"); 3998} 3999 4000bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) { 4001 X = getCanonicalTemplateName(X); 4002 Y = getCanonicalTemplateName(Y); 4003 return X.getAsVoidPointer() == Y.getAsVoidPointer(); 4004} 4005 4006TemplateArgument 4007ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const { 4008 switch (Arg.getKind()) { 4009 case TemplateArgument::Null: 4010 return Arg; 4011 4012 case TemplateArgument::Expression: 4013 return Arg; 4014 4015 case TemplateArgument::Declaration: { 4016 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl()); 4017 return TemplateArgument(D, Arg.isDeclForReferenceParam()); 4018 } 4019 4020 case TemplateArgument::NullPtr: 4021 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()), 4022 /*isNullPtr*/true); 4023 4024 case TemplateArgument::Template: 4025 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate())); 4026 4027 case TemplateArgument::TemplateExpansion: 4028 return TemplateArgument(getCanonicalTemplateName( 4029 Arg.getAsTemplateOrTemplatePattern()), 4030 Arg.getNumTemplateExpansions()); 4031 4032 case TemplateArgument::Integral: 4033 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType())); 4034 4035 case TemplateArgument::Type: 4036 return TemplateArgument(getCanonicalType(Arg.getAsType())); 4037 4038 case TemplateArgument::Pack: { 4039 if (Arg.pack_size() == 0) 4040 return Arg; 4041 4042 TemplateArgument *CanonArgs 4043 = new (*this) TemplateArgument[Arg.pack_size()]; 4044 unsigned Idx = 0; 4045 for (TemplateArgument::pack_iterator A = Arg.pack_begin(), 4046 AEnd = Arg.pack_end(); 4047 A != AEnd; (void)++A, ++Idx) 4048 CanonArgs[Idx] = getCanonicalTemplateArgument(*A); 4049 4050 return TemplateArgument(CanonArgs, Arg.pack_size()); 4051 } 4052 } 4053 4054 // Silence GCC warning 4055 llvm_unreachable("Unhandled template argument kind"); 4056} 4057 4058NestedNameSpecifier * 4059ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const { 4060 if (!NNS) 4061 return 0; 4062 4063 switch (NNS->getKind()) { 4064 case NestedNameSpecifier::Identifier: 4065 // Canonicalize the prefix but keep the identifier the same. 4066 return NestedNameSpecifier::Create(*this, 4067 getCanonicalNestedNameSpecifier(NNS->getPrefix()), 4068 NNS->getAsIdentifier()); 4069 4070 case NestedNameSpecifier::Namespace: 4071 // A namespace is canonical; build a nested-name-specifier with 4072 // this namespace and no prefix. 4073 return NestedNameSpecifier::Create(*this, 0, 4074 NNS->getAsNamespace()->getOriginalNamespace()); 4075 4076 case NestedNameSpecifier::NamespaceAlias: 4077 // A namespace is canonical; build a nested-name-specifier with 4078 // this namespace and no prefix. 4079 return NestedNameSpecifier::Create(*this, 0, 4080 NNS->getAsNamespaceAlias()->getNamespace() 4081 ->getOriginalNamespace()); 4082 4083 case NestedNameSpecifier::TypeSpec: 4084 case NestedNameSpecifier::TypeSpecWithTemplate: { 4085 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0)); 4086 4087 // If we have some kind of dependent-named type (e.g., "typename T::type"), 4088 // break it apart into its prefix and identifier, then reconsititute those 4089 // as the canonical nested-name-specifier. This is required to canonicalize 4090 // a dependent nested-name-specifier involving typedefs of dependent-name 4091 // types, e.g., 4092 // typedef typename T::type T1; 4093 // typedef typename T1::type T2; 4094 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) 4095 return NestedNameSpecifier::Create(*this, DNT->getQualifier(), 4096 const_cast<IdentifierInfo *>(DNT->getIdentifier())); 4097 4098 // Otherwise, just canonicalize the type, and force it to be a TypeSpec. 4099 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the 4100 // first place? 4101 return NestedNameSpecifier::Create(*this, 0, false, 4102 const_cast<Type*>(T.getTypePtr())); 4103 } 4104 4105 case NestedNameSpecifier::Global: 4106 // The global specifier is canonical and unique. 4107 return NNS; 4108 } 4109 4110 llvm_unreachable("Invalid NestedNameSpecifier::Kind!"); 4111} 4112 4113 4114const ArrayType *ASTContext::getAsArrayType(QualType T) const { 4115 // Handle the non-qualified case efficiently. 4116 if (!T.hasLocalQualifiers()) { 4117 // Handle the common positive case fast. 4118 if (const ArrayType *AT = dyn_cast<ArrayType>(T)) 4119 return AT; 4120 } 4121 4122 // Handle the common negative case fast. 4123 if (!isa<ArrayType>(T.getCanonicalType())) 4124 return 0; 4125 4126 // Apply any qualifiers from the array type to the element type. This 4127 // implements C99 6.7.3p8: "If the specification of an array type includes 4128 // any type qualifiers, the element type is so qualified, not the array type." 4129 4130 // If we get here, we either have type qualifiers on the type, or we have 4131 // sugar such as a typedef in the way. If we have type qualifiers on the type 4132 // we must propagate them down into the element type. 4133 4134 SplitQualType split = T.getSplitDesugaredType(); 4135 Qualifiers qs = split.Quals; 4136 4137 // If we have a simple case, just return now. 4138 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty); 4139 if (ATy == 0 || qs.empty()) 4140 return ATy; 4141 4142 // Otherwise, we have an array and we have qualifiers on it. Push the 4143 // qualifiers into the array element type and return a new array type. 4144 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs); 4145 4146 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy)) 4147 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(), 4148 CAT->getSizeModifier(), 4149 CAT->getIndexTypeCVRQualifiers())); 4150 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy)) 4151 return cast<ArrayType>(getIncompleteArrayType(NewEltTy, 4152 IAT->getSizeModifier(), 4153 IAT->getIndexTypeCVRQualifiers())); 4154 4155 if (const DependentSizedArrayType *DSAT 4156 = dyn_cast<DependentSizedArrayType>(ATy)) 4157 return cast<ArrayType>( 4158 getDependentSizedArrayType(NewEltTy, 4159 DSAT->getSizeExpr(), 4160 DSAT->getSizeModifier(), 4161 DSAT->getIndexTypeCVRQualifiers(), 4162 DSAT->getBracketsRange())); 4163 4164 const VariableArrayType *VAT = cast<VariableArrayType>(ATy); 4165 return cast<ArrayType>(getVariableArrayType(NewEltTy, 4166 VAT->getSizeExpr(), 4167 VAT->getSizeModifier(), 4168 VAT->getIndexTypeCVRQualifiers(), 4169 VAT->getBracketsRange())); 4170} 4171 4172QualType ASTContext::getAdjustedParameterType(QualType T) const { 4173 if (T->isArrayType() || T->isFunctionType()) 4174 return getDecayedType(T); 4175 return T; 4176} 4177 4178QualType ASTContext::getSignatureParameterType(QualType T) const { 4179 T = getVariableArrayDecayedType(T); 4180 T = getAdjustedParameterType(T); 4181 return T.getUnqualifiedType(); 4182} 4183 4184/// getArrayDecayedType - Return the properly qualified result of decaying the 4185/// specified array type to a pointer. This operation is non-trivial when 4186/// handling typedefs etc. The canonical type of "T" must be an array type, 4187/// this returns a pointer to a properly qualified element of the array. 4188/// 4189/// See C99 6.7.5.3p7 and C99 6.3.2.1p3. 4190QualType ASTContext::getArrayDecayedType(QualType Ty) const { 4191 // Get the element type with 'getAsArrayType' so that we don't lose any 4192 // typedefs in the element type of the array. This also handles propagation 4193 // of type qualifiers from the array type into the element type if present 4194 // (C99 6.7.3p8). 4195 const ArrayType *PrettyArrayType = getAsArrayType(Ty); 4196 assert(PrettyArrayType && "Not an array type!"); 4197 4198 QualType PtrTy = getPointerType(PrettyArrayType->getElementType()); 4199 4200 // int x[restrict 4] -> int *restrict 4201 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers()); 4202} 4203 4204QualType ASTContext::getBaseElementType(const ArrayType *array) const { 4205 return getBaseElementType(array->getElementType()); 4206} 4207 4208QualType ASTContext::getBaseElementType(QualType type) const { 4209 Qualifiers qs; 4210 while (true) { 4211 SplitQualType split = type.getSplitDesugaredType(); 4212 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe(); 4213 if (!array) break; 4214 4215 type = array->getElementType(); 4216 qs.addConsistentQualifiers(split.Quals); 4217 } 4218 4219 return getQualifiedType(type, qs); 4220} 4221 4222/// getConstantArrayElementCount - Returns number of constant array elements. 4223uint64_t 4224ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const { 4225 uint64_t ElementCount = 1; 4226 do { 4227 ElementCount *= CA->getSize().getZExtValue(); 4228 CA = dyn_cast_or_null<ConstantArrayType>( 4229 CA->getElementType()->getAsArrayTypeUnsafe()); 4230 } while (CA); 4231 return ElementCount; 4232} 4233 4234/// getFloatingRank - Return a relative rank for floating point types. 4235/// This routine will assert if passed a built-in type that isn't a float. 4236static FloatingRank getFloatingRank(QualType T) { 4237 if (const ComplexType *CT = T->getAs<ComplexType>()) 4238 return getFloatingRank(CT->getElementType()); 4239 4240 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type"); 4241 switch (T->getAs<BuiltinType>()->getKind()) { 4242 default: llvm_unreachable("getFloatingRank(): not a floating type"); 4243 case BuiltinType::Half: return HalfRank; 4244 case BuiltinType::Float: return FloatRank; 4245 case BuiltinType::Double: return DoubleRank; 4246 case BuiltinType::LongDouble: return LongDoubleRank; 4247 } 4248} 4249 4250/// getFloatingTypeOfSizeWithinDomain - Returns a real floating 4251/// point or a complex type (based on typeDomain/typeSize). 4252/// 'typeDomain' is a real floating point or complex type. 4253/// 'typeSize' is a real floating point or complex type. 4254QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size, 4255 QualType Domain) const { 4256 FloatingRank EltRank = getFloatingRank(Size); 4257 if (Domain->isComplexType()) { 4258 switch (EltRank) { 4259 case HalfRank: llvm_unreachable("Complex half is not supported"); 4260 case FloatRank: return FloatComplexTy; 4261 case DoubleRank: return DoubleComplexTy; 4262 case LongDoubleRank: return LongDoubleComplexTy; 4263 } 4264 } 4265 4266 assert(Domain->isRealFloatingType() && "Unknown domain!"); 4267 switch (EltRank) { 4268 case HalfRank: return HalfTy; 4269 case FloatRank: return FloatTy; 4270 case DoubleRank: return DoubleTy; 4271 case LongDoubleRank: return LongDoubleTy; 4272 } 4273 llvm_unreachable("getFloatingRank(): illegal value for rank"); 4274} 4275 4276/// getFloatingTypeOrder - Compare the rank of the two specified floating 4277/// point types, ignoring the domain of the type (i.e. 'double' == 4278/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If 4279/// LHS < RHS, return -1. 4280int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const { 4281 FloatingRank LHSR = getFloatingRank(LHS); 4282 FloatingRank RHSR = getFloatingRank(RHS); 4283 4284 if (LHSR == RHSR) 4285 return 0; 4286 if (LHSR > RHSR) 4287 return 1; 4288 return -1; 4289} 4290 4291/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This 4292/// routine will assert if passed a built-in type that isn't an integer or enum, 4293/// or if it is not canonicalized. 4294unsigned ASTContext::getIntegerRank(const Type *T) const { 4295 assert(T->isCanonicalUnqualified() && "T should be canonicalized"); 4296 4297 switch (cast<BuiltinType>(T)->getKind()) { 4298 default: llvm_unreachable("getIntegerRank(): not a built-in integer"); 4299 case BuiltinType::Bool: 4300 return 1 + (getIntWidth(BoolTy) << 3); 4301 case BuiltinType::Char_S: 4302 case BuiltinType::Char_U: 4303 case BuiltinType::SChar: 4304 case BuiltinType::UChar: 4305 return 2 + (getIntWidth(CharTy) << 3); 4306 case BuiltinType::Short: 4307 case BuiltinType::UShort: 4308 return 3 + (getIntWidth(ShortTy) << 3); 4309 case BuiltinType::Int: 4310 case BuiltinType::UInt: 4311 return 4 + (getIntWidth(IntTy) << 3); 4312 case BuiltinType::Long: 4313 case BuiltinType::ULong: 4314 return 5 + (getIntWidth(LongTy) << 3); 4315 case BuiltinType::LongLong: 4316 case BuiltinType::ULongLong: 4317 return 6 + (getIntWidth(LongLongTy) << 3); 4318 case BuiltinType::Int128: 4319 case BuiltinType::UInt128: 4320 return 7 + (getIntWidth(Int128Ty) << 3); 4321 } 4322} 4323 4324/// \brief Whether this is a promotable bitfield reference according 4325/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions). 4326/// 4327/// \returns the type this bit-field will promote to, or NULL if no 4328/// promotion occurs. 4329QualType ASTContext::isPromotableBitField(Expr *E) const { 4330 if (E->isTypeDependent() || E->isValueDependent()) 4331 return QualType(); 4332 4333 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields? 4334 if (!Field) 4335 return QualType(); 4336 4337 QualType FT = Field->getType(); 4338 4339 uint64_t BitWidth = Field->getBitWidthValue(*this); 4340 uint64_t IntSize = getTypeSize(IntTy); 4341 // GCC extension compatibility: if the bit-field size is less than or equal 4342 // to the size of int, it gets promoted no matter what its type is. 4343 // For instance, unsigned long bf : 4 gets promoted to signed int. 4344 if (BitWidth < IntSize) 4345 return IntTy; 4346 4347 if (BitWidth == IntSize) 4348 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy; 4349 4350 // Types bigger than int are not subject to promotions, and therefore act 4351 // like the base type. 4352 // FIXME: This doesn't quite match what gcc does, but what gcc does here 4353 // is ridiculous. 4354 return QualType(); 4355} 4356 4357/// getPromotedIntegerType - Returns the type that Promotable will 4358/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable 4359/// integer type. 4360QualType ASTContext::getPromotedIntegerType(QualType Promotable) const { 4361 assert(!Promotable.isNull()); 4362 assert(Promotable->isPromotableIntegerType()); 4363 if (const EnumType *ET = Promotable->getAs<EnumType>()) 4364 return ET->getDecl()->getPromotionType(); 4365 4366 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) { 4367 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t 4368 // (3.9.1) can be converted to a prvalue of the first of the following 4369 // types that can represent all the values of its underlying type: 4370 // int, unsigned int, long int, unsigned long int, long long int, or 4371 // unsigned long long int [...] 4372 // FIXME: Is there some better way to compute this? 4373 if (BT->getKind() == BuiltinType::WChar_S || 4374 BT->getKind() == BuiltinType::WChar_U || 4375 BT->getKind() == BuiltinType::Char16 || 4376 BT->getKind() == BuiltinType::Char32) { 4377 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S; 4378 uint64_t FromSize = getTypeSize(BT); 4379 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy, 4380 LongLongTy, UnsignedLongLongTy }; 4381 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) { 4382 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]); 4383 if (FromSize < ToSize || 4384 (FromSize == ToSize && 4385 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) 4386 return PromoteTypes[Idx]; 4387 } 4388 llvm_unreachable("char type should fit into long long"); 4389 } 4390 } 4391 4392 // At this point, we should have a signed or unsigned integer type. 4393 if (Promotable->isSignedIntegerType()) 4394 return IntTy; 4395 uint64_t PromotableSize = getIntWidth(Promotable); 4396 uint64_t IntSize = getIntWidth(IntTy); 4397 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize); 4398 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy; 4399} 4400 4401/// \brief Recurses in pointer/array types until it finds an objc retainable 4402/// type and returns its ownership. 4403Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const { 4404 while (!T.isNull()) { 4405 if (T.getObjCLifetime() != Qualifiers::OCL_None) 4406 return T.getObjCLifetime(); 4407 if (T->isArrayType()) 4408 T = getBaseElementType(T); 4409 else if (const PointerType *PT = T->getAs<PointerType>()) 4410 T = PT->getPointeeType(); 4411 else if (const ReferenceType *RT = T->getAs<ReferenceType>()) 4412 T = RT->getPointeeType(); 4413 else 4414 break; 4415 } 4416 4417 return Qualifiers::OCL_None; 4418} 4419 4420/// getIntegerTypeOrder - Returns the highest ranked integer type: 4421/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If 4422/// LHS < RHS, return -1. 4423int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const { 4424 const Type *LHSC = getCanonicalType(LHS).getTypePtr(); 4425 const Type *RHSC = getCanonicalType(RHS).getTypePtr(); 4426 if (LHSC == RHSC) return 0; 4427 4428 bool LHSUnsigned = LHSC->isUnsignedIntegerType(); 4429 bool RHSUnsigned = RHSC->isUnsignedIntegerType(); 4430 4431 unsigned LHSRank = getIntegerRank(LHSC); 4432 unsigned RHSRank = getIntegerRank(RHSC); 4433 4434 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned. 4435 if (LHSRank == RHSRank) return 0; 4436 return LHSRank > RHSRank ? 1 : -1; 4437 } 4438 4439 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa. 4440 if (LHSUnsigned) { 4441 // If the unsigned [LHS] type is larger, return it. 4442 if (LHSRank >= RHSRank) 4443 return 1; 4444 4445 // If the signed type can represent all values of the unsigned type, it 4446 // wins. Because we are dealing with 2's complement and types that are 4447 // powers of two larger than each other, this is always safe. 4448 return -1; 4449 } 4450 4451 // If the unsigned [RHS] type is larger, return it. 4452 if (RHSRank >= LHSRank) 4453 return -1; 4454 4455 // If the signed type can represent all values of the unsigned type, it 4456 // wins. Because we are dealing with 2's complement and types that are 4457 // powers of two larger than each other, this is always safe. 4458 return 1; 4459} 4460 4461static RecordDecl * 4462CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK, 4463 DeclContext *DC, IdentifierInfo *Id) { 4464 SourceLocation Loc; 4465 if (Ctx.getLangOpts().CPlusPlus) 4466 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id); 4467 else 4468 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id); 4469} 4470 4471// getCFConstantStringType - Return the type used for constant CFStrings. 4472QualType ASTContext::getCFConstantStringType() const { 4473 if (!CFConstantStringTypeDecl) { 4474 CFConstantStringTypeDecl = 4475 CreateRecordDecl(*this, TTK_Struct, TUDecl, 4476 &Idents.get("NSConstantString")); 4477 CFConstantStringTypeDecl->startDefinition(); 4478 4479 QualType FieldTypes[4]; 4480 4481 // const int *isa; 4482 FieldTypes[0] = getPointerType(IntTy.withConst()); 4483 // int flags; 4484 FieldTypes[1] = IntTy; 4485 // const char *str; 4486 FieldTypes[2] = getPointerType(CharTy.withConst()); 4487 // long length; 4488 FieldTypes[3] = LongTy; 4489 4490 // Create fields 4491 for (unsigned i = 0; i < 4; ++i) { 4492 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl, 4493 SourceLocation(), 4494 SourceLocation(), 0, 4495 FieldTypes[i], /*TInfo=*/0, 4496 /*BitWidth=*/0, 4497 /*Mutable=*/false, 4498 ICIS_NoInit); 4499 Field->setAccess(AS_public); 4500 CFConstantStringTypeDecl->addDecl(Field); 4501 } 4502 4503 CFConstantStringTypeDecl->completeDefinition(); 4504 } 4505 4506 return getTagDeclType(CFConstantStringTypeDecl); 4507} 4508 4509QualType ASTContext::getObjCSuperType() const { 4510 if (ObjCSuperType.isNull()) { 4511 RecordDecl *ObjCSuperTypeDecl = 4512 CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get("objc_super")); 4513 TUDecl->addDecl(ObjCSuperTypeDecl); 4514 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl); 4515 } 4516 return ObjCSuperType; 4517} 4518 4519void ASTContext::setCFConstantStringType(QualType T) { 4520 const RecordType *Rec = T->getAs<RecordType>(); 4521 assert(Rec && "Invalid CFConstantStringType"); 4522 CFConstantStringTypeDecl = Rec->getDecl(); 4523} 4524 4525QualType ASTContext::getBlockDescriptorType() const { 4526 if (BlockDescriptorType) 4527 return getTagDeclType(BlockDescriptorType); 4528 4529 RecordDecl *T; 4530 // FIXME: Needs the FlagAppleBlock bit. 4531 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, 4532 &Idents.get("__block_descriptor")); 4533 T->startDefinition(); 4534 4535 QualType FieldTypes[] = { 4536 UnsignedLongTy, 4537 UnsignedLongTy, 4538 }; 4539 4540 static const char *const FieldNames[] = { 4541 "reserved", 4542 "Size" 4543 }; 4544 4545 for (size_t i = 0; i < 2; ++i) { 4546 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(), 4547 SourceLocation(), 4548 &Idents.get(FieldNames[i]), 4549 FieldTypes[i], /*TInfo=*/0, 4550 /*BitWidth=*/0, 4551 /*Mutable=*/false, 4552 ICIS_NoInit); 4553 Field->setAccess(AS_public); 4554 T->addDecl(Field); 4555 } 4556 4557 T->completeDefinition(); 4558 4559 BlockDescriptorType = T; 4560 4561 return getTagDeclType(BlockDescriptorType); 4562} 4563 4564QualType ASTContext::getBlockDescriptorExtendedType() const { 4565 if (BlockDescriptorExtendedType) 4566 return getTagDeclType(BlockDescriptorExtendedType); 4567 4568 RecordDecl *T; 4569 // FIXME: Needs the FlagAppleBlock bit. 4570 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, 4571 &Idents.get("__block_descriptor_withcopydispose")); 4572 T->startDefinition(); 4573 4574 QualType FieldTypes[] = { 4575 UnsignedLongTy, 4576 UnsignedLongTy, 4577 getPointerType(VoidPtrTy), 4578 getPointerType(VoidPtrTy) 4579 }; 4580 4581 static const char *const FieldNames[] = { 4582 "reserved", 4583 "Size", 4584 "CopyFuncPtr", 4585 "DestroyFuncPtr" 4586 }; 4587 4588 for (size_t i = 0; i < 4; ++i) { 4589 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(), 4590 SourceLocation(), 4591 &Idents.get(FieldNames[i]), 4592 FieldTypes[i], /*TInfo=*/0, 4593 /*BitWidth=*/0, 4594 /*Mutable=*/false, 4595 ICIS_NoInit); 4596 Field->setAccess(AS_public); 4597 T->addDecl(Field); 4598 } 4599 4600 T->completeDefinition(); 4601 4602 BlockDescriptorExtendedType = T; 4603 4604 return getTagDeclType(BlockDescriptorExtendedType); 4605} 4606 4607/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty" 4608/// requires copy/dispose. Note that this must match the logic 4609/// in buildByrefHelpers. 4610bool ASTContext::BlockRequiresCopying(QualType Ty, 4611 const VarDecl *D) { 4612 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) { 4613 const Expr *copyExpr = getBlockVarCopyInits(D); 4614 if (!copyExpr && record->hasTrivialDestructor()) return false; 4615 4616 return true; 4617 } 4618 4619 if (!Ty->isObjCRetainableType()) return false; 4620 4621 Qualifiers qs = Ty.getQualifiers(); 4622 4623 // If we have lifetime, that dominates. 4624 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) { 4625 assert(getLangOpts().ObjCAutoRefCount); 4626 4627 switch (lifetime) { 4628 case Qualifiers::OCL_None: llvm_unreachable("impossible"); 4629 4630 // These are just bits as far as the runtime is concerned. 4631 case Qualifiers::OCL_ExplicitNone: 4632 case Qualifiers::OCL_Autoreleasing: 4633 return false; 4634 4635 // Tell the runtime that this is ARC __weak, called by the 4636 // byref routines. 4637 case Qualifiers::OCL_Weak: 4638 // ARC __strong __block variables need to be retained. 4639 case Qualifiers::OCL_Strong: 4640 return true; 4641 } 4642 llvm_unreachable("fell out of lifetime switch!"); 4643 } 4644 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) || 4645 Ty->isObjCObjectPointerType()); 4646} 4647 4648bool ASTContext::getByrefLifetime(QualType Ty, 4649 Qualifiers::ObjCLifetime &LifeTime, 4650 bool &HasByrefExtendedLayout) const { 4651 4652 if (!getLangOpts().ObjC1 || 4653 getLangOpts().getGC() != LangOptions::NonGC) 4654 return false; 4655 4656 HasByrefExtendedLayout = false; 4657 if (Ty->isRecordType()) { 4658 HasByrefExtendedLayout = true; 4659 LifeTime = Qualifiers::OCL_None; 4660 } 4661 else if (getLangOpts().ObjCAutoRefCount) 4662 LifeTime = Ty.getObjCLifetime(); 4663 // MRR. 4664 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) 4665 LifeTime = Qualifiers::OCL_ExplicitNone; 4666 else 4667 LifeTime = Qualifiers::OCL_None; 4668 return true; 4669} 4670 4671TypedefDecl *ASTContext::getObjCInstanceTypeDecl() { 4672 if (!ObjCInstanceTypeDecl) 4673 ObjCInstanceTypeDecl = TypedefDecl::Create(*this, 4674 getTranslationUnitDecl(), 4675 SourceLocation(), 4676 SourceLocation(), 4677 &Idents.get("instancetype"), 4678 getTrivialTypeSourceInfo(getObjCIdType())); 4679 return ObjCInstanceTypeDecl; 4680} 4681 4682// This returns true if a type has been typedefed to BOOL: 4683// typedef <type> BOOL; 4684static bool isTypeTypedefedAsBOOL(QualType T) { 4685 if (const TypedefType *TT = dyn_cast<TypedefType>(T)) 4686 if (IdentifierInfo *II = TT->getDecl()->getIdentifier()) 4687 return II->isStr("BOOL"); 4688 4689 return false; 4690} 4691 4692/// getObjCEncodingTypeSize returns size of type for objective-c encoding 4693/// purpose. 4694CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const { 4695 if (!type->isIncompleteArrayType() && type->isIncompleteType()) 4696 return CharUnits::Zero(); 4697 4698 CharUnits sz = getTypeSizeInChars(type); 4699 4700 // Make all integer and enum types at least as large as an int 4701 if (sz.isPositive() && type->isIntegralOrEnumerationType()) 4702 sz = std::max(sz, getTypeSizeInChars(IntTy)); 4703 // Treat arrays as pointers, since that's how they're passed in. 4704 else if (type->isArrayType()) 4705 sz = getTypeSizeInChars(VoidPtrTy); 4706 return sz; 4707} 4708 4709static inline 4710std::string charUnitsToString(const CharUnits &CU) { 4711 return llvm::itostr(CU.getQuantity()); 4712} 4713 4714/// getObjCEncodingForBlock - Return the encoded type for this block 4715/// declaration. 4716std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const { 4717 std::string S; 4718 4719 const BlockDecl *Decl = Expr->getBlockDecl(); 4720 QualType BlockTy = 4721 Expr->getType()->getAs<BlockPointerType>()->getPointeeType(); 4722 // Encode result type. 4723 if (getLangOpts().EncodeExtendedBlockSig) 4724 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, 4725 BlockTy->getAs<FunctionType>()->getResultType(), 4726 S, true /*Extended*/); 4727 else 4728 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), 4729 S); 4730 // Compute size of all parameters. 4731 // Start with computing size of a pointer in number of bytes. 4732 // FIXME: There might(should) be a better way of doing this computation! 4733 SourceLocation Loc; 4734 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 4735 CharUnits ParmOffset = PtrSize; 4736 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), 4737 E = Decl->param_end(); PI != E; ++PI) { 4738 QualType PType = (*PI)->getType(); 4739 CharUnits sz = getObjCEncodingTypeSize(PType); 4740 if (sz.isZero()) 4741 continue; 4742 assert (sz.isPositive() && "BlockExpr - Incomplete param type"); 4743 ParmOffset += sz; 4744 } 4745 // Size of the argument frame 4746 S += charUnitsToString(ParmOffset); 4747 // Block pointer and offset. 4748 S += "@?0"; 4749 4750 // Argument types. 4751 ParmOffset = PtrSize; 4752 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E = 4753 Decl->param_end(); PI != E; ++PI) { 4754 ParmVarDecl *PVDecl = *PI; 4755 QualType PType = PVDecl->getOriginalType(); 4756 if (const ArrayType *AT = 4757 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 4758 // Use array's original type only if it has known number of 4759 // elements. 4760 if (!isa<ConstantArrayType>(AT)) 4761 PType = PVDecl->getType(); 4762 } else if (PType->isFunctionType()) 4763 PType = PVDecl->getType(); 4764 if (getLangOpts().EncodeExtendedBlockSig) 4765 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType, 4766 S, true /*Extended*/); 4767 else 4768 getObjCEncodingForType(PType, S); 4769 S += charUnitsToString(ParmOffset); 4770 ParmOffset += getObjCEncodingTypeSize(PType); 4771 } 4772 4773 return S; 4774} 4775 4776bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl, 4777 std::string& S) { 4778 // Encode result type. 4779 getObjCEncodingForType(Decl->getResultType(), S); 4780 CharUnits ParmOffset; 4781 // Compute size of all parameters. 4782 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(), 4783 E = Decl->param_end(); PI != E; ++PI) { 4784 QualType PType = (*PI)->getType(); 4785 CharUnits sz = getObjCEncodingTypeSize(PType); 4786 if (sz.isZero()) 4787 continue; 4788 4789 assert (sz.isPositive() && 4790 "getObjCEncodingForFunctionDecl - Incomplete param type"); 4791 ParmOffset += sz; 4792 } 4793 S += charUnitsToString(ParmOffset); 4794 ParmOffset = CharUnits::Zero(); 4795 4796 // Argument types. 4797 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(), 4798 E = Decl->param_end(); PI != E; ++PI) { 4799 ParmVarDecl *PVDecl = *PI; 4800 QualType PType = PVDecl->getOriginalType(); 4801 if (const ArrayType *AT = 4802 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 4803 // Use array's original type only if it has known number of 4804 // elements. 4805 if (!isa<ConstantArrayType>(AT)) 4806 PType = PVDecl->getType(); 4807 } else if (PType->isFunctionType()) 4808 PType = PVDecl->getType(); 4809 getObjCEncodingForType(PType, S); 4810 S += charUnitsToString(ParmOffset); 4811 ParmOffset += getObjCEncodingTypeSize(PType); 4812 } 4813 4814 return false; 4815} 4816 4817/// getObjCEncodingForMethodParameter - Return the encoded type for a single 4818/// method parameter or return type. If Extended, include class names and 4819/// block object types. 4820void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, 4821 QualType T, std::string& S, 4822 bool Extended) const { 4823 // Encode type qualifer, 'in', 'inout', etc. for the parameter. 4824 getObjCEncodingForTypeQualifier(QT, S); 4825 // Encode parameter type. 4826 getObjCEncodingForTypeImpl(T, S, true, true, 0, 4827 true /*OutermostType*/, 4828 false /*EncodingProperty*/, 4829 false /*StructField*/, 4830 Extended /*EncodeBlockParameters*/, 4831 Extended /*EncodeClassNames*/); 4832} 4833 4834/// getObjCEncodingForMethodDecl - Return the encoded type for this method 4835/// declaration. 4836bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, 4837 std::string& S, 4838 bool Extended) const { 4839 // FIXME: This is not very efficient. 4840 // Encode return type. 4841 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(), 4842 Decl->getResultType(), S, Extended); 4843 // Compute size of all parameters. 4844 // Start with computing size of a pointer in number of bytes. 4845 // FIXME: There might(should) be a better way of doing this computation! 4846 SourceLocation Loc; 4847 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 4848 // The first two arguments (self and _cmd) are pointers; account for 4849 // their size. 4850 CharUnits ParmOffset = 2 * PtrSize; 4851 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 4852 E = Decl->sel_param_end(); PI != E; ++PI) { 4853 QualType PType = (*PI)->getType(); 4854 CharUnits sz = getObjCEncodingTypeSize(PType); 4855 if (sz.isZero()) 4856 continue; 4857 4858 assert (sz.isPositive() && 4859 "getObjCEncodingForMethodDecl - Incomplete param type"); 4860 ParmOffset += sz; 4861 } 4862 S += charUnitsToString(ParmOffset); 4863 S += "@0:"; 4864 S += charUnitsToString(PtrSize); 4865 4866 // Argument types. 4867 ParmOffset = 2 * PtrSize; 4868 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 4869 E = Decl->sel_param_end(); PI != E; ++PI) { 4870 const ParmVarDecl *PVDecl = *PI; 4871 QualType PType = PVDecl->getOriginalType(); 4872 if (const ArrayType *AT = 4873 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 4874 // Use array's original type only if it has known number of 4875 // elements. 4876 if (!isa<ConstantArrayType>(AT)) 4877 PType = PVDecl->getType(); 4878 } else if (PType->isFunctionType()) 4879 PType = PVDecl->getType(); 4880 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(), 4881 PType, S, Extended); 4882 S += charUnitsToString(ParmOffset); 4883 ParmOffset += getObjCEncodingTypeSize(PType); 4884 } 4885 4886 return false; 4887} 4888 4889/// getObjCEncodingForPropertyDecl - Return the encoded type for this 4890/// property declaration. If non-NULL, Container must be either an 4891/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be 4892/// NULL when getting encodings for protocol properties. 4893/// Property attributes are stored as a comma-delimited C string. The simple 4894/// attributes readonly and bycopy are encoded as single characters. The 4895/// parametrized attributes, getter=name, setter=name, and ivar=name, are 4896/// encoded as single characters, followed by an identifier. Property types 4897/// are also encoded as a parametrized attribute. The characters used to encode 4898/// these attributes are defined by the following enumeration: 4899/// @code 4900/// enum PropertyAttributes { 4901/// kPropertyReadOnly = 'R', // property is read-only. 4902/// kPropertyBycopy = 'C', // property is a copy of the value last assigned 4903/// kPropertyByref = '&', // property is a reference to the value last assigned 4904/// kPropertyDynamic = 'D', // property is dynamic 4905/// kPropertyGetter = 'G', // followed by getter selector name 4906/// kPropertySetter = 'S', // followed by setter selector name 4907/// kPropertyInstanceVariable = 'V' // followed by instance variable name 4908/// kPropertyType = 'T' // followed by old-style type encoding. 4909/// kPropertyWeak = 'W' // 'weak' property 4910/// kPropertyStrong = 'P' // property GC'able 4911/// kPropertyNonAtomic = 'N' // property non-atomic 4912/// }; 4913/// @endcode 4914void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, 4915 const Decl *Container, 4916 std::string& S) const { 4917 // Collect information from the property implementation decl(s). 4918 bool Dynamic = false; 4919 ObjCPropertyImplDecl *SynthesizePID = 0; 4920 4921 // FIXME: Duplicated code due to poor abstraction. 4922 if (Container) { 4923 if (const ObjCCategoryImplDecl *CID = 4924 dyn_cast<ObjCCategoryImplDecl>(Container)) { 4925 for (ObjCCategoryImplDecl::propimpl_iterator 4926 i = CID->propimpl_begin(), e = CID->propimpl_end(); 4927 i != e; ++i) { 4928 ObjCPropertyImplDecl *PID = *i; 4929 if (PID->getPropertyDecl() == PD) { 4930 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) { 4931 Dynamic = true; 4932 } else { 4933 SynthesizePID = PID; 4934 } 4935 } 4936 } 4937 } else { 4938 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container); 4939 for (ObjCCategoryImplDecl::propimpl_iterator 4940 i = OID->propimpl_begin(), e = OID->propimpl_end(); 4941 i != e; ++i) { 4942 ObjCPropertyImplDecl *PID = *i; 4943 if (PID->getPropertyDecl() == PD) { 4944 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) { 4945 Dynamic = true; 4946 } else { 4947 SynthesizePID = PID; 4948 } 4949 } 4950 } 4951 } 4952 } 4953 4954 // FIXME: This is not very efficient. 4955 S = "T"; 4956 4957 // Encode result type. 4958 // GCC has some special rules regarding encoding of properties which 4959 // closely resembles encoding of ivars. 4960 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0, 4961 true /* outermost type */, 4962 true /* encoding for property */); 4963 4964 if (PD->isReadOnly()) { 4965 S += ",R"; 4966 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy) 4967 S += ",C"; 4968 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain) 4969 S += ",&"; 4970 } else { 4971 switch (PD->getSetterKind()) { 4972 case ObjCPropertyDecl::Assign: break; 4973 case ObjCPropertyDecl::Copy: S += ",C"; break; 4974 case ObjCPropertyDecl::Retain: S += ",&"; break; 4975 case ObjCPropertyDecl::Weak: S += ",W"; break; 4976 } 4977 } 4978 4979 // It really isn't clear at all what this means, since properties 4980 // are "dynamic by default". 4981 if (Dynamic) 4982 S += ",D"; 4983 4984 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic) 4985 S += ",N"; 4986 4987 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) { 4988 S += ",G"; 4989 S += PD->getGetterName().getAsString(); 4990 } 4991 4992 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) { 4993 S += ",S"; 4994 S += PD->getSetterName().getAsString(); 4995 } 4996 4997 if (SynthesizePID) { 4998 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl(); 4999 S += ",V"; 5000 S += OID->getNameAsString(); 5001 } 5002 5003 // FIXME: OBJCGC: weak & strong 5004} 5005 5006/// getLegacyIntegralTypeEncoding - 5007/// Another legacy compatibility encoding: 32-bit longs are encoded as 5008/// 'l' or 'L' , but not always. For typedefs, we need to use 5009/// 'i' or 'I' instead if encoding a struct field, or a pointer! 5010/// 5011void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const { 5012 if (isa<TypedefType>(PointeeTy.getTypePtr())) { 5013 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) { 5014 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32) 5015 PointeeTy = UnsignedIntTy; 5016 else 5017 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32) 5018 PointeeTy = IntTy; 5019 } 5020 } 5021} 5022 5023void ASTContext::getObjCEncodingForType(QualType T, std::string& S, 5024 const FieldDecl *Field) const { 5025 // We follow the behavior of gcc, expanding structures which are 5026 // directly pointed to, and expanding embedded structures. Note that 5027 // these rules are sufficient to prevent recursive encoding of the 5028 // same type. 5029 getObjCEncodingForTypeImpl(T, S, true, true, Field, 5030 true /* outermost type */); 5031} 5032 5033static char getObjCEncodingForPrimitiveKind(const ASTContext *C, 5034 BuiltinType::Kind kind) { 5035 switch (kind) { 5036 case BuiltinType::Void: return 'v'; 5037 case BuiltinType::Bool: return 'B'; 5038 case BuiltinType::Char_U: 5039 case BuiltinType::UChar: return 'C'; 5040 case BuiltinType::Char16: 5041 case BuiltinType::UShort: return 'S'; 5042 case BuiltinType::Char32: 5043 case BuiltinType::UInt: return 'I'; 5044 case BuiltinType::ULong: 5045 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q'; 5046 case BuiltinType::UInt128: return 'T'; 5047 case BuiltinType::ULongLong: return 'Q'; 5048 case BuiltinType::Char_S: 5049 case BuiltinType::SChar: return 'c'; 5050 case BuiltinType::Short: return 's'; 5051 case BuiltinType::WChar_S: 5052 case BuiltinType::WChar_U: 5053 case BuiltinType::Int: return 'i'; 5054 case BuiltinType::Long: 5055 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q'; 5056 case BuiltinType::LongLong: return 'q'; 5057 case BuiltinType::Int128: return 't'; 5058 case BuiltinType::Float: return 'f'; 5059 case BuiltinType::Double: return 'd'; 5060 case BuiltinType::LongDouble: return 'D'; 5061 case BuiltinType::NullPtr: return '*'; // like char* 5062 5063 case BuiltinType::Half: 5064 // FIXME: potentially need @encodes for these! 5065 return ' '; 5066 5067 case BuiltinType::ObjCId: 5068 case BuiltinType::ObjCClass: 5069 case BuiltinType::ObjCSel: 5070 llvm_unreachable("@encoding ObjC primitive type"); 5071 5072 // OpenCL and placeholder types don't need @encodings. 5073 case BuiltinType::OCLImage1d: 5074 case BuiltinType::OCLImage1dArray: 5075 case BuiltinType::OCLImage1dBuffer: 5076 case BuiltinType::OCLImage2d: 5077 case BuiltinType::OCLImage2dArray: 5078 case BuiltinType::OCLImage3d: 5079 case BuiltinType::OCLEvent: 5080 case BuiltinType::OCLSampler: 5081 case BuiltinType::Dependent: 5082#define BUILTIN_TYPE(KIND, ID) 5083#define PLACEHOLDER_TYPE(KIND, ID) \ 5084 case BuiltinType::KIND: 5085#include "clang/AST/BuiltinTypes.def" 5086 llvm_unreachable("invalid builtin type for @encode"); 5087 } 5088 llvm_unreachable("invalid BuiltinType::Kind value"); 5089} 5090 5091static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) { 5092 EnumDecl *Enum = ET->getDecl(); 5093 5094 // The encoding of an non-fixed enum type is always 'i', regardless of size. 5095 if (!Enum->isFixed()) 5096 return 'i'; 5097 5098 // The encoding of a fixed enum type matches its fixed underlying type. 5099 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>(); 5100 return getObjCEncodingForPrimitiveKind(C, BT->getKind()); 5101} 5102 5103static void EncodeBitField(const ASTContext *Ctx, std::string& S, 5104 QualType T, const FieldDecl *FD) { 5105 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl"); 5106 S += 'b'; 5107 // The NeXT runtime encodes bit fields as b followed by the number of bits. 5108 // The GNU runtime requires more information; bitfields are encoded as b, 5109 // then the offset (in bits) of the first element, then the type of the 5110 // bitfield, then the size in bits. For example, in this structure: 5111 // 5112 // struct 5113 // { 5114 // int integer; 5115 // int flags:2; 5116 // }; 5117 // On a 32-bit system, the encoding for flags would be b2 for the NeXT 5118 // runtime, but b32i2 for the GNU runtime. The reason for this extra 5119 // information is not especially sensible, but we're stuck with it for 5120 // compatibility with GCC, although providing it breaks anything that 5121 // actually uses runtime introspection and wants to work on both runtimes... 5122 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) { 5123 const RecordDecl *RD = FD->getParent(); 5124 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD); 5125 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex())); 5126 if (const EnumType *ET = T->getAs<EnumType>()) 5127 S += ObjCEncodingForEnumType(Ctx, ET); 5128 else { 5129 const BuiltinType *BT = T->castAs<BuiltinType>(); 5130 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind()); 5131 } 5132 } 5133 S += llvm::utostr(FD->getBitWidthValue(*Ctx)); 5134} 5135 5136// FIXME: Use SmallString for accumulating string. 5137void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, 5138 bool ExpandPointedToStructures, 5139 bool ExpandStructures, 5140 const FieldDecl *FD, 5141 bool OutermostType, 5142 bool EncodingProperty, 5143 bool StructField, 5144 bool EncodeBlockParameters, 5145 bool EncodeClassNames, 5146 bool EncodePointerToObjCTypedef) const { 5147 CanQualType CT = getCanonicalType(T); 5148 switch (CT->getTypeClass()) { 5149 case Type::Builtin: 5150 case Type::Enum: 5151 if (FD && FD->isBitField()) 5152 return EncodeBitField(this, S, T, FD); 5153 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT)) 5154 S += getObjCEncodingForPrimitiveKind(this, BT->getKind()); 5155 else 5156 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT)); 5157 return; 5158 5159 case Type::Complex: { 5160 const ComplexType *CT = T->castAs<ComplexType>(); 5161 S += 'j'; 5162 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false, 5163 false); 5164 return; 5165 } 5166 5167 case Type::Atomic: { 5168 const AtomicType *AT = T->castAs<AtomicType>(); 5169 S += 'A'; 5170 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0, 5171 false, false); 5172 return; 5173 } 5174 5175 // encoding for pointer or reference types. 5176 case Type::Pointer: 5177 case Type::LValueReference: 5178 case Type::RValueReference: { 5179 QualType PointeeTy; 5180 if (isa<PointerType>(CT)) { 5181 const PointerType *PT = T->castAs<PointerType>(); 5182 if (PT->isObjCSelType()) { 5183 S += ':'; 5184 return; 5185 } 5186 PointeeTy = PT->getPointeeType(); 5187 } else { 5188 PointeeTy = T->castAs<ReferenceType>()->getPointeeType(); 5189 } 5190 5191 bool isReadOnly = false; 5192 // For historical/compatibility reasons, the read-only qualifier of the 5193 // pointee gets emitted _before_ the '^'. The read-only qualifier of 5194 // the pointer itself gets ignored, _unless_ we are looking at a typedef! 5195 // Also, do not emit the 'r' for anything but the outermost type! 5196 if (isa<TypedefType>(T.getTypePtr())) { 5197 if (OutermostType && T.isConstQualified()) { 5198 isReadOnly = true; 5199 S += 'r'; 5200 } 5201 } else if (OutermostType) { 5202 QualType P = PointeeTy; 5203 while (P->getAs<PointerType>()) 5204 P = P->getAs<PointerType>()->getPointeeType(); 5205 if (P.isConstQualified()) { 5206 isReadOnly = true; 5207 S += 'r'; 5208 } 5209 } 5210 if (isReadOnly) { 5211 // Another legacy compatibility encoding. Some ObjC qualifier and type 5212 // combinations need to be rearranged. 5213 // Rewrite "in const" from "nr" to "rn" 5214 if (StringRef(S).endswith("nr")) 5215 S.replace(S.end()-2, S.end(), "rn"); 5216 } 5217 5218 if (PointeeTy->isCharType()) { 5219 // char pointer types should be encoded as '*' unless it is a 5220 // type that has been typedef'd to 'BOOL'. 5221 if (!isTypeTypedefedAsBOOL(PointeeTy)) { 5222 S += '*'; 5223 return; 5224 } 5225 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) { 5226 // GCC binary compat: Need to convert "struct objc_class *" to "#". 5227 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) { 5228 S += '#'; 5229 return; 5230 } 5231 // GCC binary compat: Need to convert "struct objc_object *" to "@". 5232 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) { 5233 S += '@'; 5234 return; 5235 } 5236 // fall through... 5237 } 5238 S += '^'; 5239 getLegacyIntegralTypeEncoding(PointeeTy); 5240 5241 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures, 5242 NULL); 5243 return; 5244 } 5245 5246 case Type::ConstantArray: 5247 case Type::IncompleteArray: 5248 case Type::VariableArray: { 5249 const ArrayType *AT = cast<ArrayType>(CT); 5250 5251 if (isa<IncompleteArrayType>(AT) && !StructField) { 5252 // Incomplete arrays are encoded as a pointer to the array element. 5253 S += '^'; 5254 5255 getObjCEncodingForTypeImpl(AT->getElementType(), S, 5256 false, ExpandStructures, FD); 5257 } else { 5258 S += '['; 5259 5260 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) 5261 S += llvm::utostr(CAT->getSize().getZExtValue()); 5262 else { 5263 //Variable length arrays are encoded as a regular array with 0 elements. 5264 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) && 5265 "Unknown array type!"); 5266 S += '0'; 5267 } 5268 5269 getObjCEncodingForTypeImpl(AT->getElementType(), S, 5270 false, ExpandStructures, FD); 5271 S += ']'; 5272 } 5273 return; 5274 } 5275 5276 case Type::FunctionNoProto: 5277 case Type::FunctionProto: 5278 S += '?'; 5279 return; 5280 5281 case Type::Record: { 5282 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl(); 5283 S += RDecl->isUnion() ? '(' : '{'; 5284 // Anonymous structures print as '?' 5285 if (const IdentifierInfo *II = RDecl->getIdentifier()) { 5286 S += II->getName(); 5287 if (ClassTemplateSpecializationDecl *Spec 5288 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) { 5289 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 5290 llvm::raw_string_ostream OS(S); 5291 TemplateSpecializationType::PrintTemplateArgumentList(OS, 5292 TemplateArgs.data(), 5293 TemplateArgs.size(), 5294 (*this).getPrintingPolicy()); 5295 } 5296 } else { 5297 S += '?'; 5298 } 5299 if (ExpandStructures) { 5300 S += '='; 5301 if (!RDecl->isUnion()) { 5302 getObjCEncodingForStructureImpl(RDecl, S, FD); 5303 } else { 5304 for (RecordDecl::field_iterator Field = RDecl->field_begin(), 5305 FieldEnd = RDecl->field_end(); 5306 Field != FieldEnd; ++Field) { 5307 if (FD) { 5308 S += '"'; 5309 S += Field->getNameAsString(); 5310 S += '"'; 5311 } 5312 5313 // Special case bit-fields. 5314 if (Field->isBitField()) { 5315 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, 5316 *Field); 5317 } else { 5318 QualType qt = Field->getType(); 5319 getLegacyIntegralTypeEncoding(qt); 5320 getObjCEncodingForTypeImpl(qt, S, false, true, 5321 FD, /*OutermostType*/false, 5322 /*EncodingProperty*/false, 5323 /*StructField*/true); 5324 } 5325 } 5326 } 5327 } 5328 S += RDecl->isUnion() ? ')' : '}'; 5329 return; 5330 } 5331 5332 case Type::BlockPointer: { 5333 const BlockPointerType *BT = T->castAs<BlockPointerType>(); 5334 S += "@?"; // Unlike a pointer-to-function, which is "^?". 5335 if (EncodeBlockParameters) { 5336 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>(); 5337 5338 S += '<'; 5339 // Block return type 5340 getObjCEncodingForTypeImpl(FT->getResultType(), S, 5341 ExpandPointedToStructures, ExpandStructures, 5342 FD, 5343 false /* OutermostType */, 5344 EncodingProperty, 5345 false /* StructField */, 5346 EncodeBlockParameters, 5347 EncodeClassNames); 5348 // Block self 5349 S += "@?"; 5350 // Block parameters 5351 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) { 5352 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(), 5353 E = FPT->arg_type_end(); I && (I != E); ++I) { 5354 getObjCEncodingForTypeImpl(*I, S, 5355 ExpandPointedToStructures, 5356 ExpandStructures, 5357 FD, 5358 false /* OutermostType */, 5359 EncodingProperty, 5360 false /* StructField */, 5361 EncodeBlockParameters, 5362 EncodeClassNames); 5363 } 5364 } 5365 S += '>'; 5366 } 5367 return; 5368 } 5369 5370 case Type::ObjCObject: 5371 case Type::ObjCInterface: { 5372 // Ignore protocol qualifiers when mangling at this level. 5373 T = T->castAs<ObjCObjectType>()->getBaseType(); 5374 5375 // The assumption seems to be that this assert will succeed 5376 // because nested levels will have filtered out 'id' and 'Class'. 5377 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>(); 5378 // @encode(class_name) 5379 ObjCInterfaceDecl *OI = OIT->getDecl(); 5380 S += '{'; 5381 const IdentifierInfo *II = OI->getIdentifier(); 5382 S += II->getName(); 5383 S += '='; 5384 SmallVector<const ObjCIvarDecl*, 32> Ivars; 5385 DeepCollectObjCIvars(OI, true, Ivars); 5386 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) { 5387 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]); 5388 if (Field->isBitField()) 5389 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field); 5390 else 5391 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD, 5392 false, false, false, false, false, 5393 EncodePointerToObjCTypedef); 5394 } 5395 S += '}'; 5396 return; 5397 } 5398 5399 case Type::ObjCObjectPointer: { 5400 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>(); 5401 if (OPT->isObjCIdType()) { 5402 S += '@'; 5403 return; 5404 } 5405 5406 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) { 5407 // FIXME: Consider if we need to output qualifiers for 'Class<p>'. 5408 // Since this is a binary compatibility issue, need to consult with runtime 5409 // folks. Fortunately, this is a *very* obsure construct. 5410 S += '#'; 5411 return; 5412 } 5413 5414 if (OPT->isObjCQualifiedIdType()) { 5415 getObjCEncodingForTypeImpl(getObjCIdType(), S, 5416 ExpandPointedToStructures, 5417 ExpandStructures, FD); 5418 if (FD || EncodingProperty || EncodeClassNames) { 5419 // Note that we do extended encoding of protocol qualifer list 5420 // Only when doing ivar or property encoding. 5421 S += '"'; 5422 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(), 5423 E = OPT->qual_end(); I != E; ++I) { 5424 S += '<'; 5425 S += (*I)->getNameAsString(); 5426 S += '>'; 5427 } 5428 S += '"'; 5429 } 5430 return; 5431 } 5432 5433 QualType PointeeTy = OPT->getPointeeType(); 5434 if (!EncodingProperty && 5435 isa<TypedefType>(PointeeTy.getTypePtr()) && 5436 !EncodePointerToObjCTypedef) { 5437 // Another historical/compatibility reason. 5438 // We encode the underlying type which comes out as 5439 // {...}; 5440 S += '^'; 5441 if (FD && OPT->getInterfaceDecl()) { 5442 // Prevent recursive encoding of fields in some rare cases. 5443 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl(); 5444 SmallVector<const ObjCIvarDecl*, 32> Ivars; 5445 DeepCollectObjCIvars(OI, true, Ivars); 5446 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) { 5447 if (cast<FieldDecl>(Ivars[i]) == FD) { 5448 S += '{'; 5449 S += OI->getIdentifier()->getName(); 5450 S += '}'; 5451 return; 5452 } 5453 } 5454 } 5455 getObjCEncodingForTypeImpl(PointeeTy, S, 5456 false, ExpandPointedToStructures, 5457 NULL, 5458 false, false, false, false, false, 5459 /*EncodePointerToObjCTypedef*/true); 5460 return; 5461 } 5462 5463 S += '@'; 5464 if (OPT->getInterfaceDecl() && 5465 (FD || EncodingProperty || EncodeClassNames)) { 5466 S += '"'; 5467 S += OPT->getInterfaceDecl()->getIdentifier()->getName(); 5468 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(), 5469 E = OPT->qual_end(); I != E; ++I) { 5470 S += '<'; 5471 S += (*I)->getNameAsString(); 5472 S += '>'; 5473 } 5474 S += '"'; 5475 } 5476 return; 5477 } 5478 5479 // gcc just blithely ignores member pointers. 5480 // FIXME: we shoul do better than that. 'M' is available. 5481 case Type::MemberPointer: 5482 return; 5483 5484 case Type::Vector: 5485 case Type::ExtVector: 5486 // This matches gcc's encoding, even though technically it is 5487 // insufficient. 5488 // FIXME. We should do a better job than gcc. 5489 return; 5490 5491 case Type::Auto: 5492 // We could see an undeduced auto type here during error recovery. 5493 // Just ignore it. 5494 return; 5495 5496#define ABSTRACT_TYPE(KIND, BASE) 5497#define TYPE(KIND, BASE) 5498#define DEPENDENT_TYPE(KIND, BASE) \ 5499 case Type::KIND: 5500#define NON_CANONICAL_TYPE(KIND, BASE) \ 5501 case Type::KIND: 5502#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \ 5503 case Type::KIND: 5504#include "clang/AST/TypeNodes.def" 5505 llvm_unreachable("@encode for dependent type!"); 5506 } 5507 llvm_unreachable("bad type kind!"); 5508} 5509 5510void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl, 5511 std::string &S, 5512 const FieldDecl *FD, 5513 bool includeVBases) const { 5514 assert(RDecl && "Expected non-null RecordDecl"); 5515 assert(!RDecl->isUnion() && "Should not be called for unions"); 5516 if (!RDecl->getDefinition()) 5517 return; 5518 5519 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl); 5520 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets; 5521 const ASTRecordLayout &layout = getASTRecordLayout(RDecl); 5522 5523 if (CXXRec) { 5524 for (CXXRecordDecl::base_class_iterator 5525 BI = CXXRec->bases_begin(), 5526 BE = CXXRec->bases_end(); BI != BE; ++BI) { 5527 if (!BI->isVirtual()) { 5528 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl(); 5529 if (base->isEmpty()) 5530 continue; 5531 uint64_t offs = toBits(layout.getBaseClassOffset(base)); 5532 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 5533 std::make_pair(offs, base)); 5534 } 5535 } 5536 } 5537 5538 unsigned i = 0; 5539 for (RecordDecl::field_iterator Field = RDecl->field_begin(), 5540 FieldEnd = RDecl->field_end(); 5541 Field != FieldEnd; ++Field, ++i) { 5542 uint64_t offs = layout.getFieldOffset(i); 5543 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 5544 std::make_pair(offs, *Field)); 5545 } 5546 5547 if (CXXRec && includeVBases) { 5548 for (CXXRecordDecl::base_class_iterator 5549 BI = CXXRec->vbases_begin(), 5550 BE = CXXRec->vbases_end(); BI != BE; ++BI) { 5551 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl(); 5552 if (base->isEmpty()) 5553 continue; 5554 uint64_t offs = toBits(layout.getVBaseClassOffset(base)); 5555 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) && 5556 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