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