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