1 //===- DeclObjC.cpp - ObjC Declaration AST Node Implementation ------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the Objective-C related Decl classes. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/DeclObjC.h" 14 #include "clang/AST/ASTContext.h" 15 #include "clang/AST/ASTMutationListener.h" 16 #include "clang/AST/Attr.h" 17 #include "clang/AST/Decl.h" 18 #include "clang/AST/DeclBase.h" 19 #include "clang/AST/Stmt.h" 20 #include "clang/AST/Type.h" 21 #include "clang/AST/TypeLoc.h" 22 #include "clang/Basic/IdentifierTable.h" 23 #include "clang/Basic/LLVM.h" 24 #include "clang/Basic/LangOptions.h" 25 #include "clang/Basic/SourceLocation.h" 26 #include "llvm/ADT/None.h" 27 #include "llvm/ADT/SmallString.h" 28 #include "llvm/ADT/SmallVector.h" 29 #include "llvm/Support/Casting.h" 30 #include "llvm/Support/ErrorHandling.h" 31 #include "llvm/Support/raw_ostream.h" 32 #include <algorithm> 33 #include <cassert> 34 #include <cstdint> 35 #include <cstring> 36 #include <queue> 37 #include <utility> 38 39 using namespace clang; 40 41 //===----------------------------------------------------------------------===// 42 // ObjCListBase 43 //===----------------------------------------------------------------------===// 44 45 void ObjCListBase::set(void *const* InList, unsigned Elts, ASTContext &Ctx) { 46 List = nullptr; 47 if (Elts == 0) return; // Setting to an empty list is a noop. 48 49 List = new (Ctx) void*[Elts]; 50 NumElts = Elts; 51 memcpy(List, InList, sizeof(void*)*Elts); 52 } 53 54 void ObjCProtocolList::set(ObjCProtocolDecl* const* InList, unsigned Elts, 55 const SourceLocation *Locs, ASTContext &Ctx) { 56 if (Elts == 0) 57 return; 58 59 Locations = new (Ctx) SourceLocation[Elts]; 60 memcpy(Locations, Locs, sizeof(SourceLocation) * Elts); 61 set(InList, Elts, Ctx); 62 } 63 64 //===----------------------------------------------------------------------===// 65 // ObjCInterfaceDecl 66 //===----------------------------------------------------------------------===// 67 68 ObjCContainerDecl::ObjCContainerDecl(Kind DK, DeclContext *DC, 69 IdentifierInfo *Id, SourceLocation nameLoc, 70 SourceLocation atStartLoc) 71 : NamedDecl(DK, DC, nameLoc, Id), DeclContext(DK) { 72 setAtStartLoc(atStartLoc); 73 } 74 75 void ObjCContainerDecl::anchor() {} 76 77 /// getIvarDecl - This method looks up an ivar in this ContextDecl. 78 /// 79 ObjCIvarDecl * 80 ObjCContainerDecl::getIvarDecl(IdentifierInfo *Id) const { 81 lookup_result R = lookup(Id); 82 for (lookup_iterator Ivar = R.begin(), IvarEnd = R.end(); 83 Ivar != IvarEnd; ++Ivar) { 84 if (auto *ivar = dyn_cast<ObjCIvarDecl>(*Ivar)) 85 return ivar; 86 } 87 return nullptr; 88 } 89 90 // Get the local instance/class method declared in this interface. 91 ObjCMethodDecl * 92 ObjCContainerDecl::getMethod(Selector Sel, bool isInstance, 93 bool AllowHidden) const { 94 // If this context is a hidden protocol definition, don't find any 95 // methods there. 96 if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(this)) { 97 if (const ObjCProtocolDecl *Def = Proto->getDefinition()) 98 if (!Def->isUnconditionallyVisible() && !AllowHidden) 99 return nullptr; 100 } 101 102 // Since instance & class methods can have the same name, the loop below 103 // ensures we get the correct method. 104 // 105 // @interface Whatever 106 // - (int) class_method; 107 // + (float) class_method; 108 // @end 109 lookup_result R = lookup(Sel); 110 for (lookup_iterator Meth = R.begin(), MethEnd = R.end(); 111 Meth != MethEnd; ++Meth) { 112 auto *MD = dyn_cast<ObjCMethodDecl>(*Meth); 113 if (MD && MD->isInstanceMethod() == isInstance) 114 return MD; 115 } 116 return nullptr; 117 } 118 119 /// This routine returns 'true' if a user declared setter method was 120 /// found in the class, its protocols, its super classes or categories. 121 /// It also returns 'true' if one of its categories has declared a 'readwrite' 122 /// property. This is because, user must provide a setter method for the 123 /// category's 'readwrite' property. 124 bool ObjCContainerDecl::HasUserDeclaredSetterMethod( 125 const ObjCPropertyDecl *Property) const { 126 Selector Sel = Property->getSetterName(); 127 lookup_result R = lookup(Sel); 128 for (lookup_iterator Meth = R.begin(), MethEnd = R.end(); 129 Meth != MethEnd; ++Meth) { 130 auto *MD = dyn_cast<ObjCMethodDecl>(*Meth); 131 if (MD && MD->isInstanceMethod() && !MD->isImplicit()) 132 return true; 133 } 134 135 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(this)) { 136 // Also look into categories, including class extensions, looking 137 // for a user declared instance method. 138 for (const auto *Cat : ID->visible_categories()) { 139 if (ObjCMethodDecl *MD = Cat->getInstanceMethod(Sel)) 140 if (!MD->isImplicit()) 141 return true; 142 if (Cat->IsClassExtension()) 143 continue; 144 // Also search through the categories looking for a 'readwrite' 145 // declaration of this property. If one found, presumably a setter will 146 // be provided (properties declared in categories will not get 147 // auto-synthesized). 148 for (const auto *P : Cat->properties()) 149 if (P->getIdentifier() == Property->getIdentifier()) { 150 if (P->getPropertyAttributes() & 151 ObjCPropertyAttribute::kind_readwrite) 152 return true; 153 break; 154 } 155 } 156 157 // Also look into protocols, for a user declared instance method. 158 for (const auto *Proto : ID->all_referenced_protocols()) 159 if (Proto->HasUserDeclaredSetterMethod(Property)) 160 return true; 161 162 // And in its super class. 163 ObjCInterfaceDecl *OSC = ID->getSuperClass(); 164 while (OSC) { 165 if (OSC->HasUserDeclaredSetterMethod(Property)) 166 return true; 167 OSC = OSC->getSuperClass(); 168 } 169 } 170 if (const auto *PD = dyn_cast<ObjCProtocolDecl>(this)) 171 for (const auto *PI : PD->protocols()) 172 if (PI->HasUserDeclaredSetterMethod(Property)) 173 return true; 174 return false; 175 } 176 177 ObjCPropertyDecl * 178 ObjCPropertyDecl::findPropertyDecl(const DeclContext *DC, 179 const IdentifierInfo *propertyID, 180 ObjCPropertyQueryKind queryKind) { 181 // If this context is a hidden protocol definition, don't find any 182 // property. 183 if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(DC)) { 184 if (const ObjCProtocolDecl *Def = Proto->getDefinition()) 185 if (!Def->isUnconditionallyVisible()) 186 return nullptr; 187 } 188 189 // If context is class, then lookup property in its visible extensions. 190 // This comes before property is looked up in primary class. 191 if (auto *IDecl = dyn_cast<ObjCInterfaceDecl>(DC)) { 192 for (const auto *Ext : IDecl->visible_extensions()) 193 if (ObjCPropertyDecl *PD = ObjCPropertyDecl::findPropertyDecl(Ext, 194 propertyID, 195 queryKind)) 196 return PD; 197 } 198 199 DeclContext::lookup_result R = DC->lookup(propertyID); 200 ObjCPropertyDecl *classProp = nullptr; 201 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 202 ++I) 203 if (auto *PD = dyn_cast<ObjCPropertyDecl>(*I)) { 204 // If queryKind is unknown, we return the instance property if one 205 // exists; otherwise we return the class property. 206 if ((queryKind == ObjCPropertyQueryKind::OBJC_PR_query_unknown && 207 !PD->isClassProperty()) || 208 (queryKind == ObjCPropertyQueryKind::OBJC_PR_query_class && 209 PD->isClassProperty()) || 210 (queryKind == ObjCPropertyQueryKind::OBJC_PR_query_instance && 211 !PD->isClassProperty())) 212 return PD; 213 214 if (PD->isClassProperty()) 215 classProp = PD; 216 } 217 218 if (queryKind == ObjCPropertyQueryKind::OBJC_PR_query_unknown) 219 // We can't find the instance property, return the class property. 220 return classProp; 221 222 return nullptr; 223 } 224 225 IdentifierInfo * 226 ObjCPropertyDecl::getDefaultSynthIvarName(ASTContext &Ctx) const { 227 SmallString<128> ivarName; 228 { 229 llvm::raw_svector_ostream os(ivarName); 230 os << '_' << getIdentifier()->getName(); 231 } 232 return &Ctx.Idents.get(ivarName.str()); 233 } 234 235 /// FindPropertyDeclaration - Finds declaration of the property given its name 236 /// in 'PropertyId' and returns it. It returns 0, if not found. 237 ObjCPropertyDecl *ObjCContainerDecl::FindPropertyDeclaration( 238 const IdentifierInfo *PropertyId, 239 ObjCPropertyQueryKind QueryKind) const { 240 // Don't find properties within hidden protocol definitions. 241 if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(this)) { 242 if (const ObjCProtocolDecl *Def = Proto->getDefinition()) 243 if (!Def->isUnconditionallyVisible()) 244 return nullptr; 245 } 246 247 // Search the extensions of a class first; they override what's in 248 // the class itself. 249 if (const auto *ClassDecl = dyn_cast<ObjCInterfaceDecl>(this)) { 250 for (const auto *Ext : ClassDecl->visible_extensions()) { 251 if (auto *P = Ext->FindPropertyDeclaration(PropertyId, QueryKind)) 252 return P; 253 } 254 } 255 256 if (ObjCPropertyDecl *PD = 257 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(this), PropertyId, 258 QueryKind)) 259 return PD; 260 261 switch (getKind()) { 262 default: 263 break; 264 case Decl::ObjCProtocol: { 265 const auto *PID = cast<ObjCProtocolDecl>(this); 266 for (const auto *I : PID->protocols()) 267 if (ObjCPropertyDecl *P = I->FindPropertyDeclaration(PropertyId, 268 QueryKind)) 269 return P; 270 break; 271 } 272 case Decl::ObjCInterface: { 273 const auto *OID = cast<ObjCInterfaceDecl>(this); 274 // Look through categories (but not extensions; they were handled above). 275 for (const auto *Cat : OID->visible_categories()) { 276 if (!Cat->IsClassExtension()) 277 if (ObjCPropertyDecl *P = Cat->FindPropertyDeclaration( 278 PropertyId, QueryKind)) 279 return P; 280 } 281 282 // Look through protocols. 283 for (const auto *I : OID->all_referenced_protocols()) 284 if (ObjCPropertyDecl *P = I->FindPropertyDeclaration(PropertyId, 285 QueryKind)) 286 return P; 287 288 // Finally, check the super class. 289 if (const ObjCInterfaceDecl *superClass = OID->getSuperClass()) 290 return superClass->FindPropertyDeclaration(PropertyId, QueryKind); 291 break; 292 } 293 case Decl::ObjCCategory: { 294 const auto *OCD = cast<ObjCCategoryDecl>(this); 295 // Look through protocols. 296 if (!OCD->IsClassExtension()) 297 for (const auto *I : OCD->protocols()) 298 if (ObjCPropertyDecl *P = I->FindPropertyDeclaration(PropertyId, 299 QueryKind)) 300 return P; 301 break; 302 } 303 } 304 return nullptr; 305 } 306 307 void ObjCInterfaceDecl::anchor() {} 308 309 ObjCTypeParamList *ObjCInterfaceDecl::getTypeParamList() const { 310 // If this particular declaration has a type parameter list, return it. 311 if (ObjCTypeParamList *written = getTypeParamListAsWritten()) 312 return written; 313 314 // If there is a definition, return its type parameter list. 315 if (const ObjCInterfaceDecl *def = getDefinition()) 316 return def->getTypeParamListAsWritten(); 317 318 // Otherwise, look at previous declarations to determine whether any 319 // of them has a type parameter list, skipping over those 320 // declarations that do not. 321 for (const ObjCInterfaceDecl *decl = getMostRecentDecl(); decl; 322 decl = decl->getPreviousDecl()) { 323 if (ObjCTypeParamList *written = decl->getTypeParamListAsWritten()) 324 return written; 325 } 326 327 return nullptr; 328 } 329 330 void ObjCInterfaceDecl::setTypeParamList(ObjCTypeParamList *TPL) { 331 TypeParamList = TPL; 332 if (!TPL) 333 return; 334 // Set the declaration context of each of the type parameters. 335 for (auto *typeParam : *TypeParamList) 336 typeParam->setDeclContext(this); 337 } 338 339 ObjCInterfaceDecl *ObjCInterfaceDecl::getSuperClass() const { 340 // FIXME: Should make sure no callers ever do this. 341 if (!hasDefinition()) 342 return nullptr; 343 344 if (data().ExternallyCompleted) 345 LoadExternalDefinition(); 346 347 if (const ObjCObjectType *superType = getSuperClassType()) { 348 if (ObjCInterfaceDecl *superDecl = superType->getInterface()) { 349 if (ObjCInterfaceDecl *superDef = superDecl->getDefinition()) 350 return superDef; 351 352 return superDecl; 353 } 354 } 355 356 return nullptr; 357 } 358 359 SourceLocation ObjCInterfaceDecl::getSuperClassLoc() const { 360 if (TypeSourceInfo *superTInfo = getSuperClassTInfo()) 361 return superTInfo->getTypeLoc().getBeginLoc(); 362 363 return SourceLocation(); 364 } 365 366 /// FindPropertyVisibleInPrimaryClass - Finds declaration of the property 367 /// with name 'PropertyId' in the primary class; including those in protocols 368 /// (direct or indirect) used by the primary class. 369 ObjCPropertyDecl * 370 ObjCInterfaceDecl::FindPropertyVisibleInPrimaryClass( 371 IdentifierInfo *PropertyId, 372 ObjCPropertyQueryKind QueryKind) const { 373 // FIXME: Should make sure no callers ever do this. 374 if (!hasDefinition()) 375 return nullptr; 376 377 if (data().ExternallyCompleted) 378 LoadExternalDefinition(); 379 380 if (ObjCPropertyDecl *PD = 381 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(this), PropertyId, 382 QueryKind)) 383 return PD; 384 385 // Look through protocols. 386 for (const auto *I : all_referenced_protocols()) 387 if (ObjCPropertyDecl *P = I->FindPropertyDeclaration(PropertyId, 388 QueryKind)) 389 return P; 390 391 return nullptr; 392 } 393 394 void ObjCInterfaceDecl::collectPropertiesToImplement(PropertyMap &PM, 395 PropertyDeclOrder &PO) const { 396 for (auto *Prop : properties()) { 397 PM[std::make_pair(Prop->getIdentifier(), Prop->isClassProperty())] = Prop; 398 PO.push_back(Prop); 399 } 400 for (const auto *Ext : known_extensions()) { 401 const ObjCCategoryDecl *ClassExt = Ext; 402 for (auto *Prop : ClassExt->properties()) { 403 PM[std::make_pair(Prop->getIdentifier(), Prop->isClassProperty())] = Prop; 404 PO.push_back(Prop); 405 } 406 } 407 for (const auto *PI : all_referenced_protocols()) 408 PI->collectPropertiesToImplement(PM, PO); 409 // Note, the properties declared only in class extensions are still copied 410 // into the main @interface's property list, and therefore we don't 411 // explicitly, have to search class extension properties. 412 } 413 414 bool ObjCInterfaceDecl::isArcWeakrefUnavailable() const { 415 const ObjCInterfaceDecl *Class = this; 416 while (Class) { 417 if (Class->hasAttr<ArcWeakrefUnavailableAttr>()) 418 return true; 419 Class = Class->getSuperClass(); 420 } 421 return false; 422 } 423 424 const ObjCInterfaceDecl *ObjCInterfaceDecl::isObjCRequiresPropertyDefs() const { 425 const ObjCInterfaceDecl *Class = this; 426 while (Class) { 427 if (Class->hasAttr<ObjCRequiresPropertyDefsAttr>()) 428 return Class; 429 Class = Class->getSuperClass(); 430 } 431 return nullptr; 432 } 433 434 void ObjCInterfaceDecl::mergeClassExtensionProtocolList( 435 ObjCProtocolDecl *const* ExtList, unsigned ExtNum, 436 ASTContext &C) { 437 if (data().ExternallyCompleted) 438 LoadExternalDefinition(); 439 440 if (data().AllReferencedProtocols.empty() && 441 data().ReferencedProtocols.empty()) { 442 data().AllReferencedProtocols.set(ExtList, ExtNum, C); 443 return; 444 } 445 446 // Check for duplicate protocol in class's protocol list. 447 // This is O(n*m). But it is extremely rare and number of protocols in 448 // class or its extension are very few. 449 SmallVector<ObjCProtocolDecl *, 8> ProtocolRefs; 450 for (unsigned i = 0; i < ExtNum; i++) { 451 bool protocolExists = false; 452 ObjCProtocolDecl *ProtoInExtension = ExtList[i]; 453 for (auto *Proto : all_referenced_protocols()) { 454 if (C.ProtocolCompatibleWithProtocol(ProtoInExtension, Proto)) { 455 protocolExists = true; 456 break; 457 } 458 } 459 // Do we want to warn on a protocol in extension class which 460 // already exist in the class? Probably not. 461 if (!protocolExists) 462 ProtocolRefs.push_back(ProtoInExtension); 463 } 464 465 if (ProtocolRefs.empty()) 466 return; 467 468 // Merge ProtocolRefs into class's protocol list; 469 ProtocolRefs.append(all_referenced_protocol_begin(), 470 all_referenced_protocol_end()); 471 472 data().AllReferencedProtocols.set(ProtocolRefs.data(), ProtocolRefs.size(),C); 473 } 474 475 const ObjCInterfaceDecl * 476 ObjCInterfaceDecl::findInterfaceWithDesignatedInitializers() const { 477 const ObjCInterfaceDecl *IFace = this; 478 while (IFace) { 479 if (IFace->hasDesignatedInitializers()) 480 return IFace; 481 if (!IFace->inheritsDesignatedInitializers()) 482 break; 483 IFace = IFace->getSuperClass(); 484 } 485 return nullptr; 486 } 487 488 static bool isIntroducingInitializers(const ObjCInterfaceDecl *D) { 489 for (const auto *MD : D->instance_methods()) { 490 if (MD->getMethodFamily() == OMF_init && !MD->isOverriding()) 491 return true; 492 } 493 for (const auto *Ext : D->visible_extensions()) { 494 for (const auto *MD : Ext->instance_methods()) { 495 if (MD->getMethodFamily() == OMF_init && !MD->isOverriding()) 496 return true; 497 } 498 } 499 if (const auto *ImplD = D->getImplementation()) { 500 for (const auto *MD : ImplD->instance_methods()) { 501 if (MD->getMethodFamily() == OMF_init && !MD->isOverriding()) 502 return true; 503 } 504 } 505 return false; 506 } 507 508 bool ObjCInterfaceDecl::inheritsDesignatedInitializers() const { 509 switch (data().InheritedDesignatedInitializers) { 510 case DefinitionData::IDI_Inherited: 511 return true; 512 case DefinitionData::IDI_NotInherited: 513 return false; 514 case DefinitionData::IDI_Unknown: 515 // If the class introduced initializers we conservatively assume that we 516 // don't know if any of them is a designated initializer to avoid possible 517 // misleading warnings. 518 if (isIntroducingInitializers(this)) { 519 data().InheritedDesignatedInitializers = DefinitionData::IDI_NotInherited; 520 } else { 521 if (auto SuperD = getSuperClass()) { 522 data().InheritedDesignatedInitializers = 523 SuperD->declaresOrInheritsDesignatedInitializers() ? 524 DefinitionData::IDI_Inherited : 525 DefinitionData::IDI_NotInherited; 526 } else { 527 data().InheritedDesignatedInitializers = 528 DefinitionData::IDI_NotInherited; 529 } 530 } 531 assert(data().InheritedDesignatedInitializers 532 != DefinitionData::IDI_Unknown); 533 return data().InheritedDesignatedInitializers == 534 DefinitionData::IDI_Inherited; 535 } 536 537 llvm_unreachable("unexpected InheritedDesignatedInitializers value"); 538 } 539 540 void ObjCInterfaceDecl::getDesignatedInitializers( 541 llvm::SmallVectorImpl<const ObjCMethodDecl *> &Methods) const { 542 // Check for a complete definition and recover if not so. 543 if (!isThisDeclarationADefinition()) 544 return; 545 if (data().ExternallyCompleted) 546 LoadExternalDefinition(); 547 548 const ObjCInterfaceDecl *IFace= findInterfaceWithDesignatedInitializers(); 549 if (!IFace) 550 return; 551 552 for (const auto *MD : IFace->instance_methods()) 553 if (MD->isThisDeclarationADesignatedInitializer()) 554 Methods.push_back(MD); 555 for (const auto *Ext : IFace->visible_extensions()) { 556 for (const auto *MD : Ext->instance_methods()) 557 if (MD->isThisDeclarationADesignatedInitializer()) 558 Methods.push_back(MD); 559 } 560 } 561 562 bool ObjCInterfaceDecl::isDesignatedInitializer(Selector Sel, 563 const ObjCMethodDecl **InitMethod) const { 564 bool HasCompleteDef = isThisDeclarationADefinition(); 565 // During deserialization the data record for the ObjCInterfaceDecl could 566 // be made invariant by reusing the canonical decl. Take this into account 567 // when checking for the complete definition. 568 if (!HasCompleteDef && getCanonicalDecl()->hasDefinition() && 569 getCanonicalDecl()->getDefinition() == getDefinition()) 570 HasCompleteDef = true; 571 572 // Check for a complete definition and recover if not so. 573 if (!HasCompleteDef) 574 return false; 575 576 if (data().ExternallyCompleted) 577 LoadExternalDefinition(); 578 579 const ObjCInterfaceDecl *IFace= findInterfaceWithDesignatedInitializers(); 580 if (!IFace) 581 return false; 582 583 if (const ObjCMethodDecl *MD = IFace->getInstanceMethod(Sel)) { 584 if (MD->isThisDeclarationADesignatedInitializer()) { 585 if (InitMethod) 586 *InitMethod = MD; 587 return true; 588 } 589 } 590 for (const auto *Ext : IFace->visible_extensions()) { 591 if (const ObjCMethodDecl *MD = Ext->getInstanceMethod(Sel)) { 592 if (MD->isThisDeclarationADesignatedInitializer()) { 593 if (InitMethod) 594 *InitMethod = MD; 595 return true; 596 } 597 } 598 } 599 return false; 600 } 601 602 void ObjCInterfaceDecl::allocateDefinitionData() { 603 assert(!hasDefinition() && "ObjC class already has a definition"); 604 Data.setPointer(new (getASTContext()) DefinitionData()); 605 Data.getPointer()->Definition = this; 606 } 607 608 void ObjCInterfaceDecl::startDefinition() { 609 allocateDefinitionData(); 610 611 // Update all of the declarations with a pointer to the definition. 612 for (auto *RD : redecls()) { 613 if (RD != this) 614 RD->Data = Data; 615 } 616 } 617 618 ObjCIvarDecl *ObjCInterfaceDecl::lookupInstanceVariable(IdentifierInfo *ID, 619 ObjCInterfaceDecl *&clsDeclared) { 620 // FIXME: Should make sure no callers ever do this. 621 if (!hasDefinition()) 622 return nullptr; 623 624 if (data().ExternallyCompleted) 625 LoadExternalDefinition(); 626 627 ObjCInterfaceDecl* ClassDecl = this; 628 while (ClassDecl != nullptr) { 629 if (ObjCIvarDecl *I = ClassDecl->getIvarDecl(ID)) { 630 clsDeclared = ClassDecl; 631 return I; 632 } 633 634 for (const auto *Ext : ClassDecl->visible_extensions()) { 635 if (ObjCIvarDecl *I = Ext->getIvarDecl(ID)) { 636 clsDeclared = ClassDecl; 637 return I; 638 } 639 } 640 641 ClassDecl = ClassDecl->getSuperClass(); 642 } 643 return nullptr; 644 } 645 646 /// lookupInheritedClass - This method returns ObjCInterfaceDecl * of the super 647 /// class whose name is passed as argument. If it is not one of the super classes 648 /// the it returns NULL. 649 ObjCInterfaceDecl *ObjCInterfaceDecl::lookupInheritedClass( 650 const IdentifierInfo*ICName) { 651 // FIXME: Should make sure no callers ever do this. 652 if (!hasDefinition()) 653 return nullptr; 654 655 if (data().ExternallyCompleted) 656 LoadExternalDefinition(); 657 658 ObjCInterfaceDecl* ClassDecl = this; 659 while (ClassDecl != nullptr) { 660 if (ClassDecl->getIdentifier() == ICName) 661 return ClassDecl; 662 ClassDecl = ClassDecl->getSuperClass(); 663 } 664 return nullptr; 665 } 666 667 ObjCProtocolDecl * 668 ObjCInterfaceDecl::lookupNestedProtocol(IdentifierInfo *Name) { 669 for (auto *P : all_referenced_protocols()) 670 if (P->lookupProtocolNamed(Name)) 671 return P; 672 ObjCInterfaceDecl *SuperClass = getSuperClass(); 673 return SuperClass ? SuperClass->lookupNestedProtocol(Name) : nullptr; 674 } 675 676 /// lookupMethod - This method returns an instance/class method by looking in 677 /// the class, its categories, and its super classes (using a linear search). 678 /// When argument category "C" is specified, any implicit method found 679 /// in this category is ignored. 680 ObjCMethodDecl *ObjCInterfaceDecl::lookupMethod(Selector Sel, 681 bool isInstance, 682 bool shallowCategoryLookup, 683 bool followSuper, 684 const ObjCCategoryDecl *C) const 685 { 686 // FIXME: Should make sure no callers ever do this. 687 if (!hasDefinition()) 688 return nullptr; 689 690 const ObjCInterfaceDecl* ClassDecl = this; 691 ObjCMethodDecl *MethodDecl = nullptr; 692 693 if (data().ExternallyCompleted) 694 LoadExternalDefinition(); 695 696 while (ClassDecl) { 697 // 1. Look through primary class. 698 if ((MethodDecl = ClassDecl->getMethod(Sel, isInstance))) 699 return MethodDecl; 700 701 // 2. Didn't find one yet - now look through categories. 702 for (const auto *Cat : ClassDecl->visible_categories()) 703 if ((MethodDecl = Cat->getMethod(Sel, isInstance))) 704 if (C != Cat || !MethodDecl->isImplicit()) 705 return MethodDecl; 706 707 // 3. Didn't find one yet - look through primary class's protocols. 708 for (const auto *I : ClassDecl->protocols()) 709 if ((MethodDecl = I->lookupMethod(Sel, isInstance))) 710 return MethodDecl; 711 712 // 4. Didn't find one yet - now look through categories' protocols 713 if (!shallowCategoryLookup) 714 for (const auto *Cat : ClassDecl->visible_categories()) { 715 // Didn't find one yet - look through protocols. 716 const ObjCList<ObjCProtocolDecl> &Protocols = 717 Cat->getReferencedProtocols(); 718 for (auto *Protocol : Protocols) 719 if ((MethodDecl = Protocol->lookupMethod(Sel, isInstance))) 720 if (C != Cat || !MethodDecl->isImplicit()) 721 return MethodDecl; 722 } 723 724 725 if (!followSuper) 726 return nullptr; 727 728 // 5. Get to the super class (if any). 729 ClassDecl = ClassDecl->getSuperClass(); 730 } 731 return nullptr; 732 } 733 734 // Will search "local" class/category implementations for a method decl. 735 // If failed, then we search in class's root for an instance method. 736 // Returns 0 if no method is found. 737 ObjCMethodDecl *ObjCInterfaceDecl::lookupPrivateMethod( 738 const Selector &Sel, 739 bool Instance) const { 740 // FIXME: Should make sure no callers ever do this. 741 if (!hasDefinition()) 742 return nullptr; 743 744 if (data().ExternallyCompleted) 745 LoadExternalDefinition(); 746 747 ObjCMethodDecl *Method = nullptr; 748 if (ObjCImplementationDecl *ImpDecl = getImplementation()) 749 Method = Instance ? ImpDecl->getInstanceMethod(Sel) 750 : ImpDecl->getClassMethod(Sel); 751 752 // Look through local category implementations associated with the class. 753 if (!Method) 754 Method = getCategoryMethod(Sel, Instance); 755 756 // Before we give up, check if the selector is an instance method. 757 // But only in the root. This matches gcc's behavior and what the 758 // runtime expects. 759 if (!Instance && !Method && !getSuperClass()) { 760 Method = lookupInstanceMethod(Sel); 761 // Look through local category implementations associated 762 // with the root class. 763 if (!Method) 764 Method = lookupPrivateMethod(Sel, true); 765 } 766 767 if (!Method && getSuperClass()) 768 return getSuperClass()->lookupPrivateMethod(Sel, Instance); 769 return Method; 770 } 771 772 //===----------------------------------------------------------------------===// 773 // ObjCMethodDecl 774 //===----------------------------------------------------------------------===// 775 776 ObjCMethodDecl::ObjCMethodDecl( 777 SourceLocation beginLoc, SourceLocation endLoc, Selector SelInfo, 778 QualType T, TypeSourceInfo *ReturnTInfo, DeclContext *contextDecl, 779 bool isInstance, bool isVariadic, bool isPropertyAccessor, 780 bool isSynthesizedAccessorStub, bool isImplicitlyDeclared, bool isDefined, 781 ImplementationControl impControl, bool HasRelatedResultType) 782 : NamedDecl(ObjCMethod, contextDecl, beginLoc, SelInfo), 783 DeclContext(ObjCMethod), MethodDeclType(T), ReturnTInfo(ReturnTInfo), 784 DeclEndLoc(endLoc) { 785 786 // Initialized the bits stored in DeclContext. 787 ObjCMethodDeclBits.Family = 788 static_cast<ObjCMethodFamily>(InvalidObjCMethodFamily); 789 setInstanceMethod(isInstance); 790 setVariadic(isVariadic); 791 setPropertyAccessor(isPropertyAccessor); 792 setSynthesizedAccessorStub(isSynthesizedAccessorStub); 793 setDefined(isDefined); 794 setIsRedeclaration(false); 795 setHasRedeclaration(false); 796 setDeclImplementation(impControl); 797 setObjCDeclQualifier(OBJC_TQ_None); 798 setRelatedResultType(HasRelatedResultType); 799 setSelLocsKind(SelLoc_StandardNoSpace); 800 setOverriding(false); 801 setHasSkippedBody(false); 802 803 setImplicit(isImplicitlyDeclared); 804 } 805 806 ObjCMethodDecl *ObjCMethodDecl::Create( 807 ASTContext &C, SourceLocation beginLoc, SourceLocation endLoc, 808 Selector SelInfo, QualType T, TypeSourceInfo *ReturnTInfo, 809 DeclContext *contextDecl, bool isInstance, bool isVariadic, 810 bool isPropertyAccessor, bool isSynthesizedAccessorStub, 811 bool isImplicitlyDeclared, bool isDefined, ImplementationControl impControl, 812 bool HasRelatedResultType) { 813 return new (C, contextDecl) ObjCMethodDecl( 814 beginLoc, endLoc, SelInfo, T, ReturnTInfo, contextDecl, isInstance, 815 isVariadic, isPropertyAccessor, isSynthesizedAccessorStub, 816 isImplicitlyDeclared, isDefined, impControl, HasRelatedResultType); 817 } 818 819 ObjCMethodDecl *ObjCMethodDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 820 return new (C, ID) ObjCMethodDecl(SourceLocation(), SourceLocation(), 821 Selector(), QualType(), nullptr, nullptr); 822 } 823 824 bool ObjCMethodDecl::isDirectMethod() const { 825 return hasAttr<ObjCDirectAttr>() && 826 !getASTContext().getLangOpts().ObjCDisableDirectMethodsForTesting; 827 } 828 829 bool ObjCMethodDecl::isThisDeclarationADesignatedInitializer() const { 830 return getMethodFamily() == OMF_init && 831 hasAttr<ObjCDesignatedInitializerAttr>(); 832 } 833 834 bool ObjCMethodDecl::definedInNSObject(const ASTContext &Ctx) const { 835 if (const auto *PD = dyn_cast<const ObjCProtocolDecl>(getDeclContext())) 836 return PD->getIdentifier() == Ctx.getNSObjectName(); 837 if (const auto *ID = dyn_cast<const ObjCInterfaceDecl>(getDeclContext())) 838 return ID->getIdentifier() == Ctx.getNSObjectName(); 839 return false; 840 } 841 842 bool ObjCMethodDecl::isDesignatedInitializerForTheInterface( 843 const ObjCMethodDecl **InitMethod) const { 844 if (getMethodFamily() != OMF_init) 845 return false; 846 const DeclContext *DC = getDeclContext(); 847 if (isa<ObjCProtocolDecl>(DC)) 848 return false; 849 if (const ObjCInterfaceDecl *ID = getClassInterface()) 850 return ID->isDesignatedInitializer(getSelector(), InitMethod); 851 return false; 852 } 853 854 bool ObjCMethodDecl::hasParamDestroyedInCallee() const { 855 for (auto param : parameters()) { 856 if (param->isDestroyedInCallee()) 857 return true; 858 } 859 return false; 860 } 861 862 Stmt *ObjCMethodDecl::getBody() const { 863 return Body.get(getASTContext().getExternalSource()); 864 } 865 866 void ObjCMethodDecl::setAsRedeclaration(const ObjCMethodDecl *PrevMethod) { 867 assert(PrevMethod); 868 getASTContext().setObjCMethodRedeclaration(PrevMethod, this); 869 setIsRedeclaration(true); 870 PrevMethod->setHasRedeclaration(true); 871 } 872 873 void ObjCMethodDecl::setParamsAndSelLocs(ASTContext &C, 874 ArrayRef<ParmVarDecl*> Params, 875 ArrayRef<SourceLocation> SelLocs) { 876 ParamsAndSelLocs = nullptr; 877 NumParams = Params.size(); 878 if (Params.empty() && SelLocs.empty()) 879 return; 880 881 static_assert(alignof(ParmVarDecl *) >= alignof(SourceLocation), 882 "Alignment not sufficient for SourceLocation"); 883 884 unsigned Size = sizeof(ParmVarDecl *) * NumParams + 885 sizeof(SourceLocation) * SelLocs.size(); 886 ParamsAndSelLocs = C.Allocate(Size); 887 std::copy(Params.begin(), Params.end(), getParams()); 888 std::copy(SelLocs.begin(), SelLocs.end(), getStoredSelLocs()); 889 } 890 891 void ObjCMethodDecl::getSelectorLocs( 892 SmallVectorImpl<SourceLocation> &SelLocs) const { 893 for (unsigned i = 0, e = getNumSelectorLocs(); i != e; ++i) 894 SelLocs.push_back(getSelectorLoc(i)); 895 } 896 897 void ObjCMethodDecl::setMethodParams(ASTContext &C, 898 ArrayRef<ParmVarDecl*> Params, 899 ArrayRef<SourceLocation> SelLocs) { 900 assert((!SelLocs.empty() || isImplicit()) && 901 "No selector locs for non-implicit method"); 902 if (isImplicit()) 903 return setParamsAndSelLocs(C, Params, llvm::None); 904 905 setSelLocsKind(hasStandardSelectorLocs(getSelector(), SelLocs, Params, 906 DeclEndLoc)); 907 if (getSelLocsKind() != SelLoc_NonStandard) 908 return setParamsAndSelLocs(C, Params, llvm::None); 909 910 setParamsAndSelLocs(C, Params, SelLocs); 911 } 912 913 /// A definition will return its interface declaration. 914 /// An interface declaration will return its definition. 915 /// Otherwise it will return itself. 916 ObjCMethodDecl *ObjCMethodDecl::getNextRedeclarationImpl() { 917 ASTContext &Ctx = getASTContext(); 918 ObjCMethodDecl *Redecl = nullptr; 919 if (hasRedeclaration()) 920 Redecl = const_cast<ObjCMethodDecl*>(Ctx.getObjCMethodRedeclaration(this)); 921 if (Redecl) 922 return Redecl; 923 924 auto *CtxD = cast<Decl>(getDeclContext()); 925 926 if (!CtxD->isInvalidDecl()) { 927 if (auto *IFD = dyn_cast<ObjCInterfaceDecl>(CtxD)) { 928 if (ObjCImplementationDecl *ImplD = Ctx.getObjCImplementation(IFD)) 929 if (!ImplD->isInvalidDecl()) 930 Redecl = ImplD->getMethod(getSelector(), isInstanceMethod()); 931 932 } else if (auto *CD = dyn_cast<ObjCCategoryDecl>(CtxD)) { 933 if (ObjCCategoryImplDecl *ImplD = Ctx.getObjCImplementation(CD)) 934 if (!ImplD->isInvalidDecl()) 935 Redecl = ImplD->getMethod(getSelector(), isInstanceMethod()); 936 937 } else if (auto *ImplD = dyn_cast<ObjCImplementationDecl>(CtxD)) { 938 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface()) 939 if (!IFD->isInvalidDecl()) 940 Redecl = IFD->getMethod(getSelector(), isInstanceMethod()); 941 942 } else if (auto *CImplD = dyn_cast<ObjCCategoryImplDecl>(CtxD)) { 943 if (ObjCCategoryDecl *CatD = CImplD->getCategoryDecl()) 944 if (!CatD->isInvalidDecl()) 945 Redecl = CatD->getMethod(getSelector(), isInstanceMethod()); 946 } 947 } 948 949 // Ensure that the discovered method redeclaration has a valid declaration 950 // context. Used to prevent infinite loops when iterating redeclarations in 951 // a partially invalid AST. 952 if (Redecl && cast<Decl>(Redecl->getDeclContext())->isInvalidDecl()) 953 Redecl = nullptr; 954 955 if (!Redecl && isRedeclaration()) { 956 // This is the last redeclaration, go back to the first method. 957 return cast<ObjCContainerDecl>(CtxD)->getMethod(getSelector(), 958 isInstanceMethod(), 959 /*AllowHidden=*/true); 960 } 961 962 return Redecl ? Redecl : this; 963 } 964 965 ObjCMethodDecl *ObjCMethodDecl::getCanonicalDecl() { 966 auto *CtxD = cast<Decl>(getDeclContext()); 967 const auto &Sel = getSelector(); 968 969 if (auto *ImplD = dyn_cast<ObjCImplementationDecl>(CtxD)) { 970 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface()) { 971 // When the container is the ObjCImplementationDecl (the primary 972 // @implementation), then the canonical Decl is either in 973 // the class Interface, or in any of its extension. 974 // 975 // So when we don't find it in the ObjCInterfaceDecl, 976 // sift through extensions too. 977 if (ObjCMethodDecl *MD = IFD->getMethod(Sel, isInstanceMethod())) 978 return MD; 979 for (auto *Ext : IFD->known_extensions()) 980 if (ObjCMethodDecl *MD = Ext->getMethod(Sel, isInstanceMethod())) 981 return MD; 982 } 983 } else if (auto *CImplD = dyn_cast<ObjCCategoryImplDecl>(CtxD)) { 984 if (ObjCCategoryDecl *CatD = CImplD->getCategoryDecl()) 985 if (ObjCMethodDecl *MD = CatD->getMethod(Sel, isInstanceMethod())) 986 return MD; 987 } 988 989 if (isRedeclaration()) { 990 // It is possible that we have not done deserializing the ObjCMethod yet. 991 ObjCMethodDecl *MD = 992 cast<ObjCContainerDecl>(CtxD)->getMethod(Sel, isInstanceMethod(), 993 /*AllowHidden=*/true); 994 return MD ? MD : this; 995 } 996 997 return this; 998 } 999 1000 SourceLocation ObjCMethodDecl::getEndLoc() const { 1001 if (Stmt *Body = getBody()) 1002 return Body->getEndLoc(); 1003 return DeclEndLoc; 1004 } 1005 1006 ObjCMethodFamily ObjCMethodDecl::getMethodFamily() const { 1007 auto family = static_cast<ObjCMethodFamily>(ObjCMethodDeclBits.Family); 1008 if (family != static_cast<unsigned>(InvalidObjCMethodFamily)) 1009 return family; 1010 1011 // Check for an explicit attribute. 1012 if (const ObjCMethodFamilyAttr *attr = getAttr<ObjCMethodFamilyAttr>()) { 1013 // The unfortunate necessity of mapping between enums here is due 1014 // to the attributes framework. 1015 switch (attr->getFamily()) { 1016 case ObjCMethodFamilyAttr::OMF_None: family = OMF_None; break; 1017 case ObjCMethodFamilyAttr::OMF_alloc: family = OMF_alloc; break; 1018 case ObjCMethodFamilyAttr::OMF_copy: family = OMF_copy; break; 1019 case ObjCMethodFamilyAttr::OMF_init: family = OMF_init; break; 1020 case ObjCMethodFamilyAttr::OMF_mutableCopy: family = OMF_mutableCopy; break; 1021 case ObjCMethodFamilyAttr::OMF_new: family = OMF_new; break; 1022 } 1023 ObjCMethodDeclBits.Family = family; 1024 return family; 1025 } 1026 1027 family = getSelector().getMethodFamily(); 1028 switch (family) { 1029 case OMF_None: break; 1030 1031 // init only has a conventional meaning for an instance method, and 1032 // it has to return an object. 1033 case OMF_init: 1034 if (!isInstanceMethod() || !getReturnType()->isObjCObjectPointerType()) 1035 family = OMF_None; 1036 break; 1037 1038 // alloc/copy/new have a conventional meaning for both class and 1039 // instance methods, but they require an object return. 1040 case OMF_alloc: 1041 case OMF_copy: 1042 case OMF_mutableCopy: 1043 case OMF_new: 1044 if (!getReturnType()->isObjCObjectPointerType()) 1045 family = OMF_None; 1046 break; 1047 1048 // These selectors have a conventional meaning only for instance methods. 1049 case OMF_dealloc: 1050 case OMF_finalize: 1051 case OMF_retain: 1052 case OMF_release: 1053 case OMF_autorelease: 1054 case OMF_retainCount: 1055 case OMF_self: 1056 if (!isInstanceMethod()) 1057 family = OMF_None; 1058 break; 1059 1060 case OMF_initialize: 1061 if (isInstanceMethod() || !getReturnType()->isVoidType()) 1062 family = OMF_None; 1063 break; 1064 1065 case OMF_performSelector: 1066 if (!isInstanceMethod() || !getReturnType()->isObjCIdType()) 1067 family = OMF_None; 1068 else { 1069 unsigned noParams = param_size(); 1070 if (noParams < 1 || noParams > 3) 1071 family = OMF_None; 1072 else { 1073 ObjCMethodDecl::param_type_iterator it = param_type_begin(); 1074 QualType ArgT = (*it); 1075 if (!ArgT->isObjCSelType()) { 1076 family = OMF_None; 1077 break; 1078 } 1079 while (--noParams) { 1080 it++; 1081 ArgT = (*it); 1082 if (!ArgT->isObjCIdType()) { 1083 family = OMF_None; 1084 break; 1085 } 1086 } 1087 } 1088 } 1089 break; 1090 1091 } 1092 1093 // Cache the result. 1094 ObjCMethodDeclBits.Family = family; 1095 return family; 1096 } 1097 1098 QualType ObjCMethodDecl::getSelfType(ASTContext &Context, 1099 const ObjCInterfaceDecl *OID, 1100 bool &selfIsPseudoStrong, 1101 bool &selfIsConsumed) const { 1102 QualType selfTy; 1103 selfIsPseudoStrong = false; 1104 selfIsConsumed = false; 1105 if (isInstanceMethod()) { 1106 // There may be no interface context due to error in declaration 1107 // of the interface (which has been reported). Recover gracefully. 1108 if (OID) { 1109 selfTy = Context.getObjCInterfaceType(OID); 1110 selfTy = Context.getObjCObjectPointerType(selfTy); 1111 } else { 1112 selfTy = Context.getObjCIdType(); 1113 } 1114 } else // we have a factory method. 1115 selfTy = Context.getObjCClassType(); 1116 1117 if (Context.getLangOpts().ObjCAutoRefCount) { 1118 if (isInstanceMethod()) { 1119 selfIsConsumed = hasAttr<NSConsumesSelfAttr>(); 1120 1121 // 'self' is always __strong. It's actually pseudo-strong except 1122 // in init methods (or methods labeled ns_consumes_self), though. 1123 Qualifiers qs; 1124 qs.setObjCLifetime(Qualifiers::OCL_Strong); 1125 selfTy = Context.getQualifiedType(selfTy, qs); 1126 1127 // In addition, 'self' is const unless this is an init method. 1128 if (getMethodFamily() != OMF_init && !selfIsConsumed) { 1129 selfTy = selfTy.withConst(); 1130 selfIsPseudoStrong = true; 1131 } 1132 } 1133 else { 1134 assert(isClassMethod()); 1135 // 'self' is always const in class methods. 1136 selfTy = selfTy.withConst(); 1137 selfIsPseudoStrong = true; 1138 } 1139 } 1140 return selfTy; 1141 } 1142 1143 void ObjCMethodDecl::createImplicitParams(ASTContext &Context, 1144 const ObjCInterfaceDecl *OID) { 1145 bool selfIsPseudoStrong, selfIsConsumed; 1146 QualType selfTy = 1147 getSelfType(Context, OID, selfIsPseudoStrong, selfIsConsumed); 1148 auto *Self = ImplicitParamDecl::Create(Context, this, SourceLocation(), 1149 &Context.Idents.get("self"), selfTy, 1150 ImplicitParamDecl::ObjCSelf); 1151 setSelfDecl(Self); 1152 1153 if (selfIsConsumed) 1154 Self->addAttr(NSConsumedAttr::CreateImplicit(Context)); 1155 1156 if (selfIsPseudoStrong) 1157 Self->setARCPseudoStrong(true); 1158 1159 setCmdDecl(ImplicitParamDecl::Create( 1160 Context, this, SourceLocation(), &Context.Idents.get("_cmd"), 1161 Context.getObjCSelType(), ImplicitParamDecl::ObjCCmd)); 1162 } 1163 1164 ObjCInterfaceDecl *ObjCMethodDecl::getClassInterface() { 1165 if (auto *ID = dyn_cast<ObjCInterfaceDecl>(getDeclContext())) 1166 return ID; 1167 if (auto *CD = dyn_cast<ObjCCategoryDecl>(getDeclContext())) 1168 return CD->getClassInterface(); 1169 if (auto *IMD = dyn_cast<ObjCImplDecl>(getDeclContext())) 1170 return IMD->getClassInterface(); 1171 if (isa<ObjCProtocolDecl>(getDeclContext())) 1172 return nullptr; 1173 llvm_unreachable("unknown method context"); 1174 } 1175 1176 ObjCCategoryDecl *ObjCMethodDecl::getCategory() { 1177 if (auto *CD = dyn_cast<ObjCCategoryDecl>(getDeclContext())) 1178 return CD; 1179 if (auto *IMD = dyn_cast<ObjCCategoryImplDecl>(getDeclContext())) 1180 return IMD->getCategoryDecl(); 1181 return nullptr; 1182 } 1183 1184 SourceRange ObjCMethodDecl::getReturnTypeSourceRange() const { 1185 const auto *TSI = getReturnTypeSourceInfo(); 1186 if (TSI) 1187 return TSI->getTypeLoc().getSourceRange(); 1188 return SourceRange(); 1189 } 1190 1191 QualType ObjCMethodDecl::getSendResultType() const { 1192 ASTContext &Ctx = getASTContext(); 1193 return getReturnType().getNonLValueExprType(Ctx) 1194 .substObjCTypeArgs(Ctx, {}, ObjCSubstitutionContext::Result); 1195 } 1196 1197 QualType ObjCMethodDecl::getSendResultType(QualType receiverType) const { 1198 // FIXME: Handle related result types here. 1199 1200 return getReturnType().getNonLValueExprType(getASTContext()) 1201 .substObjCMemberType(receiverType, getDeclContext(), 1202 ObjCSubstitutionContext::Result); 1203 } 1204 1205 static void CollectOverriddenMethodsRecurse(const ObjCContainerDecl *Container, 1206 const ObjCMethodDecl *Method, 1207 SmallVectorImpl<const ObjCMethodDecl *> &Methods, 1208 bool MovedToSuper) { 1209 if (!Container) 1210 return; 1211 1212 // In categories look for overridden methods from protocols. A method from 1213 // category is not "overridden" since it is considered as the "same" method 1214 // (same USR) as the one from the interface. 1215 if (const auto *Category = dyn_cast<ObjCCategoryDecl>(Container)) { 1216 // Check whether we have a matching method at this category but only if we 1217 // are at the super class level. 1218 if (MovedToSuper) 1219 if (ObjCMethodDecl * 1220 Overridden = Container->getMethod(Method->getSelector(), 1221 Method->isInstanceMethod(), 1222 /*AllowHidden=*/true)) 1223 if (Method != Overridden) { 1224 // We found an override at this category; there is no need to look 1225 // into its protocols. 1226 Methods.push_back(Overridden); 1227 return; 1228 } 1229 1230 for (const auto *P : Category->protocols()) 1231 CollectOverriddenMethodsRecurse(P, Method, Methods, MovedToSuper); 1232 return; 1233 } 1234 1235 // Check whether we have a matching method at this level. 1236 if (const ObjCMethodDecl * 1237 Overridden = Container->getMethod(Method->getSelector(), 1238 Method->isInstanceMethod(), 1239 /*AllowHidden=*/true)) 1240 if (Method != Overridden) { 1241 // We found an override at this level; there is no need to look 1242 // into other protocols or categories. 1243 Methods.push_back(Overridden); 1244 return; 1245 } 1246 1247 if (const auto *Protocol = dyn_cast<ObjCProtocolDecl>(Container)){ 1248 for (const auto *P : Protocol->protocols()) 1249 CollectOverriddenMethodsRecurse(P, Method, Methods, MovedToSuper); 1250 } 1251 1252 if (const auto *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) { 1253 for (const auto *P : Interface->protocols()) 1254 CollectOverriddenMethodsRecurse(P, Method, Methods, MovedToSuper); 1255 1256 for (const auto *Cat : Interface->known_categories()) 1257 CollectOverriddenMethodsRecurse(Cat, Method, Methods, MovedToSuper); 1258 1259 if (const ObjCInterfaceDecl *Super = Interface->getSuperClass()) 1260 return CollectOverriddenMethodsRecurse(Super, Method, Methods, 1261 /*MovedToSuper=*/true); 1262 } 1263 } 1264 1265 static inline void CollectOverriddenMethods(const ObjCContainerDecl *Container, 1266 const ObjCMethodDecl *Method, 1267 SmallVectorImpl<const ObjCMethodDecl *> &Methods) { 1268 CollectOverriddenMethodsRecurse(Container, Method, Methods, 1269 /*MovedToSuper=*/false); 1270 } 1271 1272 static void collectOverriddenMethodsSlow(const ObjCMethodDecl *Method, 1273 SmallVectorImpl<const ObjCMethodDecl *> &overridden) { 1274 assert(Method->isOverriding()); 1275 1276 if (const auto *ProtD = 1277 dyn_cast<ObjCProtocolDecl>(Method->getDeclContext())) { 1278 CollectOverriddenMethods(ProtD, Method, overridden); 1279 1280 } else if (const auto *IMD = 1281 dyn_cast<ObjCImplDecl>(Method->getDeclContext())) { 1282 const ObjCInterfaceDecl *ID = IMD->getClassInterface(); 1283 if (!ID) 1284 return; 1285 // Start searching for overridden methods using the method from the 1286 // interface as starting point. 1287 if (const ObjCMethodDecl *IFaceMeth = ID->getMethod(Method->getSelector(), 1288 Method->isInstanceMethod(), 1289 /*AllowHidden=*/true)) 1290 Method = IFaceMeth; 1291 CollectOverriddenMethods(ID, Method, overridden); 1292 1293 } else if (const auto *CatD = 1294 dyn_cast<ObjCCategoryDecl>(Method->getDeclContext())) { 1295 const ObjCInterfaceDecl *ID = CatD->getClassInterface(); 1296 if (!ID) 1297 return; 1298 // Start searching for overridden methods using the method from the 1299 // interface as starting point. 1300 if (const ObjCMethodDecl *IFaceMeth = ID->getMethod(Method->getSelector(), 1301 Method->isInstanceMethod(), 1302 /*AllowHidden=*/true)) 1303 Method = IFaceMeth; 1304 CollectOverriddenMethods(ID, Method, overridden); 1305 1306 } else { 1307 CollectOverriddenMethods( 1308 dyn_cast_or_null<ObjCContainerDecl>(Method->getDeclContext()), 1309 Method, overridden); 1310 } 1311 } 1312 1313 void ObjCMethodDecl::getOverriddenMethods( 1314 SmallVectorImpl<const ObjCMethodDecl *> &Overridden) const { 1315 const ObjCMethodDecl *Method = this; 1316 1317 if (Method->isRedeclaration()) { 1318 Method = cast<ObjCContainerDecl>(Method->getDeclContext()) 1319 ->getMethod(Method->getSelector(), Method->isInstanceMethod(), 1320 /*AllowHidden=*/true); 1321 } 1322 1323 if (Method->isOverriding()) { 1324 collectOverriddenMethodsSlow(Method, Overridden); 1325 assert(!Overridden.empty() && 1326 "ObjCMethodDecl's overriding bit is not as expected"); 1327 } 1328 } 1329 1330 const ObjCPropertyDecl * 1331 ObjCMethodDecl::findPropertyDecl(bool CheckOverrides) const { 1332 Selector Sel = getSelector(); 1333 unsigned NumArgs = Sel.getNumArgs(); 1334 if (NumArgs > 1) 1335 return nullptr; 1336 1337 if (isPropertyAccessor()) { 1338 const auto *Container = cast<ObjCContainerDecl>(getParent()); 1339 // For accessor stubs, go back to the interface. 1340 if (auto *ImplDecl = dyn_cast<ObjCImplDecl>(Container)) 1341 if (isSynthesizedAccessorStub()) 1342 Container = ImplDecl->getClassInterface(); 1343 1344 bool IsGetter = (NumArgs == 0); 1345 bool IsInstance = isInstanceMethod(); 1346 1347 /// Local function that attempts to find a matching property within the 1348 /// given Objective-C container. 1349 auto findMatchingProperty = 1350 [&](const ObjCContainerDecl *Container) -> const ObjCPropertyDecl * { 1351 if (IsInstance) { 1352 for (const auto *I : Container->instance_properties()) { 1353 Selector NextSel = IsGetter ? I->getGetterName() 1354 : I->getSetterName(); 1355 if (NextSel == Sel) 1356 return I; 1357 } 1358 } else { 1359 for (const auto *I : Container->class_properties()) { 1360 Selector NextSel = IsGetter ? I->getGetterName() 1361 : I->getSetterName(); 1362 if (NextSel == Sel) 1363 return I; 1364 } 1365 } 1366 1367 return nullptr; 1368 }; 1369 1370 // Look in the container we were given. 1371 if (const auto *Found = findMatchingProperty(Container)) 1372 return Found; 1373 1374 // If we're in a category or extension, look in the main class. 1375 const ObjCInterfaceDecl *ClassDecl = nullptr; 1376 if (const auto *Category = dyn_cast<ObjCCategoryDecl>(Container)) { 1377 ClassDecl = Category->getClassInterface(); 1378 if (const auto *Found = findMatchingProperty(ClassDecl)) 1379 return Found; 1380 } else { 1381 // Determine whether the container is a class. 1382 ClassDecl = cast<ObjCInterfaceDecl>(Container); 1383 } 1384 assert(ClassDecl && "Failed to find main class"); 1385 1386 // If we have a class, check its visible extensions. 1387 for (const auto *Ext : ClassDecl->visible_extensions()) { 1388 if (Ext == Container) 1389 continue; 1390 if (const auto *Found = findMatchingProperty(Ext)) 1391 return Found; 1392 } 1393 1394 assert(isSynthesizedAccessorStub() && "expected an accessor stub"); 1395 1396 for (const auto *Cat : ClassDecl->known_categories()) { 1397 if (Cat == Container) 1398 continue; 1399 if (const auto *Found = findMatchingProperty(Cat)) 1400 return Found; 1401 } 1402 1403 llvm_unreachable("Marked as a property accessor but no property found!"); 1404 } 1405 1406 if (!CheckOverrides) 1407 return nullptr; 1408 1409 using OverridesTy = SmallVector<const ObjCMethodDecl *, 8>; 1410 1411 OverridesTy Overrides; 1412 getOverriddenMethods(Overrides); 1413 for (const auto *Override : Overrides) 1414 if (const ObjCPropertyDecl *Prop = Override->findPropertyDecl(false)) 1415 return Prop; 1416 1417 return nullptr; 1418 } 1419 1420 //===----------------------------------------------------------------------===// 1421 // ObjCTypeParamDecl 1422 //===----------------------------------------------------------------------===// 1423 1424 void ObjCTypeParamDecl::anchor() {} 1425 1426 ObjCTypeParamDecl *ObjCTypeParamDecl::Create(ASTContext &ctx, DeclContext *dc, 1427 ObjCTypeParamVariance variance, 1428 SourceLocation varianceLoc, 1429 unsigned index, 1430 SourceLocation nameLoc, 1431 IdentifierInfo *name, 1432 SourceLocation colonLoc, 1433 TypeSourceInfo *boundInfo) { 1434 auto *TPDecl = 1435 new (ctx, dc) ObjCTypeParamDecl(ctx, dc, variance, varianceLoc, index, 1436 nameLoc, name, colonLoc, boundInfo); 1437 QualType TPType = ctx.getObjCTypeParamType(TPDecl, {}); 1438 TPDecl->setTypeForDecl(TPType.getTypePtr()); 1439 return TPDecl; 1440 } 1441 1442 ObjCTypeParamDecl *ObjCTypeParamDecl::CreateDeserialized(ASTContext &ctx, 1443 unsigned ID) { 1444 return new (ctx, ID) ObjCTypeParamDecl(ctx, nullptr, 1445 ObjCTypeParamVariance::Invariant, 1446 SourceLocation(), 0, SourceLocation(), 1447 nullptr, SourceLocation(), nullptr); 1448 } 1449 1450 SourceRange ObjCTypeParamDecl::getSourceRange() const { 1451 SourceLocation startLoc = VarianceLoc; 1452 if (startLoc.isInvalid()) 1453 startLoc = getLocation(); 1454 1455 if (hasExplicitBound()) { 1456 return SourceRange(startLoc, 1457 getTypeSourceInfo()->getTypeLoc().getEndLoc()); 1458 } 1459 1460 return SourceRange(startLoc); 1461 } 1462 1463 //===----------------------------------------------------------------------===// 1464 // ObjCTypeParamList 1465 //===----------------------------------------------------------------------===// 1466 ObjCTypeParamList::ObjCTypeParamList(SourceLocation lAngleLoc, 1467 ArrayRef<ObjCTypeParamDecl *> typeParams, 1468 SourceLocation rAngleLoc) 1469 : Brackets(lAngleLoc, rAngleLoc), NumParams(typeParams.size()) { 1470 std::copy(typeParams.begin(), typeParams.end(), begin()); 1471 } 1472 1473 ObjCTypeParamList *ObjCTypeParamList::create( 1474 ASTContext &ctx, 1475 SourceLocation lAngleLoc, 1476 ArrayRef<ObjCTypeParamDecl *> typeParams, 1477 SourceLocation rAngleLoc) { 1478 void *mem = 1479 ctx.Allocate(totalSizeToAlloc<ObjCTypeParamDecl *>(typeParams.size()), 1480 alignof(ObjCTypeParamList)); 1481 return new (mem) ObjCTypeParamList(lAngleLoc, typeParams, rAngleLoc); 1482 } 1483 1484 void ObjCTypeParamList::gatherDefaultTypeArgs( 1485 SmallVectorImpl<QualType> &typeArgs) const { 1486 typeArgs.reserve(size()); 1487 for (auto typeParam : *this) 1488 typeArgs.push_back(typeParam->getUnderlyingType()); 1489 } 1490 1491 //===----------------------------------------------------------------------===// 1492 // ObjCInterfaceDecl 1493 //===----------------------------------------------------------------------===// 1494 1495 ObjCInterfaceDecl *ObjCInterfaceDecl::Create(const ASTContext &C, 1496 DeclContext *DC, 1497 SourceLocation atLoc, 1498 IdentifierInfo *Id, 1499 ObjCTypeParamList *typeParamList, 1500 ObjCInterfaceDecl *PrevDecl, 1501 SourceLocation ClassLoc, 1502 bool isInternal){ 1503 auto *Result = new (C, DC) 1504 ObjCInterfaceDecl(C, DC, atLoc, Id, typeParamList, ClassLoc, PrevDecl, 1505 isInternal); 1506 Result->Data.setInt(!C.getLangOpts().Modules); 1507 C.getObjCInterfaceType(Result, PrevDecl); 1508 return Result; 1509 } 1510 1511 ObjCInterfaceDecl *ObjCInterfaceDecl::CreateDeserialized(const ASTContext &C, 1512 unsigned ID) { 1513 auto *Result = new (C, ID) 1514 ObjCInterfaceDecl(C, nullptr, SourceLocation(), nullptr, nullptr, 1515 SourceLocation(), nullptr, false); 1516 Result->Data.setInt(!C.getLangOpts().Modules); 1517 return Result; 1518 } 1519 1520 ObjCInterfaceDecl::ObjCInterfaceDecl(const ASTContext &C, DeclContext *DC, 1521 SourceLocation AtLoc, IdentifierInfo *Id, 1522 ObjCTypeParamList *typeParamList, 1523 SourceLocation CLoc, 1524 ObjCInterfaceDecl *PrevDecl, 1525 bool IsInternal) 1526 : ObjCContainerDecl(ObjCInterface, DC, Id, CLoc, AtLoc), 1527 redeclarable_base(C) { 1528 setPreviousDecl(PrevDecl); 1529 1530 // Copy the 'data' pointer over. 1531 if (PrevDecl) 1532 Data = PrevDecl->Data; 1533 1534 setImplicit(IsInternal); 1535 1536 setTypeParamList(typeParamList); 1537 } 1538 1539 void ObjCInterfaceDecl::LoadExternalDefinition() const { 1540 assert(data().ExternallyCompleted && "Class is not externally completed"); 1541 data().ExternallyCompleted = false; 1542 getASTContext().getExternalSource()->CompleteType( 1543 const_cast<ObjCInterfaceDecl *>(this)); 1544 } 1545 1546 void ObjCInterfaceDecl::setExternallyCompleted() { 1547 assert(getASTContext().getExternalSource() && 1548 "Class can't be externally completed without an external source"); 1549 assert(hasDefinition() && 1550 "Forward declarations can't be externally completed"); 1551 data().ExternallyCompleted = true; 1552 } 1553 1554 void ObjCInterfaceDecl::setHasDesignatedInitializers() { 1555 // Check for a complete definition and recover if not so. 1556 if (!isThisDeclarationADefinition()) 1557 return; 1558 data().HasDesignatedInitializers = true; 1559 } 1560 1561 bool ObjCInterfaceDecl::hasDesignatedInitializers() const { 1562 // Check for a complete definition and recover if not so. 1563 if (!isThisDeclarationADefinition()) 1564 return false; 1565 if (data().ExternallyCompleted) 1566 LoadExternalDefinition(); 1567 1568 return data().HasDesignatedInitializers; 1569 } 1570 1571 StringRef 1572 ObjCInterfaceDecl::getObjCRuntimeNameAsString() const { 1573 if (const auto *ObjCRTName = getAttr<ObjCRuntimeNameAttr>()) 1574 return ObjCRTName->getMetadataName(); 1575 1576 return getName(); 1577 } 1578 1579 StringRef 1580 ObjCImplementationDecl::getObjCRuntimeNameAsString() const { 1581 if (ObjCInterfaceDecl *ID = 1582 const_cast<ObjCImplementationDecl*>(this)->getClassInterface()) 1583 return ID->getObjCRuntimeNameAsString(); 1584 1585 return getName(); 1586 } 1587 1588 ObjCImplementationDecl *ObjCInterfaceDecl::getImplementation() const { 1589 if (const ObjCInterfaceDecl *Def = getDefinition()) { 1590 if (data().ExternallyCompleted) 1591 LoadExternalDefinition(); 1592 1593 return getASTContext().getObjCImplementation( 1594 const_cast<ObjCInterfaceDecl*>(Def)); 1595 } 1596 1597 // FIXME: Should make sure no callers ever do this. 1598 return nullptr; 1599 } 1600 1601 void ObjCInterfaceDecl::setImplementation(ObjCImplementationDecl *ImplD) { 1602 getASTContext().setObjCImplementation(getDefinition(), ImplD); 1603 } 1604 1605 namespace { 1606 1607 struct SynthesizeIvarChunk { 1608 uint64_t Size; 1609 ObjCIvarDecl *Ivar; 1610 1611 SynthesizeIvarChunk(uint64_t size, ObjCIvarDecl *ivar) 1612 : Size(size), Ivar(ivar) {} 1613 }; 1614 1615 bool operator<(const SynthesizeIvarChunk & LHS, 1616 const SynthesizeIvarChunk &RHS) { 1617 return LHS.Size < RHS.Size; 1618 } 1619 1620 } // namespace 1621 1622 /// all_declared_ivar_begin - return first ivar declared in this class, 1623 /// its extensions and its implementation. Lazily build the list on first 1624 /// access. 1625 /// 1626 /// Caveat: The list returned by this method reflects the current 1627 /// state of the parser. The cache will be updated for every ivar 1628 /// added by an extension or the implementation when they are 1629 /// encountered. 1630 /// See also ObjCIvarDecl::Create(). 1631 ObjCIvarDecl *ObjCInterfaceDecl::all_declared_ivar_begin() { 1632 // FIXME: Should make sure no callers ever do this. 1633 if (!hasDefinition()) 1634 return nullptr; 1635 1636 ObjCIvarDecl *curIvar = nullptr; 1637 if (!data().IvarList) { 1638 if (!ivar_empty()) { 1639 ObjCInterfaceDecl::ivar_iterator I = ivar_begin(), E = ivar_end(); 1640 data().IvarList = *I; ++I; 1641 for (curIvar = data().IvarList; I != E; curIvar = *I, ++I) 1642 curIvar->setNextIvar(*I); 1643 } 1644 1645 for (const auto *Ext : known_extensions()) { 1646 if (!Ext->ivar_empty()) { 1647 ObjCCategoryDecl::ivar_iterator 1648 I = Ext->ivar_begin(), 1649 E = Ext->ivar_end(); 1650 if (!data().IvarList) { 1651 data().IvarList = *I; ++I; 1652 curIvar = data().IvarList; 1653 } 1654 for ( ;I != E; curIvar = *I, ++I) 1655 curIvar->setNextIvar(*I); 1656 } 1657 } 1658 data().IvarListMissingImplementation = true; 1659 } 1660 1661 // cached and complete! 1662 if (!data().IvarListMissingImplementation) 1663 return data().IvarList; 1664 1665 if (ObjCImplementationDecl *ImplDecl = getImplementation()) { 1666 data().IvarListMissingImplementation = false; 1667 if (!ImplDecl->ivar_empty()) { 1668 SmallVector<SynthesizeIvarChunk, 16> layout; 1669 for (auto *IV : ImplDecl->ivars()) { 1670 if (IV->getSynthesize() && !IV->isInvalidDecl()) { 1671 layout.push_back(SynthesizeIvarChunk( 1672 IV->getASTContext().getTypeSize(IV->getType()), IV)); 1673 continue; 1674 } 1675 if (!data().IvarList) 1676 data().IvarList = IV; 1677 else 1678 curIvar->setNextIvar(IV); 1679 curIvar = IV; 1680 } 1681 1682 if (!layout.empty()) { 1683 // Order synthesized ivars by their size. 1684 llvm::stable_sort(layout); 1685 unsigned Ix = 0, EIx = layout.size(); 1686 if (!data().IvarList) { 1687 data().IvarList = layout[0].Ivar; Ix++; 1688 curIvar = data().IvarList; 1689 } 1690 for ( ; Ix != EIx; curIvar = layout[Ix].Ivar, Ix++) 1691 curIvar->setNextIvar(layout[Ix].Ivar); 1692 } 1693 } 1694 } 1695 return data().IvarList; 1696 } 1697 1698 /// FindCategoryDeclaration - Finds category declaration in the list of 1699 /// categories for this class and returns it. Name of the category is passed 1700 /// in 'CategoryId'. If category not found, return 0; 1701 /// 1702 ObjCCategoryDecl * 1703 ObjCInterfaceDecl::FindCategoryDeclaration(IdentifierInfo *CategoryId) const { 1704 // FIXME: Should make sure no callers ever do this. 1705 if (!hasDefinition()) 1706 return nullptr; 1707 1708 if (data().ExternallyCompleted) 1709 LoadExternalDefinition(); 1710 1711 for (auto *Cat : visible_categories()) 1712 if (Cat->getIdentifier() == CategoryId) 1713 return Cat; 1714 1715 return nullptr; 1716 } 1717 1718 ObjCMethodDecl * 1719 ObjCInterfaceDecl::getCategoryInstanceMethod(Selector Sel) const { 1720 for (const auto *Cat : visible_categories()) { 1721 if (ObjCCategoryImplDecl *Impl = Cat->getImplementation()) 1722 if (ObjCMethodDecl *MD = Impl->getInstanceMethod(Sel)) 1723 return MD; 1724 } 1725 1726 return nullptr; 1727 } 1728 1729 ObjCMethodDecl *ObjCInterfaceDecl::getCategoryClassMethod(Selector Sel) const { 1730 for (const auto *Cat : visible_categories()) { 1731 if (ObjCCategoryImplDecl *Impl = Cat->getImplementation()) 1732 if (ObjCMethodDecl *MD = Impl->getClassMethod(Sel)) 1733 return MD; 1734 } 1735 1736 return nullptr; 1737 } 1738 1739 /// ClassImplementsProtocol - Checks that 'lProto' protocol 1740 /// has been implemented in IDecl class, its super class or categories (if 1741 /// lookupCategory is true). 1742 bool ObjCInterfaceDecl::ClassImplementsProtocol(ObjCProtocolDecl *lProto, 1743 bool lookupCategory, 1744 bool RHSIsQualifiedID) { 1745 if (!hasDefinition()) 1746 return false; 1747 1748 ObjCInterfaceDecl *IDecl = this; 1749 // 1st, look up the class. 1750 for (auto *PI : IDecl->protocols()){ 1751 if (getASTContext().ProtocolCompatibleWithProtocol(lProto, PI)) 1752 return true; 1753 // This is dubious and is added to be compatible with gcc. In gcc, it is 1754 // also allowed assigning a protocol-qualified 'id' type to a LHS object 1755 // when protocol in qualified LHS is in list of protocols in the rhs 'id' 1756 // object. This IMO, should be a bug. 1757 // FIXME: Treat this as an extension, and flag this as an error when GCC 1758 // extensions are not enabled. 1759 if (RHSIsQualifiedID && 1760 getASTContext().ProtocolCompatibleWithProtocol(PI, lProto)) 1761 return true; 1762 } 1763 1764 // 2nd, look up the category. 1765 if (lookupCategory) 1766 for (const auto *Cat : visible_categories()) { 1767 for (auto *PI : Cat->protocols()) 1768 if (getASTContext().ProtocolCompatibleWithProtocol(lProto, PI)) 1769 return true; 1770 } 1771 1772 // 3rd, look up the super class(s) 1773 if (IDecl->getSuperClass()) 1774 return 1775 IDecl->getSuperClass()->ClassImplementsProtocol(lProto, lookupCategory, 1776 RHSIsQualifiedID); 1777 1778 return false; 1779 } 1780 1781 //===----------------------------------------------------------------------===// 1782 // ObjCIvarDecl 1783 //===----------------------------------------------------------------------===// 1784 1785 void ObjCIvarDecl::anchor() {} 1786 1787 ObjCIvarDecl *ObjCIvarDecl::Create(ASTContext &C, ObjCContainerDecl *DC, 1788 SourceLocation StartLoc, 1789 SourceLocation IdLoc, IdentifierInfo *Id, 1790 QualType T, TypeSourceInfo *TInfo, 1791 AccessControl ac, Expr *BW, 1792 bool synthesized) { 1793 if (DC) { 1794 // Ivar's can only appear in interfaces, implementations (via synthesized 1795 // properties), and class extensions (via direct declaration, or synthesized 1796 // properties). 1797 // 1798 // FIXME: This should really be asserting this: 1799 // (isa<ObjCCategoryDecl>(DC) && 1800 // cast<ObjCCategoryDecl>(DC)->IsClassExtension())) 1801 // but unfortunately we sometimes place ivars into non-class extension 1802 // categories on error. This breaks an AST invariant, and should not be 1803 // fixed. 1804 assert((isa<ObjCInterfaceDecl>(DC) || isa<ObjCImplementationDecl>(DC) || 1805 isa<ObjCCategoryDecl>(DC)) && 1806 "Invalid ivar decl context!"); 1807 // Once a new ivar is created in any of class/class-extension/implementation 1808 // decl contexts, the previously built IvarList must be rebuilt. 1809 auto *ID = dyn_cast<ObjCInterfaceDecl>(DC); 1810 if (!ID) { 1811 if (auto *IM = dyn_cast<ObjCImplementationDecl>(DC)) 1812 ID = IM->getClassInterface(); 1813 else 1814 ID = cast<ObjCCategoryDecl>(DC)->getClassInterface(); 1815 } 1816 ID->setIvarList(nullptr); 1817 } 1818 1819 return new (C, DC) ObjCIvarDecl(DC, StartLoc, IdLoc, Id, T, TInfo, ac, BW, 1820 synthesized); 1821 } 1822 1823 ObjCIvarDecl *ObjCIvarDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 1824 return new (C, ID) ObjCIvarDecl(nullptr, SourceLocation(), SourceLocation(), 1825 nullptr, QualType(), nullptr, 1826 ObjCIvarDecl::None, nullptr, false); 1827 } 1828 1829 const ObjCInterfaceDecl *ObjCIvarDecl::getContainingInterface() const { 1830 const auto *DC = cast<ObjCContainerDecl>(getDeclContext()); 1831 1832 switch (DC->getKind()) { 1833 default: 1834 case ObjCCategoryImpl: 1835 case ObjCProtocol: 1836 llvm_unreachable("invalid ivar container!"); 1837 1838 // Ivars can only appear in class extension categories. 1839 case ObjCCategory: { 1840 const auto *CD = cast<ObjCCategoryDecl>(DC); 1841 assert(CD->IsClassExtension() && "invalid container for ivar!"); 1842 return CD->getClassInterface(); 1843 } 1844 1845 case ObjCImplementation: 1846 return cast<ObjCImplementationDecl>(DC)->getClassInterface(); 1847 1848 case ObjCInterface: 1849 return cast<ObjCInterfaceDecl>(DC); 1850 } 1851 } 1852 1853 QualType ObjCIvarDecl::getUsageType(QualType objectType) const { 1854 return getType().substObjCMemberType(objectType, getDeclContext(), 1855 ObjCSubstitutionContext::Property); 1856 } 1857 1858 //===----------------------------------------------------------------------===// 1859 // ObjCAtDefsFieldDecl 1860 //===----------------------------------------------------------------------===// 1861 1862 void ObjCAtDefsFieldDecl::anchor() {} 1863 1864 ObjCAtDefsFieldDecl 1865 *ObjCAtDefsFieldDecl::Create(ASTContext &C, DeclContext *DC, 1866 SourceLocation StartLoc, SourceLocation IdLoc, 1867 IdentifierInfo *Id, QualType T, Expr *BW) { 1868 return new (C, DC) ObjCAtDefsFieldDecl(DC, StartLoc, IdLoc, Id, T, BW); 1869 } 1870 1871 ObjCAtDefsFieldDecl *ObjCAtDefsFieldDecl::CreateDeserialized(ASTContext &C, 1872 unsigned ID) { 1873 return new (C, ID) ObjCAtDefsFieldDecl(nullptr, SourceLocation(), 1874 SourceLocation(), nullptr, QualType(), 1875 nullptr); 1876 } 1877 1878 //===----------------------------------------------------------------------===// 1879 // ObjCProtocolDecl 1880 //===----------------------------------------------------------------------===// 1881 1882 void ObjCProtocolDecl::anchor() {} 1883 1884 ObjCProtocolDecl::ObjCProtocolDecl(ASTContext &C, DeclContext *DC, 1885 IdentifierInfo *Id, SourceLocation nameLoc, 1886 SourceLocation atStartLoc, 1887 ObjCProtocolDecl *PrevDecl) 1888 : ObjCContainerDecl(ObjCProtocol, DC, Id, nameLoc, atStartLoc), 1889 redeclarable_base(C) { 1890 setPreviousDecl(PrevDecl); 1891 if (PrevDecl) 1892 Data = PrevDecl->Data; 1893 } 1894 1895 ObjCProtocolDecl *ObjCProtocolDecl::Create(ASTContext &C, DeclContext *DC, 1896 IdentifierInfo *Id, 1897 SourceLocation nameLoc, 1898 SourceLocation atStartLoc, 1899 ObjCProtocolDecl *PrevDecl) { 1900 auto *Result = 1901 new (C, DC) ObjCProtocolDecl(C, DC, Id, nameLoc, atStartLoc, PrevDecl); 1902 Result->Data.setInt(!C.getLangOpts().Modules); 1903 return Result; 1904 } 1905 1906 ObjCProtocolDecl *ObjCProtocolDecl::CreateDeserialized(ASTContext &C, 1907 unsigned ID) { 1908 ObjCProtocolDecl *Result = 1909 new (C, ID) ObjCProtocolDecl(C, nullptr, nullptr, SourceLocation(), 1910 SourceLocation(), nullptr); 1911 Result->Data.setInt(!C.getLangOpts().Modules); 1912 return Result; 1913 } 1914 1915 bool ObjCProtocolDecl::isNonRuntimeProtocol() const { 1916 return hasAttr<ObjCNonRuntimeProtocolAttr>(); 1917 } 1918 1919 void ObjCProtocolDecl::getImpliedProtocols( 1920 llvm::DenseSet<const ObjCProtocolDecl *> &IPs) const { 1921 std::queue<const ObjCProtocolDecl *> WorkQueue; 1922 WorkQueue.push(this); 1923 1924 while (!WorkQueue.empty()) { 1925 const auto *PD = WorkQueue.front(); 1926 WorkQueue.pop(); 1927 for (const auto *Parent : PD->protocols()) { 1928 const auto *Can = Parent->getCanonicalDecl(); 1929 auto Result = IPs.insert(Can); 1930 if (Result.second) 1931 WorkQueue.push(Parent); 1932 } 1933 } 1934 } 1935 1936 ObjCProtocolDecl *ObjCProtocolDecl::lookupProtocolNamed(IdentifierInfo *Name) { 1937 ObjCProtocolDecl *PDecl = this; 1938 1939 if (Name == getIdentifier()) 1940 return PDecl; 1941 1942 for (auto *I : protocols()) 1943 if ((PDecl = I->lookupProtocolNamed(Name))) 1944 return PDecl; 1945 1946 return nullptr; 1947 } 1948 1949 // lookupMethod - Lookup a instance/class method in the protocol and protocols 1950 // it inherited. 1951 ObjCMethodDecl *ObjCProtocolDecl::lookupMethod(Selector Sel, 1952 bool isInstance) const { 1953 ObjCMethodDecl *MethodDecl = nullptr; 1954 1955 // If there is no definition or the definition is hidden, we don't find 1956 // anything. 1957 const ObjCProtocolDecl *Def = getDefinition(); 1958 if (!Def || !Def->isUnconditionallyVisible()) 1959 return nullptr; 1960 1961 if ((MethodDecl = getMethod(Sel, isInstance))) 1962 return MethodDecl; 1963 1964 for (const auto *I : protocols()) 1965 if ((MethodDecl = I->lookupMethod(Sel, isInstance))) 1966 return MethodDecl; 1967 return nullptr; 1968 } 1969 1970 void ObjCProtocolDecl::allocateDefinitionData() { 1971 assert(!Data.getPointer() && "Protocol already has a definition!"); 1972 Data.setPointer(new (getASTContext()) DefinitionData); 1973 Data.getPointer()->Definition = this; 1974 } 1975 1976 void ObjCProtocolDecl::startDefinition() { 1977 allocateDefinitionData(); 1978 1979 // Update all of the declarations with a pointer to the definition. 1980 for (auto *RD : redecls()) 1981 RD->Data = this->Data; 1982 } 1983 1984 void ObjCProtocolDecl::collectPropertiesToImplement(PropertyMap &PM, 1985 PropertyDeclOrder &PO) const { 1986 if (const ObjCProtocolDecl *PDecl = getDefinition()) { 1987 for (auto *Prop : PDecl->properties()) { 1988 // Insert into PM if not there already. 1989 PM.insert(std::make_pair( 1990 std::make_pair(Prop->getIdentifier(), Prop->isClassProperty()), 1991 Prop)); 1992 PO.push_back(Prop); 1993 } 1994 // Scan through protocol's protocols. 1995 for (const auto *PI : PDecl->protocols()) 1996 PI->collectPropertiesToImplement(PM, PO); 1997 } 1998 } 1999 2000 void ObjCProtocolDecl::collectInheritedProtocolProperties( 2001 const ObjCPropertyDecl *Property, ProtocolPropertySet &PS, 2002 PropertyDeclOrder &PO) const { 2003 if (const ObjCProtocolDecl *PDecl = getDefinition()) { 2004 if (!PS.insert(PDecl).second) 2005 return; 2006 for (auto *Prop : PDecl->properties()) { 2007 if (Prop == Property) 2008 continue; 2009 if (Prop->getIdentifier() == Property->getIdentifier()) { 2010 PO.push_back(Prop); 2011 return; 2012 } 2013 } 2014 // Scan through protocol's protocols which did not have a matching property. 2015 for (const auto *PI : PDecl->protocols()) 2016 PI->collectInheritedProtocolProperties(Property, PS, PO); 2017 } 2018 } 2019 2020 StringRef 2021 ObjCProtocolDecl::getObjCRuntimeNameAsString() const { 2022 if (const auto *ObjCRTName = getAttr<ObjCRuntimeNameAttr>()) 2023 return ObjCRTName->getMetadataName(); 2024 2025 return getName(); 2026 } 2027 2028 //===----------------------------------------------------------------------===// 2029 // ObjCCategoryDecl 2030 //===----------------------------------------------------------------------===// 2031 2032 void ObjCCategoryDecl::anchor() {} 2033 2034 ObjCCategoryDecl::ObjCCategoryDecl(DeclContext *DC, SourceLocation AtLoc, 2035 SourceLocation ClassNameLoc, 2036 SourceLocation CategoryNameLoc, 2037 IdentifierInfo *Id, ObjCInterfaceDecl *IDecl, 2038 ObjCTypeParamList *typeParamList, 2039 SourceLocation IvarLBraceLoc, 2040 SourceLocation IvarRBraceLoc) 2041 : ObjCContainerDecl(ObjCCategory, DC, Id, ClassNameLoc, AtLoc), 2042 ClassInterface(IDecl), CategoryNameLoc(CategoryNameLoc), 2043 IvarLBraceLoc(IvarLBraceLoc), IvarRBraceLoc(IvarRBraceLoc) { 2044 setTypeParamList(typeParamList); 2045 } 2046 2047 ObjCCategoryDecl *ObjCCategoryDecl::Create(ASTContext &C, DeclContext *DC, 2048 SourceLocation AtLoc, 2049 SourceLocation ClassNameLoc, 2050 SourceLocation CategoryNameLoc, 2051 IdentifierInfo *Id, 2052 ObjCInterfaceDecl *IDecl, 2053 ObjCTypeParamList *typeParamList, 2054 SourceLocation IvarLBraceLoc, 2055 SourceLocation IvarRBraceLoc) { 2056 auto *CatDecl = 2057 new (C, DC) ObjCCategoryDecl(DC, AtLoc, ClassNameLoc, CategoryNameLoc, Id, 2058 IDecl, typeParamList, IvarLBraceLoc, 2059 IvarRBraceLoc); 2060 if (IDecl) { 2061 // Link this category into its class's category list. 2062 CatDecl->NextClassCategory = IDecl->getCategoryListRaw(); 2063 if (IDecl->hasDefinition()) { 2064 IDecl->setCategoryListRaw(CatDecl); 2065 if (ASTMutationListener *L = C.getASTMutationListener()) 2066 L->AddedObjCCategoryToInterface(CatDecl, IDecl); 2067 } 2068 } 2069 2070 return CatDecl; 2071 } 2072 2073 ObjCCategoryDecl *ObjCCategoryDecl::CreateDeserialized(ASTContext &C, 2074 unsigned ID) { 2075 return new (C, ID) ObjCCategoryDecl(nullptr, SourceLocation(), 2076 SourceLocation(), SourceLocation(), 2077 nullptr, nullptr, nullptr); 2078 } 2079 2080 ObjCCategoryImplDecl *ObjCCategoryDecl::getImplementation() const { 2081 return getASTContext().getObjCImplementation( 2082 const_cast<ObjCCategoryDecl*>(this)); 2083 } 2084 2085 void ObjCCategoryDecl::setImplementation(ObjCCategoryImplDecl *ImplD) { 2086 getASTContext().setObjCImplementation(this, ImplD); 2087 } 2088 2089 void ObjCCategoryDecl::setTypeParamList(ObjCTypeParamList *TPL) { 2090 TypeParamList = TPL; 2091 if (!TPL) 2092 return; 2093 // Set the declaration context of each of the type parameters. 2094 for (auto *typeParam : *TypeParamList) 2095 typeParam->setDeclContext(this); 2096 } 2097 2098 //===----------------------------------------------------------------------===// 2099 // ObjCCategoryImplDecl 2100 //===----------------------------------------------------------------------===// 2101 2102 void ObjCCategoryImplDecl::anchor() {} 2103 2104 ObjCCategoryImplDecl * 2105 ObjCCategoryImplDecl::Create(ASTContext &C, DeclContext *DC, 2106 IdentifierInfo *Id, 2107 ObjCInterfaceDecl *ClassInterface, 2108 SourceLocation nameLoc, 2109 SourceLocation atStartLoc, 2110 SourceLocation CategoryNameLoc) { 2111 if (ClassInterface && ClassInterface->hasDefinition()) 2112 ClassInterface = ClassInterface->getDefinition(); 2113 return new (C, DC) ObjCCategoryImplDecl(DC, Id, ClassInterface, nameLoc, 2114 atStartLoc, CategoryNameLoc); 2115 } 2116 2117 ObjCCategoryImplDecl *ObjCCategoryImplDecl::CreateDeserialized(ASTContext &C, 2118 unsigned ID) { 2119 return new (C, ID) ObjCCategoryImplDecl(nullptr, nullptr, nullptr, 2120 SourceLocation(), SourceLocation(), 2121 SourceLocation()); 2122 } 2123 2124 ObjCCategoryDecl *ObjCCategoryImplDecl::getCategoryDecl() const { 2125 // The class interface might be NULL if we are working with invalid code. 2126 if (const ObjCInterfaceDecl *ID = getClassInterface()) 2127 return ID->FindCategoryDeclaration(getIdentifier()); 2128 return nullptr; 2129 } 2130 2131 void ObjCImplDecl::anchor() {} 2132 2133 void ObjCImplDecl::addPropertyImplementation(ObjCPropertyImplDecl *property) { 2134 // FIXME: The context should be correct before we get here. 2135 property->setLexicalDeclContext(this); 2136 addDecl(property); 2137 } 2138 2139 void ObjCImplDecl::setClassInterface(ObjCInterfaceDecl *IFace) { 2140 ASTContext &Ctx = getASTContext(); 2141 2142 if (auto *ImplD = dyn_cast_or_null<ObjCImplementationDecl>(this)) { 2143 if (IFace) 2144 Ctx.setObjCImplementation(IFace, ImplD); 2145 2146 } else if (auto *ImplD = dyn_cast_or_null<ObjCCategoryImplDecl>(this)) { 2147 if (ObjCCategoryDecl *CD = IFace->FindCategoryDeclaration(getIdentifier())) 2148 Ctx.setObjCImplementation(CD, ImplD); 2149 } 2150 2151 ClassInterface = IFace; 2152 } 2153 2154 /// FindPropertyImplIvarDecl - This method lookup the ivar in the list of 2155 /// properties implemented in this \@implementation block and returns 2156 /// the implemented property that uses it. 2157 ObjCPropertyImplDecl *ObjCImplDecl:: 2158 FindPropertyImplIvarDecl(IdentifierInfo *ivarId) const { 2159 for (auto *PID : property_impls()) 2160 if (PID->getPropertyIvarDecl() && 2161 PID->getPropertyIvarDecl()->getIdentifier() == ivarId) 2162 return PID; 2163 return nullptr; 2164 } 2165 2166 /// FindPropertyImplDecl - This method looks up a previous ObjCPropertyImplDecl 2167 /// added to the list of those properties \@synthesized/\@dynamic in this 2168 /// category \@implementation block. 2169 ObjCPropertyImplDecl *ObjCImplDecl:: 2170 FindPropertyImplDecl(IdentifierInfo *Id, 2171 ObjCPropertyQueryKind QueryKind) const { 2172 ObjCPropertyImplDecl *ClassPropImpl = nullptr; 2173 for (auto *PID : property_impls()) 2174 // If queryKind is unknown, we return the instance property if one 2175 // exists; otherwise we return the class property. 2176 if (PID->getPropertyDecl()->getIdentifier() == Id) { 2177 if ((QueryKind == ObjCPropertyQueryKind::OBJC_PR_query_unknown && 2178 !PID->getPropertyDecl()->isClassProperty()) || 2179 (QueryKind == ObjCPropertyQueryKind::OBJC_PR_query_class && 2180 PID->getPropertyDecl()->isClassProperty()) || 2181 (QueryKind == ObjCPropertyQueryKind::OBJC_PR_query_instance && 2182 !PID->getPropertyDecl()->isClassProperty())) 2183 return PID; 2184 2185 if (PID->getPropertyDecl()->isClassProperty()) 2186 ClassPropImpl = PID; 2187 } 2188 2189 if (QueryKind == ObjCPropertyQueryKind::OBJC_PR_query_unknown) 2190 // We can't find the instance property, return the class property. 2191 return ClassPropImpl; 2192 2193 return nullptr; 2194 } 2195 2196 raw_ostream &clang::operator<<(raw_ostream &OS, 2197 const ObjCCategoryImplDecl &CID) { 2198 OS << CID.getName(); 2199 return OS; 2200 } 2201 2202 //===----------------------------------------------------------------------===// 2203 // ObjCImplementationDecl 2204 //===----------------------------------------------------------------------===// 2205 2206 void ObjCImplementationDecl::anchor() {} 2207 2208 ObjCImplementationDecl * 2209 ObjCImplementationDecl::Create(ASTContext &C, DeclContext *DC, 2210 ObjCInterfaceDecl *ClassInterface, 2211 ObjCInterfaceDecl *SuperDecl, 2212 SourceLocation nameLoc, 2213 SourceLocation atStartLoc, 2214 SourceLocation superLoc, 2215 SourceLocation IvarLBraceLoc, 2216 SourceLocation IvarRBraceLoc) { 2217 if (ClassInterface && ClassInterface->hasDefinition()) 2218 ClassInterface = ClassInterface->getDefinition(); 2219 return new (C, DC) ObjCImplementationDecl(DC, ClassInterface, SuperDecl, 2220 nameLoc, atStartLoc, superLoc, 2221 IvarLBraceLoc, IvarRBraceLoc); 2222 } 2223 2224 ObjCImplementationDecl * 2225 ObjCImplementationDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 2226 return new (C, ID) ObjCImplementationDecl(nullptr, nullptr, nullptr, 2227 SourceLocation(), SourceLocation()); 2228 } 2229 2230 void ObjCImplementationDecl::setIvarInitializers(ASTContext &C, 2231 CXXCtorInitializer ** initializers, 2232 unsigned numInitializers) { 2233 if (numInitializers > 0) { 2234 NumIvarInitializers = numInitializers; 2235 auto **ivarInitializers = new (C) CXXCtorInitializer*[NumIvarInitializers]; 2236 memcpy(ivarInitializers, initializers, 2237 numInitializers * sizeof(CXXCtorInitializer*)); 2238 IvarInitializers = ivarInitializers; 2239 } 2240 } 2241 2242 ObjCImplementationDecl::init_const_iterator 2243 ObjCImplementationDecl::init_begin() const { 2244 return IvarInitializers.get(getASTContext().getExternalSource()); 2245 } 2246 2247 raw_ostream &clang::operator<<(raw_ostream &OS, 2248 const ObjCImplementationDecl &ID) { 2249 OS << ID.getName(); 2250 return OS; 2251 } 2252 2253 //===----------------------------------------------------------------------===// 2254 // ObjCCompatibleAliasDecl 2255 //===----------------------------------------------------------------------===// 2256 2257 void ObjCCompatibleAliasDecl::anchor() {} 2258 2259 ObjCCompatibleAliasDecl * 2260 ObjCCompatibleAliasDecl::Create(ASTContext &C, DeclContext *DC, 2261 SourceLocation L, 2262 IdentifierInfo *Id, 2263 ObjCInterfaceDecl* AliasedClass) { 2264 return new (C, DC) ObjCCompatibleAliasDecl(DC, L, Id, AliasedClass); 2265 } 2266 2267 ObjCCompatibleAliasDecl * 2268 ObjCCompatibleAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 2269 return new (C, ID) ObjCCompatibleAliasDecl(nullptr, SourceLocation(), 2270 nullptr, nullptr); 2271 } 2272 2273 //===----------------------------------------------------------------------===// 2274 // ObjCPropertyDecl 2275 //===----------------------------------------------------------------------===// 2276 2277 void ObjCPropertyDecl::anchor() {} 2278 2279 ObjCPropertyDecl *ObjCPropertyDecl::Create(ASTContext &C, DeclContext *DC, 2280 SourceLocation L, 2281 IdentifierInfo *Id, 2282 SourceLocation AtLoc, 2283 SourceLocation LParenLoc, 2284 QualType T, 2285 TypeSourceInfo *TSI, 2286 PropertyControl propControl) { 2287 return new (C, DC) ObjCPropertyDecl(DC, L, Id, AtLoc, LParenLoc, T, TSI, 2288 propControl); 2289 } 2290 2291 ObjCPropertyDecl *ObjCPropertyDecl::CreateDeserialized(ASTContext &C, 2292 unsigned ID) { 2293 return new (C, ID) ObjCPropertyDecl(nullptr, SourceLocation(), nullptr, 2294 SourceLocation(), SourceLocation(), 2295 QualType(), nullptr, None); 2296 } 2297 2298 QualType ObjCPropertyDecl::getUsageType(QualType objectType) const { 2299 return DeclType.substObjCMemberType(objectType, getDeclContext(), 2300 ObjCSubstitutionContext::Property); 2301 } 2302 2303 bool ObjCPropertyDecl::isDirectProperty() const { 2304 return (PropertyAttributes & ObjCPropertyAttribute::kind_direct) && 2305 !getASTContext().getLangOpts().ObjCDisableDirectMethodsForTesting; 2306 } 2307 2308 //===----------------------------------------------------------------------===// 2309 // ObjCPropertyImplDecl 2310 //===----------------------------------------------------------------------===// 2311 2312 ObjCPropertyImplDecl *ObjCPropertyImplDecl::Create(ASTContext &C, 2313 DeclContext *DC, 2314 SourceLocation atLoc, 2315 SourceLocation L, 2316 ObjCPropertyDecl *property, 2317 Kind PK, 2318 ObjCIvarDecl *ivar, 2319 SourceLocation ivarLoc) { 2320 return new (C, DC) ObjCPropertyImplDecl(DC, atLoc, L, property, PK, ivar, 2321 ivarLoc); 2322 } 2323 2324 ObjCPropertyImplDecl *ObjCPropertyImplDecl::CreateDeserialized(ASTContext &C, 2325 unsigned ID) { 2326 return new (C, ID) ObjCPropertyImplDecl(nullptr, SourceLocation(), 2327 SourceLocation(), nullptr, Dynamic, 2328 nullptr, SourceLocation()); 2329 } 2330 2331 SourceRange ObjCPropertyImplDecl::getSourceRange() const { 2332 SourceLocation EndLoc = getLocation(); 2333 if (IvarLoc.isValid()) 2334 EndLoc = IvarLoc; 2335 2336 return SourceRange(AtLoc, EndLoc); 2337 } 2338