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