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 // Make the type point at the definition, now that we have one. 608 if (TypeForDecl) 609 cast<ObjCInterfaceType>(TypeForDecl)->Decl = this; 610 } 611 612 void ObjCInterfaceDecl::startDefinition() { 613 allocateDefinitionData(); 614 615 // Update all of the declarations with a pointer to the definition. 616 for (auto *RD : redecls()) { 617 if (RD != this) 618 RD->Data = Data; 619 } 620 } 621 622 ObjCIvarDecl *ObjCInterfaceDecl::lookupInstanceVariable(IdentifierInfo *ID, 623 ObjCInterfaceDecl *&clsDeclared) { 624 // FIXME: Should make sure no callers ever do this. 625 if (!hasDefinition()) 626 return nullptr; 627 628 if (data().ExternallyCompleted) 629 LoadExternalDefinition(); 630 631 ObjCInterfaceDecl* ClassDecl = this; 632 while (ClassDecl != nullptr) { 633 if (ObjCIvarDecl *I = ClassDecl->getIvarDecl(ID)) { 634 clsDeclared = ClassDecl; 635 return I; 636 } 637 638 for (const auto *Ext : ClassDecl->visible_extensions()) { 639 if (ObjCIvarDecl *I = Ext->getIvarDecl(ID)) { 640 clsDeclared = ClassDecl; 641 return I; 642 } 643 } 644 645 ClassDecl = ClassDecl->getSuperClass(); 646 } 647 return nullptr; 648 } 649 650 /// lookupInheritedClass - This method returns ObjCInterfaceDecl * of the super 651 /// class whose name is passed as argument. If it is not one of the super classes 652 /// the it returns NULL. 653 ObjCInterfaceDecl *ObjCInterfaceDecl::lookupInheritedClass( 654 const IdentifierInfo*ICName) { 655 // FIXME: Should make sure no callers ever do this. 656 if (!hasDefinition()) 657 return nullptr; 658 659 if (data().ExternallyCompleted) 660 LoadExternalDefinition(); 661 662 ObjCInterfaceDecl* ClassDecl = this; 663 while (ClassDecl != nullptr) { 664 if (ClassDecl->getIdentifier() == ICName) 665 return ClassDecl; 666 ClassDecl = ClassDecl->getSuperClass(); 667 } 668 return nullptr; 669 } 670 671 ObjCProtocolDecl * 672 ObjCInterfaceDecl::lookupNestedProtocol(IdentifierInfo *Name) { 673 for (auto *P : all_referenced_protocols()) 674 if (P->lookupProtocolNamed(Name)) 675 return P; 676 ObjCInterfaceDecl *SuperClass = getSuperClass(); 677 return SuperClass ? SuperClass->lookupNestedProtocol(Name) : nullptr; 678 } 679 680 /// lookupMethod - This method returns an instance/class method by looking in 681 /// the class, its categories, and its super classes (using a linear search). 682 /// When argument category "C" is specified, any implicit method found 683 /// in this category is ignored. 684 ObjCMethodDecl *ObjCInterfaceDecl::lookupMethod(Selector Sel, 685 bool isInstance, 686 bool shallowCategoryLookup, 687 bool followSuper, 688 const ObjCCategoryDecl *C) const 689 { 690 // FIXME: Should make sure no callers ever do this. 691 if (!hasDefinition()) 692 return nullptr; 693 694 const ObjCInterfaceDecl* ClassDecl = this; 695 ObjCMethodDecl *MethodDecl = nullptr; 696 697 if (data().ExternallyCompleted) 698 LoadExternalDefinition(); 699 700 while (ClassDecl) { 701 // 1. Look through primary class. 702 if ((MethodDecl = ClassDecl->getMethod(Sel, isInstance))) 703 return MethodDecl; 704 705 // 2. Didn't find one yet - now look through categories. 706 for (const auto *Cat : ClassDecl->visible_categories()) 707 if ((MethodDecl = Cat->getMethod(Sel, isInstance))) 708 if (C != Cat || !MethodDecl->isImplicit()) 709 return MethodDecl; 710 711 // 3. Didn't find one yet - look through primary class's protocols. 712 for (const auto *I : ClassDecl->protocols()) 713 if ((MethodDecl = I->lookupMethod(Sel, isInstance))) 714 return MethodDecl; 715 716 // 4. Didn't find one yet - now look through categories' protocols 717 if (!shallowCategoryLookup) 718 for (const auto *Cat : ClassDecl->visible_categories()) { 719 // Didn't find one yet - look through protocols. 720 const ObjCList<ObjCProtocolDecl> &Protocols = 721 Cat->getReferencedProtocols(); 722 for (auto *Protocol : Protocols) 723 if ((MethodDecl = Protocol->lookupMethod(Sel, isInstance))) 724 if (C != Cat || !MethodDecl->isImplicit()) 725 return MethodDecl; 726 } 727 728 729 if (!followSuper) 730 return nullptr; 731 732 // 5. Get to the super class (if any). 733 ClassDecl = ClassDecl->getSuperClass(); 734 } 735 return nullptr; 736 } 737 738 // Will search "local" class/category implementations for a method decl. 739 // If failed, then we search in class's root for an instance method. 740 // Returns 0 if no method is found. 741 ObjCMethodDecl *ObjCInterfaceDecl::lookupPrivateMethod( 742 const Selector &Sel, 743 bool Instance) const { 744 // FIXME: Should make sure no callers ever do this. 745 if (!hasDefinition()) 746 return nullptr; 747 748 if (data().ExternallyCompleted) 749 LoadExternalDefinition(); 750 751 ObjCMethodDecl *Method = nullptr; 752 if (ObjCImplementationDecl *ImpDecl = getImplementation()) 753 Method = Instance ? ImpDecl->getInstanceMethod(Sel) 754 : ImpDecl->getClassMethod(Sel); 755 756 // Look through local category implementations associated with the class. 757 if (!Method) 758 Method = getCategoryMethod(Sel, Instance); 759 760 // Before we give up, check if the selector is an instance method. 761 // But only in the root. This matches gcc's behavior and what the 762 // runtime expects. 763 if (!Instance && !Method && !getSuperClass()) { 764 Method = lookupInstanceMethod(Sel); 765 // Look through local category implementations associated 766 // with the root class. 767 if (!Method) 768 Method = lookupPrivateMethod(Sel, true); 769 } 770 771 if (!Method && getSuperClass()) 772 return getSuperClass()->lookupPrivateMethod(Sel, Instance); 773 return Method; 774 } 775 776 //===----------------------------------------------------------------------===// 777 // ObjCMethodDecl 778 //===----------------------------------------------------------------------===// 779 780 ObjCMethodDecl::ObjCMethodDecl( 781 SourceLocation beginLoc, SourceLocation endLoc, Selector SelInfo, 782 QualType T, TypeSourceInfo *ReturnTInfo, DeclContext *contextDecl, 783 bool isInstance, bool isVariadic, bool isPropertyAccessor, 784 bool isSynthesizedAccessorStub, bool isImplicitlyDeclared, bool isDefined, 785 ImplementationControl impControl, bool HasRelatedResultType) 786 : NamedDecl(ObjCMethod, contextDecl, beginLoc, SelInfo), 787 DeclContext(ObjCMethod), MethodDeclType(T), ReturnTInfo(ReturnTInfo), 788 DeclEndLoc(endLoc) { 789 790 // Initialized the bits stored in DeclContext. 791 ObjCMethodDeclBits.Family = 792 static_cast<ObjCMethodFamily>(InvalidObjCMethodFamily); 793 setInstanceMethod(isInstance); 794 setVariadic(isVariadic); 795 setPropertyAccessor(isPropertyAccessor); 796 setSynthesizedAccessorStub(isSynthesizedAccessorStub); 797 setDefined(isDefined); 798 setIsRedeclaration(false); 799 setHasRedeclaration(false); 800 setDeclImplementation(impControl); 801 setObjCDeclQualifier(OBJC_TQ_None); 802 setRelatedResultType(HasRelatedResultType); 803 setSelLocsKind(SelLoc_StandardNoSpace); 804 setOverriding(false); 805 setHasSkippedBody(false); 806 807 setImplicit(isImplicitlyDeclared); 808 } 809 810 ObjCMethodDecl *ObjCMethodDecl::Create( 811 ASTContext &C, SourceLocation beginLoc, SourceLocation endLoc, 812 Selector SelInfo, QualType T, TypeSourceInfo *ReturnTInfo, 813 DeclContext *contextDecl, bool isInstance, bool isVariadic, 814 bool isPropertyAccessor, bool isSynthesizedAccessorStub, 815 bool isImplicitlyDeclared, bool isDefined, ImplementationControl impControl, 816 bool HasRelatedResultType) { 817 return new (C, contextDecl) ObjCMethodDecl( 818 beginLoc, endLoc, SelInfo, T, ReturnTInfo, contextDecl, isInstance, 819 isVariadic, isPropertyAccessor, isSynthesizedAccessorStub, 820 isImplicitlyDeclared, isDefined, impControl, HasRelatedResultType); 821 } 822 823 ObjCMethodDecl *ObjCMethodDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 824 return new (C, ID) ObjCMethodDecl(SourceLocation(), SourceLocation(), 825 Selector(), QualType(), nullptr, nullptr); 826 } 827 828 bool ObjCMethodDecl::isDirectMethod() const { 829 return hasAttr<ObjCDirectAttr>(); 830 } 831 832 bool ObjCMethodDecl::isThisDeclarationADesignatedInitializer() const { 833 return getMethodFamily() == OMF_init && 834 hasAttr<ObjCDesignatedInitializerAttr>(); 835 } 836 837 bool ObjCMethodDecl::definedInNSObject(const ASTContext &Ctx) const { 838 if (const auto *PD = dyn_cast<const ObjCProtocolDecl>(getDeclContext())) 839 return PD->getIdentifier() == Ctx.getNSObjectName(); 840 if (const auto *ID = dyn_cast<const ObjCInterfaceDecl>(getDeclContext())) 841 return ID->getIdentifier() == Ctx.getNSObjectName(); 842 return false; 843 } 844 845 bool ObjCMethodDecl::isDesignatedInitializerForTheInterface( 846 const ObjCMethodDecl **InitMethod) const { 847 if (getMethodFamily() != OMF_init) 848 return false; 849 const DeclContext *DC = getDeclContext(); 850 if (isa<ObjCProtocolDecl>(DC)) 851 return false; 852 if (const ObjCInterfaceDecl *ID = getClassInterface()) 853 return ID->isDesignatedInitializer(getSelector(), InitMethod); 854 return false; 855 } 856 857 Stmt *ObjCMethodDecl::getBody() const { 858 return Body.get(getASTContext().getExternalSource()); 859 } 860 861 void ObjCMethodDecl::setAsRedeclaration(const ObjCMethodDecl *PrevMethod) { 862 assert(PrevMethod); 863 getASTContext().setObjCMethodRedeclaration(PrevMethod, this); 864 setIsRedeclaration(true); 865 PrevMethod->setHasRedeclaration(true); 866 } 867 868 void ObjCMethodDecl::setParamsAndSelLocs(ASTContext &C, 869 ArrayRef<ParmVarDecl*> Params, 870 ArrayRef<SourceLocation> SelLocs) { 871 ParamsAndSelLocs = nullptr; 872 NumParams = Params.size(); 873 if (Params.empty() && SelLocs.empty()) 874 return; 875 876 static_assert(alignof(ParmVarDecl *) >= alignof(SourceLocation), 877 "Alignment not sufficient for SourceLocation"); 878 879 unsigned Size = sizeof(ParmVarDecl *) * NumParams + 880 sizeof(SourceLocation) * SelLocs.size(); 881 ParamsAndSelLocs = C.Allocate(Size); 882 std::copy(Params.begin(), Params.end(), getParams()); 883 std::copy(SelLocs.begin(), SelLocs.end(), getStoredSelLocs()); 884 } 885 886 void ObjCMethodDecl::getSelectorLocs( 887 SmallVectorImpl<SourceLocation> &SelLocs) const { 888 for (unsigned i = 0, e = getNumSelectorLocs(); i != e; ++i) 889 SelLocs.push_back(getSelectorLoc(i)); 890 } 891 892 void ObjCMethodDecl::setMethodParams(ASTContext &C, 893 ArrayRef<ParmVarDecl*> Params, 894 ArrayRef<SourceLocation> SelLocs) { 895 assert((!SelLocs.empty() || isImplicit()) && 896 "No selector locs for non-implicit method"); 897 if (isImplicit()) 898 return setParamsAndSelLocs(C, Params, llvm::None); 899 900 setSelLocsKind(hasStandardSelectorLocs(getSelector(), SelLocs, Params, 901 DeclEndLoc)); 902 if (getSelLocsKind() != SelLoc_NonStandard) 903 return setParamsAndSelLocs(C, Params, llvm::None); 904 905 setParamsAndSelLocs(C, Params, SelLocs); 906 } 907 908 /// A definition will return its interface declaration. 909 /// An interface declaration will return its definition. 910 /// Otherwise it will return itself. 911 ObjCMethodDecl *ObjCMethodDecl::getNextRedeclarationImpl() { 912 ASTContext &Ctx = getASTContext(); 913 ObjCMethodDecl *Redecl = nullptr; 914 if (hasRedeclaration()) 915 Redecl = const_cast<ObjCMethodDecl*>(Ctx.getObjCMethodRedeclaration(this)); 916 if (Redecl) 917 return Redecl; 918 919 auto *CtxD = cast<Decl>(getDeclContext()); 920 921 if (!CtxD->isInvalidDecl()) { 922 if (auto *IFD = dyn_cast<ObjCInterfaceDecl>(CtxD)) { 923 if (ObjCImplementationDecl *ImplD = Ctx.getObjCImplementation(IFD)) 924 if (!ImplD->isInvalidDecl()) 925 Redecl = ImplD->getMethod(getSelector(), isInstanceMethod()); 926 927 } else if (auto *CD = dyn_cast<ObjCCategoryDecl>(CtxD)) { 928 if (ObjCCategoryImplDecl *ImplD = Ctx.getObjCImplementation(CD)) 929 if (!ImplD->isInvalidDecl()) 930 Redecl = ImplD->getMethod(getSelector(), isInstanceMethod()); 931 932 } else if (auto *ImplD = dyn_cast<ObjCImplementationDecl>(CtxD)) { 933 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface()) 934 if (!IFD->isInvalidDecl()) 935 Redecl = IFD->getMethod(getSelector(), isInstanceMethod()); 936 937 } else if (auto *CImplD = dyn_cast<ObjCCategoryImplDecl>(CtxD)) { 938 if (ObjCCategoryDecl *CatD = CImplD->getCategoryDecl()) 939 if (!CatD->isInvalidDecl()) 940 Redecl = CatD->getMethod(getSelector(), isInstanceMethod()); 941 } 942 } 943 944 // Ensure that the discovered method redeclaration has a valid declaration 945 // context. Used to prevent infinite loops when iterating redeclarations in 946 // a partially invalid AST. 947 if (Redecl && cast<Decl>(Redecl->getDeclContext())->isInvalidDecl()) 948 Redecl = nullptr; 949 950 if (!Redecl && isRedeclaration()) { 951 // This is the last redeclaration, go back to the first method. 952 return cast<ObjCContainerDecl>(CtxD)->getMethod(getSelector(), 953 isInstanceMethod()); 954 } 955 956 return Redecl ? Redecl : this; 957 } 958 959 ObjCMethodDecl *ObjCMethodDecl::getCanonicalDecl() { 960 auto *CtxD = cast<Decl>(getDeclContext()); 961 const auto &Sel = getSelector(); 962 963 if (auto *ImplD = dyn_cast<ObjCImplementationDecl>(CtxD)) { 964 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface()) { 965 // When the container is the ObjCImplementationDecl (the primary 966 // @implementation), then the canonical Decl is either in 967 // the class Interface, or in any of its extension. 968 // 969 // So when we don't find it in the ObjCInterfaceDecl, 970 // sift through extensions too. 971 if (ObjCMethodDecl *MD = IFD->getMethod(Sel, isInstanceMethod())) 972 return MD; 973 for (auto *Ext : IFD->known_extensions()) 974 if (ObjCMethodDecl *MD = Ext->getMethod(Sel, isInstanceMethod())) 975 return MD; 976 } 977 } else if (auto *CImplD = dyn_cast<ObjCCategoryImplDecl>(CtxD)) { 978 if (ObjCCategoryDecl *CatD = CImplD->getCategoryDecl()) 979 if (ObjCMethodDecl *MD = CatD->getMethod(Sel, isInstanceMethod())) 980 return MD; 981 } 982 983 if (isRedeclaration()) { 984 // It is possible that we have not done deserializing the ObjCMethod yet. 985 ObjCMethodDecl *MD = 986 cast<ObjCContainerDecl>(CtxD)->getMethod(Sel, isInstanceMethod()); 987 return MD ? MD : this; 988 } 989 990 return this; 991 } 992 993 SourceLocation ObjCMethodDecl::getEndLoc() const { 994 if (Stmt *Body = getBody()) 995 return Body->getEndLoc(); 996 return DeclEndLoc; 997 } 998 999 ObjCMethodFamily ObjCMethodDecl::getMethodFamily() const { 1000 auto family = static_cast<ObjCMethodFamily>(ObjCMethodDeclBits.Family); 1001 if (family != static_cast<unsigned>(InvalidObjCMethodFamily)) 1002 return family; 1003 1004 // Check for an explicit attribute. 1005 if (const ObjCMethodFamilyAttr *attr = getAttr<ObjCMethodFamilyAttr>()) { 1006 // The unfortunate necessity of mapping between enums here is due 1007 // to the attributes framework. 1008 switch (attr->getFamily()) { 1009 case ObjCMethodFamilyAttr::OMF_None: family = OMF_None; break; 1010 case ObjCMethodFamilyAttr::OMF_alloc: family = OMF_alloc; break; 1011 case ObjCMethodFamilyAttr::OMF_copy: family = OMF_copy; break; 1012 case ObjCMethodFamilyAttr::OMF_init: family = OMF_init; break; 1013 case ObjCMethodFamilyAttr::OMF_mutableCopy: family = OMF_mutableCopy; break; 1014 case ObjCMethodFamilyAttr::OMF_new: family = OMF_new; break; 1015 } 1016 ObjCMethodDeclBits.Family = family; 1017 return family; 1018 } 1019 1020 family = getSelector().getMethodFamily(); 1021 switch (family) { 1022 case OMF_None: break; 1023 1024 // init only has a conventional meaning for an instance method, and 1025 // it has to return an object. 1026 case OMF_init: 1027 if (!isInstanceMethod() || !getReturnType()->isObjCObjectPointerType()) 1028 family = OMF_None; 1029 break; 1030 1031 // alloc/copy/new have a conventional meaning for both class and 1032 // instance methods, but they require an object return. 1033 case OMF_alloc: 1034 case OMF_copy: 1035 case OMF_mutableCopy: 1036 case OMF_new: 1037 if (!getReturnType()->isObjCObjectPointerType()) 1038 family = OMF_None; 1039 break; 1040 1041 // These selectors have a conventional meaning only for instance methods. 1042 case OMF_dealloc: 1043 case OMF_finalize: 1044 case OMF_retain: 1045 case OMF_release: 1046 case OMF_autorelease: 1047 case OMF_retainCount: 1048 case OMF_self: 1049 if (!isInstanceMethod()) 1050 family = OMF_None; 1051 break; 1052 1053 case OMF_initialize: 1054 if (isInstanceMethod() || !getReturnType()->isVoidType()) 1055 family = OMF_None; 1056 break; 1057 1058 case OMF_performSelector: 1059 if (!isInstanceMethod() || !getReturnType()->isObjCIdType()) 1060 family = OMF_None; 1061 else { 1062 unsigned noParams = param_size(); 1063 if (noParams < 1 || noParams > 3) 1064 family = OMF_None; 1065 else { 1066 ObjCMethodDecl::param_type_iterator it = param_type_begin(); 1067 QualType ArgT = (*it); 1068 if (!ArgT->isObjCSelType()) { 1069 family = OMF_None; 1070 break; 1071 } 1072 while (--noParams) { 1073 it++; 1074 ArgT = (*it); 1075 if (!ArgT->isObjCIdType()) { 1076 family = OMF_None; 1077 break; 1078 } 1079 } 1080 } 1081 } 1082 break; 1083 1084 } 1085 1086 // Cache the result. 1087 ObjCMethodDeclBits.Family = family; 1088 return family; 1089 } 1090 1091 QualType ObjCMethodDecl::getSelfType(ASTContext &Context, 1092 const ObjCInterfaceDecl *OID, 1093 bool &selfIsPseudoStrong, 1094 bool &selfIsConsumed) const { 1095 QualType selfTy; 1096 selfIsPseudoStrong = false; 1097 selfIsConsumed = false; 1098 if (isInstanceMethod()) { 1099 // There may be no interface context due to error in declaration 1100 // of the interface (which has been reported). Recover gracefully. 1101 if (OID) { 1102 selfTy = Context.getObjCInterfaceType(OID); 1103 selfTy = Context.getObjCObjectPointerType(selfTy); 1104 } else { 1105 selfTy = Context.getObjCIdType(); 1106 } 1107 } else // we have a factory method. 1108 selfTy = Context.getObjCClassType(); 1109 1110 if (Context.getLangOpts().ObjCAutoRefCount) { 1111 if (isInstanceMethod()) { 1112 selfIsConsumed = hasAttr<NSConsumesSelfAttr>(); 1113 1114 // 'self' is always __strong. It's actually pseudo-strong except 1115 // in init methods (or methods labeled ns_consumes_self), though. 1116 Qualifiers qs; 1117 qs.setObjCLifetime(Qualifiers::OCL_Strong); 1118 selfTy = Context.getQualifiedType(selfTy, qs); 1119 1120 // In addition, 'self' is const unless this is an init method. 1121 if (getMethodFamily() != OMF_init && !selfIsConsumed) { 1122 selfTy = selfTy.withConst(); 1123 selfIsPseudoStrong = true; 1124 } 1125 } 1126 else { 1127 assert(isClassMethod()); 1128 // 'self' is always const in class methods. 1129 selfTy = selfTy.withConst(); 1130 selfIsPseudoStrong = true; 1131 } 1132 } 1133 return selfTy; 1134 } 1135 1136 void ObjCMethodDecl::createImplicitParams(ASTContext &Context, 1137 const ObjCInterfaceDecl *OID) { 1138 bool selfIsPseudoStrong, selfIsConsumed; 1139 QualType selfTy = 1140 getSelfType(Context, OID, selfIsPseudoStrong, selfIsConsumed); 1141 auto *Self = ImplicitParamDecl::Create(Context, this, SourceLocation(), 1142 &Context.Idents.get("self"), selfTy, 1143 ImplicitParamDecl::ObjCSelf); 1144 setSelfDecl(Self); 1145 1146 if (selfIsConsumed) 1147 Self->addAttr(NSConsumedAttr::CreateImplicit(Context)); 1148 1149 if (selfIsPseudoStrong) 1150 Self->setARCPseudoStrong(true); 1151 1152 setCmdDecl(ImplicitParamDecl::Create( 1153 Context, this, SourceLocation(), &Context.Idents.get("_cmd"), 1154 Context.getObjCSelType(), ImplicitParamDecl::ObjCCmd)); 1155 } 1156 1157 ObjCInterfaceDecl *ObjCMethodDecl::getClassInterface() { 1158 if (auto *ID = dyn_cast<ObjCInterfaceDecl>(getDeclContext())) 1159 return ID; 1160 if (auto *CD = dyn_cast<ObjCCategoryDecl>(getDeclContext())) 1161 return CD->getClassInterface(); 1162 if (auto *IMD = dyn_cast<ObjCImplDecl>(getDeclContext())) 1163 return IMD->getClassInterface(); 1164 if (isa<ObjCProtocolDecl>(getDeclContext())) 1165 return nullptr; 1166 llvm_unreachable("unknown method context"); 1167 } 1168 1169 ObjCCategoryDecl *ObjCMethodDecl::getCategory() { 1170 if (auto *CD = dyn_cast<ObjCCategoryDecl>(getDeclContext())) 1171 return CD; 1172 if (auto *IMD = dyn_cast<ObjCCategoryImplDecl>(getDeclContext())) 1173 return IMD->getCategoryDecl(); 1174 return nullptr; 1175 } 1176 1177 SourceRange ObjCMethodDecl::getReturnTypeSourceRange() const { 1178 const auto *TSI = getReturnTypeSourceInfo(); 1179 if (TSI) 1180 return TSI->getTypeLoc().getSourceRange(); 1181 return SourceRange(); 1182 } 1183 1184 QualType ObjCMethodDecl::getSendResultType() const { 1185 ASTContext &Ctx = getASTContext(); 1186 return getReturnType().getNonLValueExprType(Ctx) 1187 .substObjCTypeArgs(Ctx, {}, ObjCSubstitutionContext::Result); 1188 } 1189 1190 QualType ObjCMethodDecl::getSendResultType(QualType receiverType) const { 1191 // FIXME: Handle related result types here. 1192 1193 return getReturnType().getNonLValueExprType(getASTContext()) 1194 .substObjCMemberType(receiverType, getDeclContext(), 1195 ObjCSubstitutionContext::Result); 1196 } 1197 1198 static void CollectOverriddenMethodsRecurse(const ObjCContainerDecl *Container, 1199 const ObjCMethodDecl *Method, 1200 SmallVectorImpl<const ObjCMethodDecl *> &Methods, 1201 bool MovedToSuper) { 1202 if (!Container) 1203 return; 1204 1205 // In categories look for overridden methods from protocols. A method from 1206 // category is not "overridden" since it is considered as the "same" method 1207 // (same USR) as the one from the interface. 1208 if (const auto *Category = dyn_cast<ObjCCategoryDecl>(Container)) { 1209 // Check whether we have a matching method at this category but only if we 1210 // are at the super class level. 1211 if (MovedToSuper) 1212 if (ObjCMethodDecl * 1213 Overridden = Container->getMethod(Method->getSelector(), 1214 Method->isInstanceMethod(), 1215 /*AllowHidden=*/true)) 1216 if (Method != Overridden) { 1217 // We found an override at this category; there is no need to look 1218 // into its protocols. 1219 Methods.push_back(Overridden); 1220 return; 1221 } 1222 1223 for (const auto *P : Category->protocols()) 1224 CollectOverriddenMethodsRecurse(P, Method, Methods, MovedToSuper); 1225 return; 1226 } 1227 1228 // Check whether we have a matching method at this level. 1229 if (const ObjCMethodDecl * 1230 Overridden = Container->getMethod(Method->getSelector(), 1231 Method->isInstanceMethod(), 1232 /*AllowHidden=*/true)) 1233 if (Method != Overridden) { 1234 // We found an override at this level; there is no need to look 1235 // into other protocols or categories. 1236 Methods.push_back(Overridden); 1237 return; 1238 } 1239 1240 if (const auto *Protocol = dyn_cast<ObjCProtocolDecl>(Container)){ 1241 for (const auto *P : Protocol->protocols()) 1242 CollectOverriddenMethodsRecurse(P, Method, Methods, MovedToSuper); 1243 } 1244 1245 if (const auto *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) { 1246 for (const auto *P : Interface->protocols()) 1247 CollectOverriddenMethodsRecurse(P, Method, Methods, MovedToSuper); 1248 1249 for (const auto *Cat : Interface->known_categories()) 1250 CollectOverriddenMethodsRecurse(Cat, Method, Methods, MovedToSuper); 1251 1252 if (const ObjCInterfaceDecl *Super = Interface->getSuperClass()) 1253 return CollectOverriddenMethodsRecurse(Super, Method, Methods, 1254 /*MovedToSuper=*/true); 1255 } 1256 } 1257 1258 static inline void CollectOverriddenMethods(const ObjCContainerDecl *Container, 1259 const ObjCMethodDecl *Method, 1260 SmallVectorImpl<const ObjCMethodDecl *> &Methods) { 1261 CollectOverriddenMethodsRecurse(Container, Method, Methods, 1262 /*MovedToSuper=*/false); 1263 } 1264 1265 static void collectOverriddenMethodsSlow(const ObjCMethodDecl *Method, 1266 SmallVectorImpl<const ObjCMethodDecl *> &overridden) { 1267 assert(Method->isOverriding()); 1268 1269 if (const auto *ProtD = 1270 dyn_cast<ObjCProtocolDecl>(Method->getDeclContext())) { 1271 CollectOverriddenMethods(ProtD, Method, overridden); 1272 1273 } else if (const auto *IMD = 1274 dyn_cast<ObjCImplDecl>(Method->getDeclContext())) { 1275 const ObjCInterfaceDecl *ID = IMD->getClassInterface(); 1276 if (!ID) 1277 return; 1278 // Start searching for overridden methods using the method from the 1279 // interface as starting point. 1280 if (const ObjCMethodDecl *IFaceMeth = ID->getMethod(Method->getSelector(), 1281 Method->isInstanceMethod(), 1282 /*AllowHidden=*/true)) 1283 Method = IFaceMeth; 1284 CollectOverriddenMethods(ID, Method, overridden); 1285 1286 } else if (const auto *CatD = 1287 dyn_cast<ObjCCategoryDecl>(Method->getDeclContext())) { 1288 const ObjCInterfaceDecl *ID = CatD->getClassInterface(); 1289 if (!ID) 1290 return; 1291 // Start searching for overridden methods using the method from the 1292 // interface as starting point. 1293 if (const ObjCMethodDecl *IFaceMeth = ID->getMethod(Method->getSelector(), 1294 Method->isInstanceMethod(), 1295 /*AllowHidden=*/true)) 1296 Method = IFaceMeth; 1297 CollectOverriddenMethods(ID, Method, overridden); 1298 1299 } else { 1300 CollectOverriddenMethods( 1301 dyn_cast_or_null<ObjCContainerDecl>(Method->getDeclContext()), 1302 Method, overridden); 1303 } 1304 } 1305 1306 void ObjCMethodDecl::getOverriddenMethods( 1307 SmallVectorImpl<const ObjCMethodDecl *> &Overridden) const { 1308 const ObjCMethodDecl *Method = this; 1309 1310 if (Method->isRedeclaration()) { 1311 Method = cast<ObjCContainerDecl>(Method->getDeclContext())-> 1312 getMethod(Method->getSelector(), Method->isInstanceMethod()); 1313 } 1314 1315 if (Method->isOverriding()) { 1316 collectOverriddenMethodsSlow(Method, Overridden); 1317 assert(!Overridden.empty() && 1318 "ObjCMethodDecl's overriding bit is not as expected"); 1319 } 1320 } 1321 1322 const ObjCPropertyDecl * 1323 ObjCMethodDecl::findPropertyDecl(bool CheckOverrides) const { 1324 Selector Sel = getSelector(); 1325 unsigned NumArgs = Sel.getNumArgs(); 1326 if (NumArgs > 1) 1327 return nullptr; 1328 1329 if (isPropertyAccessor()) { 1330 const auto *Container = cast<ObjCContainerDecl>(getParent()); 1331 // For accessor stubs, go back to the interface. 1332 if (auto *ImplDecl = dyn_cast<ObjCImplDecl>(Container)) 1333 if (isSynthesizedAccessorStub()) 1334 Container = ImplDecl->getClassInterface(); 1335 1336 bool IsGetter = (NumArgs == 0); 1337 bool IsInstance = isInstanceMethod(); 1338 1339 /// Local function that attempts to find a matching property within the 1340 /// given Objective-C container. 1341 auto findMatchingProperty = 1342 [&](const ObjCContainerDecl *Container) -> const ObjCPropertyDecl * { 1343 if (IsInstance) { 1344 for (const auto *I : Container->instance_properties()) { 1345 Selector NextSel = IsGetter ? I->getGetterName() 1346 : I->getSetterName(); 1347 if (NextSel == Sel) 1348 return I; 1349 } 1350 } else { 1351 for (const auto *I : Container->class_properties()) { 1352 Selector NextSel = IsGetter ? I->getGetterName() 1353 : I->getSetterName(); 1354 if (NextSel == Sel) 1355 return I; 1356 } 1357 } 1358 1359 return nullptr; 1360 }; 1361 1362 // Look in the container we were given. 1363 if (const auto *Found = findMatchingProperty(Container)) 1364 return Found; 1365 1366 // If we're in a category or extension, look in the main class. 1367 const ObjCInterfaceDecl *ClassDecl = nullptr; 1368 if (const auto *Category = dyn_cast<ObjCCategoryDecl>(Container)) { 1369 ClassDecl = Category->getClassInterface(); 1370 if (const auto *Found = findMatchingProperty(ClassDecl)) 1371 return Found; 1372 } else { 1373 // Determine whether the container is a class. 1374 ClassDecl = cast<ObjCInterfaceDecl>(Container); 1375 } 1376 assert(ClassDecl && "Failed to find main class"); 1377 1378 // If we have a class, check its visible extensions. 1379 for (const auto *Ext : ClassDecl->visible_extensions()) { 1380 if (Ext == Container) 1381 continue; 1382 if (const auto *Found = findMatchingProperty(Ext)) 1383 return Found; 1384 } 1385 1386 assert(isSynthesizedAccessorStub() && "expected an accessor stub"); 1387 1388 for (const auto *Cat : ClassDecl->known_categories()) { 1389 if (Cat == Container) 1390 continue; 1391 if (const auto *Found = findMatchingProperty(Cat)) 1392 return Found; 1393 } 1394 1395 llvm_unreachable("Marked as a property accessor but no property found!"); 1396 } 1397 1398 if (!CheckOverrides) 1399 return nullptr; 1400 1401 using OverridesTy = SmallVector<const ObjCMethodDecl *, 8>; 1402 1403 OverridesTy Overrides; 1404 getOverriddenMethods(Overrides); 1405 for (const auto *Override : Overrides) 1406 if (const ObjCPropertyDecl *Prop = Override->findPropertyDecl(false)) 1407 return Prop; 1408 1409 return nullptr; 1410 } 1411 1412 //===----------------------------------------------------------------------===// 1413 // ObjCTypeParamDecl 1414 //===----------------------------------------------------------------------===// 1415 1416 void ObjCTypeParamDecl::anchor() {} 1417 1418 ObjCTypeParamDecl *ObjCTypeParamDecl::Create(ASTContext &ctx, DeclContext *dc, 1419 ObjCTypeParamVariance variance, 1420 SourceLocation varianceLoc, 1421 unsigned index, 1422 SourceLocation nameLoc, 1423 IdentifierInfo *name, 1424 SourceLocation colonLoc, 1425 TypeSourceInfo *boundInfo) { 1426 auto *TPDecl = 1427 new (ctx, dc) ObjCTypeParamDecl(ctx, dc, variance, varianceLoc, index, 1428 nameLoc, name, colonLoc, boundInfo); 1429 QualType TPType = ctx.getObjCTypeParamType(TPDecl, {}); 1430 TPDecl->setTypeForDecl(TPType.getTypePtr()); 1431 return TPDecl; 1432 } 1433 1434 ObjCTypeParamDecl *ObjCTypeParamDecl::CreateDeserialized(ASTContext &ctx, 1435 unsigned ID) { 1436 return new (ctx, ID) ObjCTypeParamDecl(ctx, nullptr, 1437 ObjCTypeParamVariance::Invariant, 1438 SourceLocation(), 0, SourceLocation(), 1439 nullptr, SourceLocation(), nullptr); 1440 } 1441 1442 SourceRange ObjCTypeParamDecl::getSourceRange() const { 1443 SourceLocation startLoc = VarianceLoc; 1444 if (startLoc.isInvalid()) 1445 startLoc = getLocation(); 1446 1447 if (hasExplicitBound()) { 1448 return SourceRange(startLoc, 1449 getTypeSourceInfo()->getTypeLoc().getEndLoc()); 1450 } 1451 1452 return SourceRange(startLoc); 1453 } 1454 1455 //===----------------------------------------------------------------------===// 1456 // ObjCTypeParamList 1457 //===----------------------------------------------------------------------===// 1458 ObjCTypeParamList::ObjCTypeParamList(SourceLocation lAngleLoc, 1459 ArrayRef<ObjCTypeParamDecl *> typeParams, 1460 SourceLocation rAngleLoc) 1461 : NumParams(typeParams.size()) { 1462 Brackets.Begin = lAngleLoc.getRawEncoding(); 1463 Brackets.End = rAngleLoc.getRawEncoding(); 1464 std::copy(typeParams.begin(), typeParams.end(), begin()); 1465 } 1466 1467 ObjCTypeParamList *ObjCTypeParamList::create( 1468 ASTContext &ctx, 1469 SourceLocation lAngleLoc, 1470 ArrayRef<ObjCTypeParamDecl *> typeParams, 1471 SourceLocation rAngleLoc) { 1472 void *mem = 1473 ctx.Allocate(totalSizeToAlloc<ObjCTypeParamDecl *>(typeParams.size()), 1474 alignof(ObjCTypeParamList)); 1475 return new (mem) ObjCTypeParamList(lAngleLoc, typeParams, rAngleLoc); 1476 } 1477 1478 void ObjCTypeParamList::gatherDefaultTypeArgs( 1479 SmallVectorImpl<QualType> &typeArgs) const { 1480 typeArgs.reserve(size()); 1481 for (auto typeParam : *this) 1482 typeArgs.push_back(typeParam->getUnderlyingType()); 1483 } 1484 1485 //===----------------------------------------------------------------------===// 1486 // ObjCInterfaceDecl 1487 //===----------------------------------------------------------------------===// 1488 1489 ObjCInterfaceDecl *ObjCInterfaceDecl::Create(const ASTContext &C, 1490 DeclContext *DC, 1491 SourceLocation atLoc, 1492 IdentifierInfo *Id, 1493 ObjCTypeParamList *typeParamList, 1494 ObjCInterfaceDecl *PrevDecl, 1495 SourceLocation ClassLoc, 1496 bool isInternal){ 1497 auto *Result = new (C, DC) 1498 ObjCInterfaceDecl(C, DC, atLoc, Id, typeParamList, ClassLoc, PrevDecl, 1499 isInternal); 1500 Result->Data.setInt(!C.getLangOpts().Modules); 1501 C.getObjCInterfaceType(Result, PrevDecl); 1502 return Result; 1503 } 1504 1505 ObjCInterfaceDecl *ObjCInterfaceDecl::CreateDeserialized(const ASTContext &C, 1506 unsigned ID) { 1507 auto *Result = new (C, ID) 1508 ObjCInterfaceDecl(C, nullptr, SourceLocation(), nullptr, nullptr, 1509 SourceLocation(), nullptr, false); 1510 Result->Data.setInt(!C.getLangOpts().Modules); 1511 return Result; 1512 } 1513 1514 ObjCInterfaceDecl::ObjCInterfaceDecl(const ASTContext &C, DeclContext *DC, 1515 SourceLocation AtLoc, IdentifierInfo *Id, 1516 ObjCTypeParamList *typeParamList, 1517 SourceLocation CLoc, 1518 ObjCInterfaceDecl *PrevDecl, 1519 bool IsInternal) 1520 : ObjCContainerDecl(ObjCInterface, DC, Id, CLoc, AtLoc), 1521 redeclarable_base(C) { 1522 setPreviousDecl(PrevDecl); 1523 1524 // Copy the 'data' pointer over. 1525 if (PrevDecl) 1526 Data = PrevDecl->Data; 1527 1528 setImplicit(IsInternal); 1529 1530 setTypeParamList(typeParamList); 1531 } 1532 1533 void ObjCInterfaceDecl::LoadExternalDefinition() const { 1534 assert(data().ExternallyCompleted && "Class is not externally completed"); 1535 data().ExternallyCompleted = false; 1536 getASTContext().getExternalSource()->CompleteType( 1537 const_cast<ObjCInterfaceDecl *>(this)); 1538 } 1539 1540 void ObjCInterfaceDecl::setExternallyCompleted() { 1541 assert(getASTContext().getExternalSource() && 1542 "Class can't be externally completed without an external source"); 1543 assert(hasDefinition() && 1544 "Forward declarations can't be externally completed"); 1545 data().ExternallyCompleted = true; 1546 } 1547 1548 void ObjCInterfaceDecl::setHasDesignatedInitializers() { 1549 // Check for a complete definition and recover if not so. 1550 if (!isThisDeclarationADefinition()) 1551 return; 1552 data().HasDesignatedInitializers = true; 1553 } 1554 1555 bool ObjCInterfaceDecl::hasDesignatedInitializers() const { 1556 // Check for a complete definition and recover if not so. 1557 if (!isThisDeclarationADefinition()) 1558 return false; 1559 if (data().ExternallyCompleted) 1560 LoadExternalDefinition(); 1561 1562 return data().HasDesignatedInitializers; 1563 } 1564 1565 StringRef 1566 ObjCInterfaceDecl::getObjCRuntimeNameAsString() const { 1567 if (const auto *ObjCRTName = getAttr<ObjCRuntimeNameAttr>()) 1568 return ObjCRTName->getMetadataName(); 1569 1570 return getName(); 1571 } 1572 1573 StringRef 1574 ObjCImplementationDecl::getObjCRuntimeNameAsString() const { 1575 if (ObjCInterfaceDecl *ID = 1576 const_cast<ObjCImplementationDecl*>(this)->getClassInterface()) 1577 return ID->getObjCRuntimeNameAsString(); 1578 1579 return getName(); 1580 } 1581 1582 ObjCImplementationDecl *ObjCInterfaceDecl::getImplementation() const { 1583 if (const ObjCInterfaceDecl *Def = getDefinition()) { 1584 if (data().ExternallyCompleted) 1585 LoadExternalDefinition(); 1586 1587 return getASTContext().getObjCImplementation( 1588 const_cast<ObjCInterfaceDecl*>(Def)); 1589 } 1590 1591 // FIXME: Should make sure no callers ever do this. 1592 return nullptr; 1593 } 1594 1595 void ObjCInterfaceDecl::setImplementation(ObjCImplementationDecl *ImplD) { 1596 getASTContext().setObjCImplementation(getDefinition(), ImplD); 1597 } 1598 1599 namespace { 1600 1601 struct SynthesizeIvarChunk { 1602 uint64_t Size; 1603 ObjCIvarDecl *Ivar; 1604 1605 SynthesizeIvarChunk(uint64_t size, ObjCIvarDecl *ivar) 1606 : Size(size), Ivar(ivar) {} 1607 }; 1608 1609 bool operator<(const SynthesizeIvarChunk & LHS, 1610 const SynthesizeIvarChunk &RHS) { 1611 return LHS.Size < RHS.Size; 1612 } 1613 1614 } // namespace 1615 1616 /// all_declared_ivar_begin - return first ivar declared in this class, 1617 /// its extensions and its implementation. Lazily build the list on first 1618 /// access. 1619 /// 1620 /// Caveat: The list returned by this method reflects the current 1621 /// state of the parser. The cache will be updated for every ivar 1622 /// added by an extension or the implementation when they are 1623 /// encountered. 1624 /// See also ObjCIvarDecl::Create(). 1625 ObjCIvarDecl *ObjCInterfaceDecl::all_declared_ivar_begin() { 1626 // FIXME: Should make sure no callers ever do this. 1627 if (!hasDefinition()) 1628 return nullptr; 1629 1630 ObjCIvarDecl *curIvar = nullptr; 1631 if (!data().IvarList) { 1632 if (!ivar_empty()) { 1633 ObjCInterfaceDecl::ivar_iterator I = ivar_begin(), E = ivar_end(); 1634 data().IvarList = *I; ++I; 1635 for (curIvar = data().IvarList; I != E; curIvar = *I, ++I) 1636 curIvar->setNextIvar(*I); 1637 } 1638 1639 for (const auto *Ext : known_extensions()) { 1640 if (!Ext->ivar_empty()) { 1641 ObjCCategoryDecl::ivar_iterator 1642 I = Ext->ivar_begin(), 1643 E = Ext->ivar_end(); 1644 if (!data().IvarList) { 1645 data().IvarList = *I; ++I; 1646 curIvar = data().IvarList; 1647 } 1648 for ( ;I != E; curIvar = *I, ++I) 1649 curIvar->setNextIvar(*I); 1650 } 1651 } 1652 data().IvarListMissingImplementation = true; 1653 } 1654 1655 // cached and complete! 1656 if (!data().IvarListMissingImplementation) 1657 return data().IvarList; 1658 1659 if (ObjCImplementationDecl *ImplDecl = getImplementation()) { 1660 data().IvarListMissingImplementation = false; 1661 if (!ImplDecl->ivar_empty()) { 1662 SmallVector<SynthesizeIvarChunk, 16> layout; 1663 for (auto *IV : ImplDecl->ivars()) { 1664 if (IV->getSynthesize() && !IV->isInvalidDecl()) { 1665 layout.push_back(SynthesizeIvarChunk( 1666 IV->getASTContext().getTypeSize(IV->getType()), IV)); 1667 continue; 1668 } 1669 if (!data().IvarList) 1670 data().IvarList = IV; 1671 else 1672 curIvar->setNextIvar(IV); 1673 curIvar = IV; 1674 } 1675 1676 if (!layout.empty()) { 1677 // Order synthesized ivars by their size. 1678 llvm::stable_sort(layout); 1679 unsigned Ix = 0, EIx = layout.size(); 1680 if (!data().IvarList) { 1681 data().IvarList = layout[0].Ivar; Ix++; 1682 curIvar = data().IvarList; 1683 } 1684 for ( ; Ix != EIx; curIvar = layout[Ix].Ivar, Ix++) 1685 curIvar->setNextIvar(layout[Ix].Ivar); 1686 } 1687 } 1688 } 1689 return data().IvarList; 1690 } 1691 1692 /// FindCategoryDeclaration - Finds category declaration in the list of 1693 /// categories for this class and returns it. Name of the category is passed 1694 /// in 'CategoryId'. If category not found, return 0; 1695 /// 1696 ObjCCategoryDecl * 1697 ObjCInterfaceDecl::FindCategoryDeclaration(IdentifierInfo *CategoryId) const { 1698 // FIXME: Should make sure no callers ever do this. 1699 if (!hasDefinition()) 1700 return nullptr; 1701 1702 if (data().ExternallyCompleted) 1703 LoadExternalDefinition(); 1704 1705 for (auto *Cat : visible_categories()) 1706 if (Cat->getIdentifier() == CategoryId) 1707 return Cat; 1708 1709 return nullptr; 1710 } 1711 1712 ObjCMethodDecl * 1713 ObjCInterfaceDecl::getCategoryInstanceMethod(Selector Sel) const { 1714 for (const auto *Cat : visible_categories()) { 1715 if (ObjCCategoryImplDecl *Impl = Cat->getImplementation()) 1716 if (ObjCMethodDecl *MD = Impl->getInstanceMethod(Sel)) 1717 return MD; 1718 } 1719 1720 return nullptr; 1721 } 1722 1723 ObjCMethodDecl *ObjCInterfaceDecl::getCategoryClassMethod(Selector Sel) const { 1724 for (const auto *Cat : visible_categories()) { 1725 if (ObjCCategoryImplDecl *Impl = Cat->getImplementation()) 1726 if (ObjCMethodDecl *MD = Impl->getClassMethod(Sel)) 1727 return MD; 1728 } 1729 1730 return nullptr; 1731 } 1732 1733 /// ClassImplementsProtocol - Checks that 'lProto' protocol 1734 /// has been implemented in IDecl class, its super class or categories (if 1735 /// lookupCategory is true). 1736 bool ObjCInterfaceDecl::ClassImplementsProtocol(ObjCProtocolDecl *lProto, 1737 bool lookupCategory, 1738 bool RHSIsQualifiedID) { 1739 if (!hasDefinition()) 1740 return false; 1741 1742 ObjCInterfaceDecl *IDecl = this; 1743 // 1st, look up the class. 1744 for (auto *PI : IDecl->protocols()){ 1745 if (getASTContext().ProtocolCompatibleWithProtocol(lProto, PI)) 1746 return true; 1747 // This is dubious and is added to be compatible with gcc. In gcc, it is 1748 // also allowed assigning a protocol-qualified 'id' type to a LHS object 1749 // when protocol in qualified LHS is in list of protocols in the rhs 'id' 1750 // object. This IMO, should be a bug. 1751 // FIXME: Treat this as an extension, and flag this as an error when GCC 1752 // extensions are not enabled. 1753 if (RHSIsQualifiedID && 1754 getASTContext().ProtocolCompatibleWithProtocol(PI, lProto)) 1755 return true; 1756 } 1757 1758 // 2nd, look up the category. 1759 if (lookupCategory) 1760 for (const auto *Cat : visible_categories()) { 1761 for (auto *PI : Cat->protocols()) 1762 if (getASTContext().ProtocolCompatibleWithProtocol(lProto, PI)) 1763 return true; 1764 } 1765 1766 // 3rd, look up the super class(s) 1767 if (IDecl->getSuperClass()) 1768 return 1769 IDecl->getSuperClass()->ClassImplementsProtocol(lProto, lookupCategory, 1770 RHSIsQualifiedID); 1771 1772 return false; 1773 } 1774 1775 //===----------------------------------------------------------------------===// 1776 // ObjCIvarDecl 1777 //===----------------------------------------------------------------------===// 1778 1779 void ObjCIvarDecl::anchor() {} 1780 1781 ObjCIvarDecl *ObjCIvarDecl::Create(ASTContext &C, ObjCContainerDecl *DC, 1782 SourceLocation StartLoc, 1783 SourceLocation IdLoc, IdentifierInfo *Id, 1784 QualType T, TypeSourceInfo *TInfo, 1785 AccessControl ac, Expr *BW, 1786 bool synthesized) { 1787 if (DC) { 1788 // Ivar's can only appear in interfaces, implementations (via synthesized 1789 // properties), and class extensions (via direct declaration, or synthesized 1790 // properties). 1791 // 1792 // FIXME: This should really be asserting this: 1793 // (isa<ObjCCategoryDecl>(DC) && 1794 // cast<ObjCCategoryDecl>(DC)->IsClassExtension())) 1795 // but unfortunately we sometimes place ivars into non-class extension 1796 // categories on error. This breaks an AST invariant, and should not be 1797 // fixed. 1798 assert((isa<ObjCInterfaceDecl>(DC) || isa<ObjCImplementationDecl>(DC) || 1799 isa<ObjCCategoryDecl>(DC)) && 1800 "Invalid ivar decl context!"); 1801 // Once a new ivar is created in any of class/class-extension/implementation 1802 // decl contexts, the previously built IvarList must be rebuilt. 1803 auto *ID = dyn_cast<ObjCInterfaceDecl>(DC); 1804 if (!ID) { 1805 if (auto *IM = dyn_cast<ObjCImplementationDecl>(DC)) 1806 ID = IM->getClassInterface(); 1807 else 1808 ID = cast<ObjCCategoryDecl>(DC)->getClassInterface(); 1809 } 1810 ID->setIvarList(nullptr); 1811 } 1812 1813 return new (C, DC) ObjCIvarDecl(DC, StartLoc, IdLoc, Id, T, TInfo, ac, BW, 1814 synthesized); 1815 } 1816 1817 ObjCIvarDecl *ObjCIvarDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 1818 return new (C, ID) ObjCIvarDecl(nullptr, SourceLocation(), SourceLocation(), 1819 nullptr, QualType(), nullptr, 1820 ObjCIvarDecl::None, nullptr, false); 1821 } 1822 1823 const ObjCInterfaceDecl *ObjCIvarDecl::getContainingInterface() const { 1824 const auto *DC = cast<ObjCContainerDecl>(getDeclContext()); 1825 1826 switch (DC->getKind()) { 1827 default: 1828 case ObjCCategoryImpl: 1829 case ObjCProtocol: 1830 llvm_unreachable("invalid ivar container!"); 1831 1832 // Ivars can only appear in class extension categories. 1833 case ObjCCategory: { 1834 const auto *CD = cast<ObjCCategoryDecl>(DC); 1835 assert(CD->IsClassExtension() && "invalid container for ivar!"); 1836 return CD->getClassInterface(); 1837 } 1838 1839 case ObjCImplementation: 1840 return cast<ObjCImplementationDecl>(DC)->getClassInterface(); 1841 1842 case ObjCInterface: 1843 return cast<ObjCInterfaceDecl>(DC); 1844 } 1845 } 1846 1847 QualType ObjCIvarDecl::getUsageType(QualType objectType) const { 1848 return getType().substObjCMemberType(objectType, getDeclContext(), 1849 ObjCSubstitutionContext::Property); 1850 } 1851 1852 //===----------------------------------------------------------------------===// 1853 // ObjCAtDefsFieldDecl 1854 //===----------------------------------------------------------------------===// 1855 1856 void ObjCAtDefsFieldDecl::anchor() {} 1857 1858 ObjCAtDefsFieldDecl 1859 *ObjCAtDefsFieldDecl::Create(ASTContext &C, DeclContext *DC, 1860 SourceLocation StartLoc, SourceLocation IdLoc, 1861 IdentifierInfo *Id, QualType T, Expr *BW) { 1862 return new (C, DC) ObjCAtDefsFieldDecl(DC, StartLoc, IdLoc, Id, T, BW); 1863 } 1864 1865 ObjCAtDefsFieldDecl *ObjCAtDefsFieldDecl::CreateDeserialized(ASTContext &C, 1866 unsigned ID) { 1867 return new (C, ID) ObjCAtDefsFieldDecl(nullptr, SourceLocation(), 1868 SourceLocation(), nullptr, QualType(), 1869 nullptr); 1870 } 1871 1872 //===----------------------------------------------------------------------===// 1873 // ObjCProtocolDecl 1874 //===----------------------------------------------------------------------===// 1875 1876 void ObjCProtocolDecl::anchor() {} 1877 1878 ObjCProtocolDecl::ObjCProtocolDecl(ASTContext &C, DeclContext *DC, 1879 IdentifierInfo *Id, SourceLocation nameLoc, 1880 SourceLocation atStartLoc, 1881 ObjCProtocolDecl *PrevDecl) 1882 : ObjCContainerDecl(ObjCProtocol, DC, Id, nameLoc, atStartLoc), 1883 redeclarable_base(C) { 1884 setPreviousDecl(PrevDecl); 1885 if (PrevDecl) 1886 Data = PrevDecl->Data; 1887 } 1888 1889 ObjCProtocolDecl *ObjCProtocolDecl::Create(ASTContext &C, DeclContext *DC, 1890 IdentifierInfo *Id, 1891 SourceLocation nameLoc, 1892 SourceLocation atStartLoc, 1893 ObjCProtocolDecl *PrevDecl) { 1894 auto *Result = 1895 new (C, DC) ObjCProtocolDecl(C, DC, Id, nameLoc, atStartLoc, PrevDecl); 1896 Result->Data.setInt(!C.getLangOpts().Modules); 1897 return Result; 1898 } 1899 1900 ObjCProtocolDecl *ObjCProtocolDecl::CreateDeserialized(ASTContext &C, 1901 unsigned ID) { 1902 ObjCProtocolDecl *Result = 1903 new (C, ID) ObjCProtocolDecl(C, nullptr, nullptr, SourceLocation(), 1904 SourceLocation(), nullptr); 1905 Result->Data.setInt(!C.getLangOpts().Modules); 1906 return Result; 1907 } 1908 1909 bool ObjCProtocolDecl::isNonRuntimeProtocol() const { 1910 return hasAttr<ObjCNonRuntimeProtocolAttr>(); 1911 } 1912 1913 void ObjCProtocolDecl::getImpliedProtocols( 1914 llvm::DenseSet<const ObjCProtocolDecl *> &IPs) const { 1915 std::queue<const ObjCProtocolDecl *> WorkQueue; 1916 WorkQueue.push(this); 1917 1918 while (!WorkQueue.empty()) { 1919 const auto *PD = WorkQueue.front(); 1920 WorkQueue.pop(); 1921 for (const auto *Parent : PD->protocols()) { 1922 const auto *Can = Parent->getCanonicalDecl(); 1923 auto Result = IPs.insert(Can); 1924 if (Result.second) 1925 WorkQueue.push(Parent); 1926 } 1927 } 1928 } 1929 1930 ObjCProtocolDecl *ObjCProtocolDecl::lookupProtocolNamed(IdentifierInfo *Name) { 1931 ObjCProtocolDecl *PDecl = this; 1932 1933 if (Name == getIdentifier()) 1934 return PDecl; 1935 1936 for (auto *I : protocols()) 1937 if ((PDecl = I->lookupProtocolNamed(Name))) 1938 return PDecl; 1939 1940 return nullptr; 1941 } 1942 1943 // lookupMethod - Lookup a instance/class method in the protocol and protocols 1944 // it inherited. 1945 ObjCMethodDecl *ObjCProtocolDecl::lookupMethod(Selector Sel, 1946 bool isInstance) const { 1947 ObjCMethodDecl *MethodDecl = nullptr; 1948 1949 // If there is no definition or the definition is hidden, we don't find 1950 // anything. 1951 const ObjCProtocolDecl *Def = getDefinition(); 1952 if (!Def || !Def->isUnconditionallyVisible()) 1953 return nullptr; 1954 1955 if ((MethodDecl = getMethod(Sel, isInstance))) 1956 return MethodDecl; 1957 1958 for (const auto *I : protocols()) 1959 if ((MethodDecl = I->lookupMethod(Sel, isInstance))) 1960 return MethodDecl; 1961 return nullptr; 1962 } 1963 1964 void ObjCProtocolDecl::allocateDefinitionData() { 1965 assert(!Data.getPointer() && "Protocol already has a definition!"); 1966 Data.setPointer(new (getASTContext()) DefinitionData); 1967 Data.getPointer()->Definition = this; 1968 } 1969 1970 void ObjCProtocolDecl::startDefinition() { 1971 allocateDefinitionData(); 1972 1973 // Update all of the declarations with a pointer to the definition. 1974 for (auto *RD : redecls()) 1975 RD->Data = this->Data; 1976 } 1977 1978 void ObjCProtocolDecl::collectPropertiesToImplement(PropertyMap &PM, 1979 PropertyDeclOrder &PO) const { 1980 if (const ObjCProtocolDecl *PDecl = getDefinition()) { 1981 for (auto *Prop : PDecl->properties()) { 1982 // Insert into PM if not there already. 1983 PM.insert(std::make_pair( 1984 std::make_pair(Prop->getIdentifier(), Prop->isClassProperty()), 1985 Prop)); 1986 PO.push_back(Prop); 1987 } 1988 // Scan through protocol's protocols. 1989 for (const auto *PI : PDecl->protocols()) 1990 PI->collectPropertiesToImplement(PM, PO); 1991 } 1992 } 1993 1994 void ObjCProtocolDecl::collectInheritedProtocolProperties( 1995 const ObjCPropertyDecl *Property, ProtocolPropertySet &PS, 1996 PropertyDeclOrder &PO) const { 1997 if (const ObjCProtocolDecl *PDecl = getDefinition()) { 1998 if (!PS.insert(PDecl).second) 1999 return; 2000 for (auto *Prop : PDecl->properties()) { 2001 if (Prop == Property) 2002 continue; 2003 if (Prop->getIdentifier() == Property->getIdentifier()) { 2004 PO.push_back(Prop); 2005 return; 2006 } 2007 } 2008 // Scan through protocol's protocols which did not have a matching property. 2009 for (const auto *PI : PDecl->protocols()) 2010 PI->collectInheritedProtocolProperties(Property, PS, PO); 2011 } 2012 } 2013 2014 StringRef 2015 ObjCProtocolDecl::getObjCRuntimeNameAsString() const { 2016 if (const auto *ObjCRTName = getAttr<ObjCRuntimeNameAttr>()) 2017 return ObjCRTName->getMetadataName(); 2018 2019 return getName(); 2020 } 2021 2022 //===----------------------------------------------------------------------===// 2023 // ObjCCategoryDecl 2024 //===----------------------------------------------------------------------===// 2025 2026 void ObjCCategoryDecl::anchor() {} 2027 2028 ObjCCategoryDecl::ObjCCategoryDecl(DeclContext *DC, SourceLocation AtLoc, 2029 SourceLocation ClassNameLoc, 2030 SourceLocation CategoryNameLoc, 2031 IdentifierInfo *Id, ObjCInterfaceDecl *IDecl, 2032 ObjCTypeParamList *typeParamList, 2033 SourceLocation IvarLBraceLoc, 2034 SourceLocation IvarRBraceLoc) 2035 : ObjCContainerDecl(ObjCCategory, DC, Id, ClassNameLoc, AtLoc), 2036 ClassInterface(IDecl), CategoryNameLoc(CategoryNameLoc), 2037 IvarLBraceLoc(IvarLBraceLoc), IvarRBraceLoc(IvarRBraceLoc) { 2038 setTypeParamList(typeParamList); 2039 } 2040 2041 ObjCCategoryDecl *ObjCCategoryDecl::Create(ASTContext &C, DeclContext *DC, 2042 SourceLocation AtLoc, 2043 SourceLocation ClassNameLoc, 2044 SourceLocation CategoryNameLoc, 2045 IdentifierInfo *Id, 2046 ObjCInterfaceDecl *IDecl, 2047 ObjCTypeParamList *typeParamList, 2048 SourceLocation IvarLBraceLoc, 2049 SourceLocation IvarRBraceLoc) { 2050 auto *CatDecl = 2051 new (C, DC) ObjCCategoryDecl(DC, AtLoc, ClassNameLoc, CategoryNameLoc, Id, 2052 IDecl, typeParamList, IvarLBraceLoc, 2053 IvarRBraceLoc); 2054 if (IDecl) { 2055 // Link this category into its class's category list. 2056 CatDecl->NextClassCategory = IDecl->getCategoryListRaw(); 2057 if (IDecl->hasDefinition()) { 2058 IDecl->setCategoryListRaw(CatDecl); 2059 if (ASTMutationListener *L = C.getASTMutationListener()) 2060 L->AddedObjCCategoryToInterface(CatDecl, IDecl); 2061 } 2062 } 2063 2064 return CatDecl; 2065 } 2066 2067 ObjCCategoryDecl *ObjCCategoryDecl::CreateDeserialized(ASTContext &C, 2068 unsigned ID) { 2069 return new (C, ID) ObjCCategoryDecl(nullptr, SourceLocation(), 2070 SourceLocation(), SourceLocation(), 2071 nullptr, nullptr, nullptr); 2072 } 2073 2074 ObjCCategoryImplDecl *ObjCCategoryDecl::getImplementation() const { 2075 return getASTContext().getObjCImplementation( 2076 const_cast<ObjCCategoryDecl*>(this)); 2077 } 2078 2079 void ObjCCategoryDecl::setImplementation(ObjCCategoryImplDecl *ImplD) { 2080 getASTContext().setObjCImplementation(this, ImplD); 2081 } 2082 2083 void ObjCCategoryDecl::setTypeParamList(ObjCTypeParamList *TPL) { 2084 TypeParamList = TPL; 2085 if (!TPL) 2086 return; 2087 // Set the declaration context of each of the type parameters. 2088 for (auto *typeParam : *TypeParamList) 2089 typeParam->setDeclContext(this); 2090 } 2091 2092 //===----------------------------------------------------------------------===// 2093 // ObjCCategoryImplDecl 2094 //===----------------------------------------------------------------------===// 2095 2096 void ObjCCategoryImplDecl::anchor() {} 2097 2098 ObjCCategoryImplDecl * 2099 ObjCCategoryImplDecl::Create(ASTContext &C, DeclContext *DC, 2100 IdentifierInfo *Id, 2101 ObjCInterfaceDecl *ClassInterface, 2102 SourceLocation nameLoc, 2103 SourceLocation atStartLoc, 2104 SourceLocation CategoryNameLoc) { 2105 if (ClassInterface && ClassInterface->hasDefinition()) 2106 ClassInterface = ClassInterface->getDefinition(); 2107 return new (C, DC) ObjCCategoryImplDecl(DC, Id, ClassInterface, nameLoc, 2108 atStartLoc, CategoryNameLoc); 2109 } 2110 2111 ObjCCategoryImplDecl *ObjCCategoryImplDecl::CreateDeserialized(ASTContext &C, 2112 unsigned ID) { 2113 return new (C, ID) ObjCCategoryImplDecl(nullptr, nullptr, nullptr, 2114 SourceLocation(), SourceLocation(), 2115 SourceLocation()); 2116 } 2117 2118 ObjCCategoryDecl *ObjCCategoryImplDecl::getCategoryDecl() const { 2119 // The class interface might be NULL if we are working with invalid code. 2120 if (const ObjCInterfaceDecl *ID = getClassInterface()) 2121 return ID->FindCategoryDeclaration(getIdentifier()); 2122 return nullptr; 2123 } 2124 2125 void ObjCImplDecl::anchor() {} 2126 2127 void ObjCImplDecl::addPropertyImplementation(ObjCPropertyImplDecl *property) { 2128 // FIXME: The context should be correct before we get here. 2129 property->setLexicalDeclContext(this); 2130 addDecl(property); 2131 } 2132 2133 void ObjCImplDecl::setClassInterface(ObjCInterfaceDecl *IFace) { 2134 ASTContext &Ctx = getASTContext(); 2135 2136 if (auto *ImplD = dyn_cast_or_null<ObjCImplementationDecl>(this)) { 2137 if (IFace) 2138 Ctx.setObjCImplementation(IFace, ImplD); 2139 2140 } else if (auto *ImplD = dyn_cast_or_null<ObjCCategoryImplDecl>(this)) { 2141 if (ObjCCategoryDecl *CD = IFace->FindCategoryDeclaration(getIdentifier())) 2142 Ctx.setObjCImplementation(CD, ImplD); 2143 } 2144 2145 ClassInterface = IFace; 2146 } 2147 2148 /// FindPropertyImplIvarDecl - This method lookup the ivar in the list of 2149 /// properties implemented in this \@implementation block and returns 2150 /// the implemented property that uses it. 2151 ObjCPropertyImplDecl *ObjCImplDecl:: 2152 FindPropertyImplIvarDecl(IdentifierInfo *ivarId) const { 2153 for (auto *PID : property_impls()) 2154 if (PID->getPropertyIvarDecl() && 2155 PID->getPropertyIvarDecl()->getIdentifier() == ivarId) 2156 return PID; 2157 return nullptr; 2158 } 2159 2160 /// FindPropertyImplDecl - This method looks up a previous ObjCPropertyImplDecl 2161 /// added to the list of those properties \@synthesized/\@dynamic in this 2162 /// category \@implementation block. 2163 ObjCPropertyImplDecl *ObjCImplDecl:: 2164 FindPropertyImplDecl(IdentifierInfo *Id, 2165 ObjCPropertyQueryKind QueryKind) const { 2166 ObjCPropertyImplDecl *ClassPropImpl = nullptr; 2167 for (auto *PID : property_impls()) 2168 // If queryKind is unknown, we return the instance property if one 2169 // exists; otherwise we return the class property. 2170 if (PID->getPropertyDecl()->getIdentifier() == Id) { 2171 if ((QueryKind == ObjCPropertyQueryKind::OBJC_PR_query_unknown && 2172 !PID->getPropertyDecl()->isClassProperty()) || 2173 (QueryKind == ObjCPropertyQueryKind::OBJC_PR_query_class && 2174 PID->getPropertyDecl()->isClassProperty()) || 2175 (QueryKind == ObjCPropertyQueryKind::OBJC_PR_query_instance && 2176 !PID->getPropertyDecl()->isClassProperty())) 2177 return PID; 2178 2179 if (PID->getPropertyDecl()->isClassProperty()) 2180 ClassPropImpl = PID; 2181 } 2182 2183 if (QueryKind == ObjCPropertyQueryKind::OBJC_PR_query_unknown) 2184 // We can't find the instance property, return the class property. 2185 return ClassPropImpl; 2186 2187 return nullptr; 2188 } 2189 2190 raw_ostream &clang::operator<<(raw_ostream &OS, 2191 const ObjCCategoryImplDecl &CID) { 2192 OS << CID.getName(); 2193 return OS; 2194 } 2195 2196 //===----------------------------------------------------------------------===// 2197 // ObjCImplementationDecl 2198 //===----------------------------------------------------------------------===// 2199 2200 void ObjCImplementationDecl::anchor() {} 2201 2202 ObjCImplementationDecl * 2203 ObjCImplementationDecl::Create(ASTContext &C, DeclContext *DC, 2204 ObjCInterfaceDecl *ClassInterface, 2205 ObjCInterfaceDecl *SuperDecl, 2206 SourceLocation nameLoc, 2207 SourceLocation atStartLoc, 2208 SourceLocation superLoc, 2209 SourceLocation IvarLBraceLoc, 2210 SourceLocation IvarRBraceLoc) { 2211 if (ClassInterface && ClassInterface->hasDefinition()) 2212 ClassInterface = ClassInterface->getDefinition(); 2213 return new (C, DC) ObjCImplementationDecl(DC, ClassInterface, SuperDecl, 2214 nameLoc, atStartLoc, superLoc, 2215 IvarLBraceLoc, IvarRBraceLoc); 2216 } 2217 2218 ObjCImplementationDecl * 2219 ObjCImplementationDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 2220 return new (C, ID) ObjCImplementationDecl(nullptr, nullptr, nullptr, 2221 SourceLocation(), SourceLocation()); 2222 } 2223 2224 void ObjCImplementationDecl::setIvarInitializers(ASTContext &C, 2225 CXXCtorInitializer ** initializers, 2226 unsigned numInitializers) { 2227 if (numInitializers > 0) { 2228 NumIvarInitializers = numInitializers; 2229 auto **ivarInitializers = new (C) CXXCtorInitializer*[NumIvarInitializers]; 2230 memcpy(ivarInitializers, initializers, 2231 numInitializers * sizeof(CXXCtorInitializer*)); 2232 IvarInitializers = ivarInitializers; 2233 } 2234 } 2235 2236 ObjCImplementationDecl::init_const_iterator 2237 ObjCImplementationDecl::init_begin() const { 2238 return IvarInitializers.get(getASTContext().getExternalSource()); 2239 } 2240 2241 raw_ostream &clang::operator<<(raw_ostream &OS, 2242 const ObjCImplementationDecl &ID) { 2243 OS << ID.getName(); 2244 return OS; 2245 } 2246 2247 //===----------------------------------------------------------------------===// 2248 // ObjCCompatibleAliasDecl 2249 //===----------------------------------------------------------------------===// 2250 2251 void ObjCCompatibleAliasDecl::anchor() {} 2252 2253 ObjCCompatibleAliasDecl * 2254 ObjCCompatibleAliasDecl::Create(ASTContext &C, DeclContext *DC, 2255 SourceLocation L, 2256 IdentifierInfo *Id, 2257 ObjCInterfaceDecl* AliasedClass) { 2258 return new (C, DC) ObjCCompatibleAliasDecl(DC, L, Id, AliasedClass); 2259 } 2260 2261 ObjCCompatibleAliasDecl * 2262 ObjCCompatibleAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 2263 return new (C, ID) ObjCCompatibleAliasDecl(nullptr, SourceLocation(), 2264 nullptr, nullptr); 2265 } 2266 2267 //===----------------------------------------------------------------------===// 2268 // ObjCPropertyDecl 2269 //===----------------------------------------------------------------------===// 2270 2271 void ObjCPropertyDecl::anchor() {} 2272 2273 ObjCPropertyDecl *ObjCPropertyDecl::Create(ASTContext &C, DeclContext *DC, 2274 SourceLocation L, 2275 IdentifierInfo *Id, 2276 SourceLocation AtLoc, 2277 SourceLocation LParenLoc, 2278 QualType T, 2279 TypeSourceInfo *TSI, 2280 PropertyControl propControl) { 2281 return new (C, DC) ObjCPropertyDecl(DC, L, Id, AtLoc, LParenLoc, T, TSI, 2282 propControl); 2283 } 2284 2285 ObjCPropertyDecl *ObjCPropertyDecl::CreateDeserialized(ASTContext &C, 2286 unsigned ID) { 2287 return new (C, ID) ObjCPropertyDecl(nullptr, SourceLocation(), nullptr, 2288 SourceLocation(), SourceLocation(), 2289 QualType(), nullptr, None); 2290 } 2291 2292 QualType ObjCPropertyDecl::getUsageType(QualType objectType) const { 2293 return DeclType.substObjCMemberType(objectType, getDeclContext(), 2294 ObjCSubstitutionContext::Property); 2295 } 2296 2297 //===----------------------------------------------------------------------===// 2298 // ObjCPropertyImplDecl 2299 //===----------------------------------------------------------------------===// 2300 2301 ObjCPropertyImplDecl *ObjCPropertyImplDecl::Create(ASTContext &C, 2302 DeclContext *DC, 2303 SourceLocation atLoc, 2304 SourceLocation L, 2305 ObjCPropertyDecl *property, 2306 Kind PK, 2307 ObjCIvarDecl *ivar, 2308 SourceLocation ivarLoc) { 2309 return new (C, DC) ObjCPropertyImplDecl(DC, atLoc, L, property, PK, ivar, 2310 ivarLoc); 2311 } 2312 2313 ObjCPropertyImplDecl *ObjCPropertyImplDecl::CreateDeserialized(ASTContext &C, 2314 unsigned ID) { 2315 return new (C, ID) ObjCPropertyImplDecl(nullptr, SourceLocation(), 2316 SourceLocation(), nullptr, Dynamic, 2317 nullptr, SourceLocation()); 2318 } 2319 2320 SourceRange ObjCPropertyImplDecl::getSourceRange() const { 2321 SourceLocation EndLoc = getLocation(); 2322 if (IvarLoc.isValid()) 2323 EndLoc = IvarLoc; 2324 2325 return SourceRange(AtLoc, EndLoc); 2326 } 2327