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