Bug Summary

File:clang/lib/AST/DeclObjC.cpp
Warning:line 1664, column 11
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name DeclObjC.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-11/lib/clang/11.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/AST -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-11/lib/clang/11.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/lib/AST -fdebug-prefix-map=/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-03-09-184146-41876-1 -x c++ /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/AST/DeclObjC.cpp

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/AST/DeclObjC.cpp

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

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclObjC.h

1//===- DeclObjC.h - Classes for representing declarations -------*- C++ -*-===//
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 defines the DeclObjC interface and subclasses.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_AST_DECLOBJC_H
14#define LLVM_CLANG_AST_DECLOBJC_H
15
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclBase.h"
18#include "clang/AST/ExternalASTSource.h"
19#include "clang/AST/Redeclarable.h"
20#include "clang/AST/SelectorLocationsKind.h"
21#include "clang/AST/Type.h"
22#include "clang/Basic/IdentifierTable.h"
23#include "clang/Basic/LLVM.h"
24#include "clang/Basic/SourceLocation.h"
25#include "clang/Basic/Specifiers.h"
26#include "llvm/ADT/ArrayRef.h"
27#include "llvm/ADT/DenseMap.h"
28#include "llvm/ADT/DenseSet.h"
29#include "llvm/ADT/None.h"
30#include "llvm/ADT/PointerIntPair.h"
31#include "llvm/ADT/STLExtras.h"
32#include "llvm/ADT/StringRef.h"
33#include "llvm/ADT/iterator_range.h"
34#include "llvm/Support/Compiler.h"
35#include "llvm/Support/TrailingObjects.h"
36#include <cassert>
37#include <cstddef>
38#include <cstdint>
39#include <iterator>
40#include <string>
41#include <utility>
42
43namespace clang {
44
45class ASTContext;
46class CompoundStmt;
47class CXXCtorInitializer;
48class Expr;
49class ObjCCategoryDecl;
50class ObjCCategoryImplDecl;
51class ObjCImplementationDecl;
52class ObjCInterfaceDecl;
53class ObjCIvarDecl;
54class ObjCPropertyDecl;
55class ObjCPropertyImplDecl;
56class ObjCProtocolDecl;
57class Stmt;
58
59class ObjCListBase {
60protected:
61 /// List is an array of pointers to objects that are not owned by this object.
62 void **List = nullptr;
63 unsigned NumElts = 0;
64
65public:
66 ObjCListBase() = default;
67 ObjCListBase(const ObjCListBase &) = delete;
68 ObjCListBase &operator=(const ObjCListBase &) = delete;
69
70 unsigned size() const { return NumElts; }
71 bool empty() const { return NumElts == 0; }
72
73protected:
74 void set(void *const* InList, unsigned Elts, ASTContext &Ctx);
75};
76
77/// ObjCList - This is a simple template class used to hold various lists of
78/// decls etc, which is heavily used by the ObjC front-end. This only use case
79/// this supports is setting the list all at once and then reading elements out
80/// of it.
81template <typename T>
82class ObjCList : public ObjCListBase {
83public:
84 void set(T* const* InList, unsigned Elts, ASTContext &Ctx) {
85 ObjCListBase::set(reinterpret_cast<void*const*>(InList), Elts, Ctx);
86 }
87
88 using iterator = T* const *;
89
90 iterator begin() const { return (iterator)List; }
91 iterator end() const { return (iterator)List+NumElts; }
92
93 T* operator[](unsigned Idx) const {
94 assert(Idx < NumElts && "Invalid access")((Idx < NumElts && "Invalid access") ? static_cast
<void> (0) : __assert_fail ("Idx < NumElts && \"Invalid access\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclObjC.h"
, 94, __PRETTY_FUNCTION__))
;
95 return (T*)List[Idx];
96 }
97};
98
99/// A list of Objective-C protocols, along with the source
100/// locations at which they were referenced.
101class ObjCProtocolList : public ObjCList<ObjCProtocolDecl> {
102 SourceLocation *Locations = nullptr;
103
104 using ObjCList<ObjCProtocolDecl>::set;
105
106public:
107 ObjCProtocolList() = default;
108
109 using loc_iterator = const SourceLocation *;
110
111 loc_iterator loc_begin() const { return Locations; }
112 loc_iterator loc_end() const { return Locations + size(); }
113
114 void set(ObjCProtocolDecl* const* InList, unsigned Elts,
115 const SourceLocation *Locs, ASTContext &Ctx);
116};
117
118/// ObjCMethodDecl - Represents an instance or class method declaration.
119/// ObjC methods can be declared within 4 contexts: class interfaces,
120/// categories, protocols, and class implementations. While C++ member
121/// functions leverage C syntax, Objective-C method syntax is modeled after
122/// Smalltalk (using colons to specify argument types/expressions).
123/// Here are some brief examples:
124///
125/// Setter/getter instance methods:
126/// - (void)setMenu:(NSMenu *)menu;
127/// - (NSMenu *)menu;
128///
129/// Instance method that takes 2 NSView arguments:
130/// - (void)replaceSubview:(NSView *)oldView with:(NSView *)newView;
131///
132/// Getter class method:
133/// + (NSMenu *)defaultMenu;
134///
135/// A selector represents a unique name for a method. The selector names for
136/// the above methods are setMenu:, menu, replaceSubview:with:, and defaultMenu.
137///
138class ObjCMethodDecl : public NamedDecl, public DeclContext {
139 // This class stores some data in DeclContext::ObjCMethodDeclBits
140 // to save some space. Use the provided accessors to access it.
141
142public:
143 enum ImplementationControl { None, Required, Optional };
144
145private:
146 /// Return type of this method.
147 QualType MethodDeclType;
148
149 /// Type source information for the return type.
150 TypeSourceInfo *ReturnTInfo;
151
152 /// Array of ParmVarDecls for the formal parameters of this method
153 /// and optionally followed by selector locations.
154 void *ParamsAndSelLocs = nullptr;
155 unsigned NumParams = 0;
156
157 /// List of attributes for this method declaration.
158 SourceLocation DeclEndLoc; // the location of the ';' or '{'.
159
160 /// The following are only used for method definitions, null otherwise.
161 LazyDeclStmtPtr Body;
162
163 /// SelfDecl - Decl for the implicit self parameter. This is lazily
164 /// constructed by createImplicitParams.
165 ImplicitParamDecl *SelfDecl = nullptr;
166
167 /// CmdDecl - Decl for the implicit _cmd parameter. This is lazily
168 /// constructed by createImplicitParams.
169 ImplicitParamDecl *CmdDecl = nullptr;
170
171 ObjCMethodDecl(SourceLocation beginLoc, SourceLocation endLoc,
172 Selector SelInfo, QualType T, TypeSourceInfo *ReturnTInfo,
173 DeclContext *contextDecl, bool isInstance = true,
174 bool isVariadic = false, bool isPropertyAccessor = false,
175 bool isSynthesizedAccessorStub = false,
176 bool isImplicitlyDeclared = false, bool isDefined = false,
177 ImplementationControl impControl = None,
178 bool HasRelatedResultType = false);
179
180 SelectorLocationsKind getSelLocsKind() const {
181 return static_cast<SelectorLocationsKind>(ObjCMethodDeclBits.SelLocsKind);
182 }
183
184 void setSelLocsKind(SelectorLocationsKind Kind) {
185 ObjCMethodDeclBits.SelLocsKind = Kind;
186 }
187
188 bool hasStandardSelLocs() const {
189 return getSelLocsKind() != SelLoc_NonStandard;
190 }
191
192 /// Get a pointer to the stored selector identifiers locations array.
193 /// No locations will be stored if HasStandardSelLocs is true.
194 SourceLocation *getStoredSelLocs() {
195 return reinterpret_cast<SourceLocation *>(getParams() + NumParams);
196 }
197 const SourceLocation *getStoredSelLocs() const {
198 return reinterpret_cast<const SourceLocation *>(getParams() + NumParams);
199 }
200
201 /// Get a pointer to the stored selector identifiers locations array.
202 /// No locations will be stored if HasStandardSelLocs is true.
203 ParmVarDecl **getParams() {
204 return reinterpret_cast<ParmVarDecl **>(ParamsAndSelLocs);
205 }
206 const ParmVarDecl *const *getParams() const {
207 return reinterpret_cast<const ParmVarDecl *const *>(ParamsAndSelLocs);
208 }
209
210 /// Get the number of stored selector identifiers locations.
211 /// No locations will be stored if HasStandardSelLocs is true.
212 unsigned getNumStoredSelLocs() const {
213 if (hasStandardSelLocs())
214 return 0;
215 return getNumSelectorLocs();
216 }
217
218 void setParamsAndSelLocs(ASTContext &C,
219 ArrayRef<ParmVarDecl*> Params,
220 ArrayRef<SourceLocation> SelLocs);
221
222 /// A definition will return its interface declaration.
223 /// An interface declaration will return its definition.
224 /// Otherwise it will return itself.
225 ObjCMethodDecl *getNextRedeclarationImpl() override;
226
227public:
228 friend class ASTDeclReader;
229 friend class ASTDeclWriter;
230
231 static ObjCMethodDecl *
232 Create(ASTContext &C, SourceLocation beginLoc, SourceLocation endLoc,
233 Selector SelInfo, QualType T, TypeSourceInfo *ReturnTInfo,
234 DeclContext *contextDecl, bool isInstance = true,
235 bool isVariadic = false, bool isPropertyAccessor = false,
236 bool isSynthesizedAccessorStub = false,
237 bool isImplicitlyDeclared = false, bool isDefined = false,
238 ImplementationControl impControl = None,
239 bool HasRelatedResultType = false);
240
241 static ObjCMethodDecl *CreateDeserialized(ASTContext &C, unsigned ID);
242
243 ObjCMethodDecl *getCanonicalDecl() override;
244 const ObjCMethodDecl *getCanonicalDecl() const {
245 return const_cast<ObjCMethodDecl*>(this)->getCanonicalDecl();
246 }
247
248 ObjCDeclQualifier getObjCDeclQualifier() const {
249 return static_cast<ObjCDeclQualifier>(ObjCMethodDeclBits.objcDeclQualifier);
250 }
251
252 void setObjCDeclQualifier(ObjCDeclQualifier QV) {
253 ObjCMethodDeclBits.objcDeclQualifier = QV;
254 }
255
256 /// Determine whether this method has a result type that is related
257 /// to the message receiver's type.
258 bool hasRelatedResultType() const {
259 return ObjCMethodDeclBits.RelatedResultType;
260 }
261
262 /// Note whether this method has a related result type.
263 void setRelatedResultType(bool RRT = true) {
264 ObjCMethodDeclBits.RelatedResultType = RRT;
265 }
266
267 /// True if this is a method redeclaration in the same interface.
268 bool isRedeclaration() const { return ObjCMethodDeclBits.IsRedeclaration; }
269 void setIsRedeclaration(bool RD) { ObjCMethodDeclBits.IsRedeclaration = RD; }
270 void setAsRedeclaration(const ObjCMethodDecl *PrevMethod);
271
272 /// True if redeclared in the same interface.
273 bool hasRedeclaration() const { return ObjCMethodDeclBits.HasRedeclaration; }
274 void setHasRedeclaration(bool HRD) const {
275 ObjCMethodDeclBits.HasRedeclaration = HRD;
276 }
277
278 /// Returns the location where the declarator ends. It will be
279 /// the location of ';' for a method declaration and the location of '{'
280 /// for a method definition.
281 SourceLocation getDeclaratorEndLoc() const { return DeclEndLoc; }
282
283 // Location information, modeled after the Stmt API.
284 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return getLocation(); }
285 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__));
286 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
287 return SourceRange(getLocation(), getEndLoc());
288 }
289
290 SourceLocation getSelectorStartLoc() const {
291 if (isImplicit())
292 return getBeginLoc();
293 return getSelectorLoc(0);
294 }
295
296 SourceLocation getSelectorLoc(unsigned Index) const {
297 assert(Index < getNumSelectorLocs() && "Index out of range!")((Index < getNumSelectorLocs() && "Index out of range!"
) ? static_cast<void> (0) : __assert_fail ("Index < getNumSelectorLocs() && \"Index out of range!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclObjC.h"
, 297, __PRETTY_FUNCTION__))
;
298 if (hasStandardSelLocs())
299 return getStandardSelectorLoc(Index, getSelector(),
300 getSelLocsKind() == SelLoc_StandardWithSpace,
301 parameters(),
302 DeclEndLoc);
303 return getStoredSelLocs()[Index];
304 }
305
306 void getSelectorLocs(SmallVectorImpl<SourceLocation> &SelLocs) const;
307
308 unsigned getNumSelectorLocs() const {
309 if (isImplicit())
310 return 0;
311 Selector Sel = getSelector();
312 if (Sel.isUnarySelector())
313 return 1;
314 return Sel.getNumArgs();
315 }
316
317 ObjCInterfaceDecl *getClassInterface();
318 const ObjCInterfaceDecl *getClassInterface() const {
319 return const_cast<ObjCMethodDecl*>(this)->getClassInterface();
320 }
321
322 Selector getSelector() const { return getDeclName().getObjCSelector(); }
323
324 QualType getReturnType() const { return MethodDeclType; }
325 void setReturnType(QualType T) { MethodDeclType = T; }
326 SourceRange getReturnTypeSourceRange() const;
327
328 /// Determine the type of an expression that sends a message to this
329 /// function. This replaces the type parameters with the types they would
330 /// get if the receiver was parameterless (e.g. it may replace the type
331 /// parameter with 'id').
332 QualType getSendResultType() const;
333
334 /// Determine the type of an expression that sends a message to this
335 /// function with the given receiver type.
336 QualType getSendResultType(QualType receiverType) const;
337
338 TypeSourceInfo *getReturnTypeSourceInfo() const { return ReturnTInfo; }
339 void setReturnTypeSourceInfo(TypeSourceInfo *TInfo) { ReturnTInfo = TInfo; }
340
341 // Iterator access to formal parameters.
342 unsigned param_size() const { return NumParams; }
343
344 using param_const_iterator = const ParmVarDecl *const *;
345 using param_iterator = ParmVarDecl *const *;
346 using param_range = llvm::iterator_range<param_iterator>;
347 using param_const_range = llvm::iterator_range<param_const_iterator>;
348
349 param_const_iterator param_begin() const {
350 return param_const_iterator(getParams());
351 }
352
353 param_const_iterator param_end() const {
354 return param_const_iterator(getParams() + NumParams);
355 }
356
357 param_iterator param_begin() { return param_iterator(getParams()); }
358 param_iterator param_end() { return param_iterator(getParams() + NumParams); }
359
360 // This method returns and of the parameters which are part of the selector
361 // name mangling requirements.
362 param_const_iterator sel_param_end() const {
363 return param_begin() + getSelector().getNumArgs();
364 }
365
366 // ArrayRef access to formal parameters. This should eventually
367 // replace the iterator interface above.
368 ArrayRef<ParmVarDecl*> parameters() const {
369 return llvm::makeArrayRef(const_cast<ParmVarDecl**>(getParams()),
370 NumParams);
371 }
372
373 ParmVarDecl *getParamDecl(unsigned Idx) {
374 assert(Idx < NumParams && "Index out of bounds!")((Idx < NumParams && "Index out of bounds!") ? static_cast
<void> (0) : __assert_fail ("Idx < NumParams && \"Index out of bounds!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclObjC.h"
, 374, __PRETTY_FUNCTION__))
;
375 return getParams()[Idx];
376 }
377 const ParmVarDecl *getParamDecl(unsigned Idx) const {
378 return const_cast<ObjCMethodDecl *>(this)->getParamDecl(Idx);
379 }
380
381 /// Sets the method's parameters and selector source locations.
382 /// If the method is implicit (not coming from source) \p SelLocs is
383 /// ignored.
384 void setMethodParams(ASTContext &C,
385 ArrayRef<ParmVarDecl*> Params,
386 ArrayRef<SourceLocation> SelLocs = llvm::None);
387
388 // Iterator access to parameter types.
389 struct GetTypeFn {
390 QualType operator()(const ParmVarDecl *PD) const { return PD->getType(); }
391 };
392
393 using param_type_iterator =
394 llvm::mapped_iterator<param_const_iterator, GetTypeFn>;
395
396 param_type_iterator param_type_begin() const {
397 return llvm::map_iterator(param_begin(), GetTypeFn());
398 }
399
400 param_type_iterator param_type_end() const {
401 return llvm::map_iterator(param_end(), GetTypeFn());
402 }
403
404 /// createImplicitParams - Used to lazily create the self and cmd
405 /// implicit parameters. This must be called prior to using getSelfDecl()
406 /// or getCmdDecl(). The call is ignored if the implicit parameters
407 /// have already been created.
408 void createImplicitParams(ASTContext &Context, const ObjCInterfaceDecl *ID);
409
410 /// \return the type for \c self and set \arg selfIsPseudoStrong and
411 /// \arg selfIsConsumed accordingly.
412 QualType getSelfType(ASTContext &Context, const ObjCInterfaceDecl *OID,
413 bool &selfIsPseudoStrong, bool &selfIsConsumed) const;
414
415 ImplicitParamDecl * getSelfDecl() const { return SelfDecl; }
416 void setSelfDecl(ImplicitParamDecl *SD) { SelfDecl = SD; }
417 ImplicitParamDecl * getCmdDecl() const { return CmdDecl; }
418 void setCmdDecl(ImplicitParamDecl *CD) { CmdDecl = CD; }
419
420 /// Determines the family of this method.
421 ObjCMethodFamily getMethodFamily() const;
422
423 bool isInstanceMethod() const { return ObjCMethodDeclBits.IsInstance; }
424 void setInstanceMethod(bool isInst) {
425 ObjCMethodDeclBits.IsInstance = isInst;
426 }
427
428 bool isVariadic() const { return ObjCMethodDeclBits.IsVariadic; }
429 void setVariadic(bool isVar) { ObjCMethodDeclBits.IsVariadic = isVar; }
430
431 bool isClassMethod() const { return !isInstanceMethod(); }
432
433 bool isPropertyAccessor() const {
434 return ObjCMethodDeclBits.IsPropertyAccessor;
435 }
436
437 void setPropertyAccessor(bool isAccessor) {
438 ObjCMethodDeclBits.IsPropertyAccessor = isAccessor;
439 }
440
441 bool isSynthesizedAccessorStub() const {
442 return ObjCMethodDeclBits.IsSynthesizedAccessorStub;
443 }
444
445 void setSynthesizedAccessorStub(bool isSynthesizedAccessorStub) {
446 ObjCMethodDeclBits.IsSynthesizedAccessorStub = isSynthesizedAccessorStub;
447 }
448
449 bool isDefined() const { return ObjCMethodDeclBits.IsDefined; }
450 void setDefined(bool isDefined) { ObjCMethodDeclBits.IsDefined = isDefined; }
451
452 /// Whether this method overrides any other in the class hierarchy.
453 ///
454 /// A method is said to override any method in the class's
455 /// base classes, its protocols, or its categories' protocols, that has
456 /// the same selector and is of the same kind (class or instance).
457 /// A method in an implementation is not considered as overriding the same
458 /// method in the interface or its categories.
459 bool isOverriding() const { return ObjCMethodDeclBits.IsOverriding; }
460 void setOverriding(bool IsOver) { ObjCMethodDeclBits.IsOverriding = IsOver; }
461
462 /// Return overridden methods for the given \p Method.
463 ///
464 /// An ObjC method is considered to override any method in the class's
465 /// base classes (and base's categories), its protocols, or its categories'
466 /// protocols, that has
467 /// the same selector and is of the same kind (class or instance).
468 /// A method in an implementation is not considered as overriding the same
469 /// method in the interface or its categories.
470 void getOverriddenMethods(
471 SmallVectorImpl<const ObjCMethodDecl *> &Overridden) const;
472
473 /// True if the method was a definition but its body was skipped.
474 bool hasSkippedBody() const { return ObjCMethodDeclBits.HasSkippedBody; }
475 void setHasSkippedBody(bool Skipped = true) {
476 ObjCMethodDeclBits.HasSkippedBody = Skipped;
477 }
478
479 /// True if the method is tagged as objc_direct
480 bool isDirectMethod() const;
481
482 /// Returns the property associated with this method's selector.
483 ///
484 /// Note that even if this particular method is not marked as a property
485 /// accessor, it is still possible for it to match a property declared in a
486 /// superclass. Pass \c false if you only want to check the current class.
487 const ObjCPropertyDecl *findPropertyDecl(bool CheckOverrides = true) const;
488
489 // Related to protocols declared in \@protocol
490 void setDeclImplementation(ImplementationControl ic) {
491 ObjCMethodDeclBits.DeclImplementation = ic;
492 }
493
494 ImplementationControl getImplementationControl() const {
495 return ImplementationControl(ObjCMethodDeclBits.DeclImplementation);
496 }
497
498 bool isOptional() const {
499 return getImplementationControl() == Optional;
500 }
501
502 /// Returns true if this specific method declaration is marked with the
503 /// designated initializer attribute.
504 bool isThisDeclarationADesignatedInitializer() const;
505
506 /// Returns true if the method selector resolves to a designated initializer
507 /// in the class's interface.
508 ///
509 /// \param InitMethod if non-null and the function returns true, it receives
510 /// the method declaration that was marked with the designated initializer
511 /// attribute.
512 bool isDesignatedInitializerForTheInterface(
513 const ObjCMethodDecl **InitMethod = nullptr) const;
514
515 /// Determine whether this method has a body.
516 bool hasBody() const override { return Body.isValid(); }
517
518 /// Retrieve the body of this method, if it has one.
519 Stmt *getBody() const override;
520
521 void setLazyBody(uint64_t Offset) { Body = Offset; }
522
523 CompoundStmt *getCompoundBody() { return (CompoundStmt*)getBody(); }
524 void setBody(Stmt *B) { Body = B; }
525
526 /// Returns whether this specific method is a definition.
527 bool isThisDeclarationADefinition() const { return hasBody(); }
528
529 /// Is this method defined in the NSObject base class?
530 bool definedInNSObject(const ASTContext &) const;
531
532 // Implement isa/cast/dyncast/etc.
533 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
534 static bool classofKind(Kind K) { return K == ObjCMethod; }
535
536 static DeclContext *castToDeclContext(const ObjCMethodDecl *D) {
537 return static_cast<DeclContext *>(const_cast<ObjCMethodDecl*>(D));
538 }
539
540 static ObjCMethodDecl *castFromDeclContext(const DeclContext *DC) {
541 return static_cast<ObjCMethodDecl *>(const_cast<DeclContext*>(DC));
542 }
543};
544
545/// Describes the variance of a given generic parameter.
546enum class ObjCTypeParamVariance : uint8_t {
547 /// The parameter is invariant: must match exactly.
548 Invariant,
549
550 /// The parameter is covariant, e.g., X<T> is a subtype of X<U> when
551 /// the type parameter is covariant and T is a subtype of U.
552 Covariant,
553
554 /// The parameter is contravariant, e.g., X<T> is a subtype of X<U>
555 /// when the type parameter is covariant and U is a subtype of T.
556 Contravariant,
557};
558
559/// Represents the declaration of an Objective-C type parameter.
560///
561/// \code
562/// @interface NSDictionary<Key : id<NSCopying>, Value>
563/// @end
564/// \endcode
565///
566/// In the example above, both \c Key and \c Value are represented by
567/// \c ObjCTypeParamDecl. \c Key has an explicit bound of \c id<NSCopying>,
568/// while \c Value gets an implicit bound of \c id.
569///
570/// Objective-C type parameters are typedef-names in the grammar,
571class ObjCTypeParamDecl : public TypedefNameDecl {
572 /// Index of this type parameter in the type parameter list.
573 unsigned Index : 14;
574
575 /// The variance of the type parameter.
576 unsigned Variance : 2;
577
578 /// The location of the variance, if any.
579 SourceLocation VarianceLoc;
580
581 /// The location of the ':', which will be valid when the bound was
582 /// explicitly specified.
583 SourceLocation ColonLoc;
584
585 ObjCTypeParamDecl(ASTContext &ctx, DeclContext *dc,
586 ObjCTypeParamVariance variance, SourceLocation varianceLoc,
587 unsigned index,
588 SourceLocation nameLoc, IdentifierInfo *name,
589 SourceLocation colonLoc, TypeSourceInfo *boundInfo)
590 : TypedefNameDecl(ObjCTypeParam, ctx, dc, nameLoc, nameLoc, name,
591 boundInfo),
592 Index(index), Variance(static_cast<unsigned>(variance)),
593 VarianceLoc(varianceLoc), ColonLoc(colonLoc) {}
594
595 void anchor() override;
596
597public:
598 friend class ASTDeclReader;
599 friend class ASTDeclWriter;
600
601 static ObjCTypeParamDecl *Create(ASTContext &ctx, DeclContext *dc,
602 ObjCTypeParamVariance variance,
603 SourceLocation varianceLoc,
604 unsigned index,
605 SourceLocation nameLoc,
606 IdentifierInfo *name,
607 SourceLocation colonLoc,
608 TypeSourceInfo *boundInfo);
609 static ObjCTypeParamDecl *CreateDeserialized(ASTContext &ctx, unsigned ID);
610
611 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
612
613 /// Determine the variance of this type parameter.
614 ObjCTypeParamVariance getVariance() const {
615 return static_cast<ObjCTypeParamVariance>(Variance);
616 }
617
618 /// Set the variance of this type parameter.
619 void setVariance(ObjCTypeParamVariance variance) {
620 Variance = static_cast<unsigned>(variance);
621 }
622
623 /// Retrieve the location of the variance keyword.
624 SourceLocation getVarianceLoc() const { return VarianceLoc; }
625
626 /// Retrieve the index into its type parameter list.
627 unsigned getIndex() const { return Index; }
628
629 /// Whether this type parameter has an explicitly-written type bound, e.g.,
630 /// "T : NSView".
631 bool hasExplicitBound() const { return ColonLoc.isValid(); }
632
633 /// Retrieve the location of the ':' separating the type parameter name
634 /// from the explicitly-specified bound.
635 SourceLocation getColonLoc() const { return ColonLoc; }
636
637 // Implement isa/cast/dyncast/etc.
638 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
639 static bool classofKind(Kind K) { return K == ObjCTypeParam; }
640};
641
642/// Stores a list of Objective-C type parameters for a parameterized class
643/// or a category/extension thereof.
644///
645/// \code
646/// @interface NSArray<T> // stores the <T>
647/// @end
648/// \endcode
649class ObjCTypeParamList final
650 : private llvm::TrailingObjects<ObjCTypeParamList, ObjCTypeParamDecl *> {
651 /// Stores the components of a SourceRange as a POD.
652 struct PODSourceRange {
653 unsigned Begin;
654 unsigned End;
655 };
656
657 union {
658 /// Location of the left and right angle brackets.
659 PODSourceRange Brackets;
660
661 // Used only for alignment.
662 ObjCTypeParamDecl *AlignmentHack;
663 };
664
665 /// The number of parameters in the list, which are tail-allocated.
666 unsigned NumParams;
667
668 ObjCTypeParamList(SourceLocation lAngleLoc,
669 ArrayRef<ObjCTypeParamDecl *> typeParams,
670 SourceLocation rAngleLoc);
671
672public:
673 friend TrailingObjects;
674
675 /// Create a new Objective-C type parameter list.
676 static ObjCTypeParamList *create(ASTContext &ctx,
677 SourceLocation lAngleLoc,
678 ArrayRef<ObjCTypeParamDecl *> typeParams,
679 SourceLocation rAngleLoc);
680
681 /// Iterate through the type parameters in the list.
682 using iterator = ObjCTypeParamDecl **;
683
684 iterator begin() { return getTrailingObjects<ObjCTypeParamDecl *>(); }
685
686 iterator end() { return begin() + size(); }
687
688 /// Determine the number of type parameters in this list.
689 unsigned size() const { return NumParams; }
690
691 // Iterate through the type parameters in the list.
692 using const_iterator = ObjCTypeParamDecl * const *;
693
694 const_iterator begin() const {
695 return getTrailingObjects<ObjCTypeParamDecl *>();
696 }
697
698 const_iterator end() const {
699 return begin() + size();
700 }
701
702 ObjCTypeParamDecl *front() const {
703 assert(size() > 0 && "empty Objective-C type parameter list")((size() > 0 && "empty Objective-C type parameter list"
) ? static_cast<void> (0) : __assert_fail ("size() > 0 && \"empty Objective-C type parameter list\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclObjC.h"
, 703, __PRETTY_FUNCTION__))
;
704 return *begin();
705 }
706
707 ObjCTypeParamDecl *back() const {
708 assert(size() > 0 && "empty Objective-C type parameter list")((size() > 0 && "empty Objective-C type parameter list"
) ? static_cast<void> (0) : __assert_fail ("size() > 0 && \"empty Objective-C type parameter list\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclObjC.h"
, 708, __PRETTY_FUNCTION__))
;
709 return *(end() - 1);
710 }
711
712 SourceLocation getLAngleLoc() const {
713 return SourceLocation::getFromRawEncoding(Brackets.Begin);
714 }
715
716 SourceLocation getRAngleLoc() const {
717 return SourceLocation::getFromRawEncoding(Brackets.End);
718 }
719
720 SourceRange getSourceRange() const {
721 return SourceRange(getLAngleLoc(), getRAngleLoc());
722 }
723
724 /// Gather the default set of type arguments to be substituted for
725 /// these type parameters when dealing with an unspecialized type.
726 void gatherDefaultTypeArgs(SmallVectorImpl<QualType> &typeArgs) const;
727};
728
729enum class ObjCPropertyQueryKind : uint8_t {
730 OBJC_PR_query_unknown = 0x00,
731 OBJC_PR_query_instance,
732 OBJC_PR_query_class
733};
734
735/// Represents one property declaration in an Objective-C interface.
736///
737/// For example:
738/// \code{.mm}
739/// \@property (assign, readwrite) int MyProperty;
740/// \endcode
741class ObjCPropertyDecl : public NamedDecl {
742 void anchor() override;
743
744public:
745 enum PropertyAttributeKind {
746 OBJC_PR_noattr = 0x00,
747 OBJC_PR_readonly = 0x01,
748 OBJC_PR_getter = 0x02,
749 OBJC_PR_assign = 0x04,
750 OBJC_PR_readwrite = 0x08,
751 OBJC_PR_retain = 0x10,
752 OBJC_PR_copy = 0x20,
753 OBJC_PR_nonatomic = 0x40,
754 OBJC_PR_setter = 0x80,
755 OBJC_PR_atomic = 0x100,
756 OBJC_PR_weak = 0x200,
757 OBJC_PR_strong = 0x400,
758 OBJC_PR_unsafe_unretained = 0x800,
759 /// Indicates that the nullability of the type was spelled with a
760 /// property attribute rather than a type qualifier.
761 OBJC_PR_nullability = 0x1000,
762 OBJC_PR_null_resettable = 0x2000,
763 OBJC_PR_class = 0x4000,
764 OBJC_PR_direct = 0x8000
765 // Adding a property should change NumPropertyAttrsBits
766 };
767
768 enum {
769 /// Number of bits fitting all the property attributes.
770 NumPropertyAttrsBits = 16
771 };
772
773 enum SetterKind { Assign, Retain, Copy, Weak };
774 enum PropertyControl { None, Required, Optional };
775
776private:
777 // location of \@property
778 SourceLocation AtLoc;
779
780 // location of '(' starting attribute list or null.
781 SourceLocation LParenLoc;
782
783 QualType DeclType;
784 TypeSourceInfo *DeclTypeSourceInfo;
785 unsigned PropertyAttributes : NumPropertyAttrsBits;
786 unsigned PropertyAttributesAsWritten : NumPropertyAttrsBits;
787
788 // \@required/\@optional
789 unsigned PropertyImplementation : 2;
790
791 // getter name of NULL if no getter
792 Selector GetterName;
793
794 // setter name of NULL if no setter
795 Selector SetterName;
796
797 // location of the getter attribute's value
798 SourceLocation GetterNameLoc;
799
800 // location of the setter attribute's value
801 SourceLocation SetterNameLoc;
802
803 // Declaration of getter instance method
804 ObjCMethodDecl *GetterMethodDecl = nullptr;
805
806 // Declaration of setter instance method
807 ObjCMethodDecl *SetterMethodDecl = nullptr;
808
809 // Synthesize ivar for this property
810 ObjCIvarDecl *PropertyIvarDecl = nullptr;
811
812 ObjCPropertyDecl(DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
813 SourceLocation AtLocation, SourceLocation LParenLocation,
814 QualType T, TypeSourceInfo *TSI,
815 PropertyControl propControl)
816 : NamedDecl(ObjCProperty, DC, L, Id), AtLoc(AtLocation),
817 LParenLoc(LParenLocation), DeclType(T), DeclTypeSourceInfo(TSI),
818 PropertyAttributes(OBJC_PR_noattr),
819 PropertyAttributesAsWritten(OBJC_PR_noattr),
820 PropertyImplementation(propControl), GetterName(Selector()),
821 SetterName(Selector()) {}
822
823public:
824 static ObjCPropertyDecl *Create(ASTContext &C, DeclContext *DC,
825 SourceLocation L,
826 IdentifierInfo *Id, SourceLocation AtLocation,
827 SourceLocation LParenLocation,
828 QualType T,
829 TypeSourceInfo *TSI,
830 PropertyControl propControl = None);
831
832 static ObjCPropertyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
833
834 SourceLocation getAtLoc() const { return AtLoc; }
835 void setAtLoc(SourceLocation L) { AtLoc = L; }
836
837 SourceLocation getLParenLoc() const { return LParenLoc; }
838 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
839
840 TypeSourceInfo *getTypeSourceInfo() const { return DeclTypeSourceInfo; }
841
842 QualType getType() const { return DeclType; }
843
844 void setType(QualType T, TypeSourceInfo *TSI) {
845 DeclType = T;
846 DeclTypeSourceInfo = TSI;
847 }
848
849 /// Retrieve the type when this property is used with a specific base object
850 /// type.
851 QualType getUsageType(QualType objectType) const;
852
853 PropertyAttributeKind getPropertyAttributes() const {
854 return PropertyAttributeKind(PropertyAttributes);
855 }
856
857 void setPropertyAttributes(PropertyAttributeKind PRVal) {
858 PropertyAttributes |= PRVal;
859 }
860
861 void overwritePropertyAttributes(unsigned PRVal) {
862 PropertyAttributes = PRVal;
863 }
864
865 PropertyAttributeKind getPropertyAttributesAsWritten() const {
866 return PropertyAttributeKind(PropertyAttributesAsWritten);
867 }
868
869 void setPropertyAttributesAsWritten(PropertyAttributeKind PRVal) {
870 PropertyAttributesAsWritten = PRVal;
871 }
872
873 // Helper methods for accessing attributes.
874
875 /// isReadOnly - Return true iff the property has a setter.
876 bool isReadOnly() const {
877 return (PropertyAttributes & OBJC_PR_readonly);
878 }
879
880 /// isAtomic - Return true if the property is atomic.
881 bool isAtomic() const {
882 return (PropertyAttributes & OBJC_PR_atomic);
883 }
884
885 /// isRetaining - Return true if the property retains its value.
886 bool isRetaining() const {
887 return (PropertyAttributes &
888 (OBJC_PR_retain | OBJC_PR_strong | OBJC_PR_copy));
889 }
890
891 bool isInstanceProperty() const { return !isClassProperty(); }
892 bool isClassProperty() const { return PropertyAttributes & OBJC_PR_class; }
893 bool isDirectProperty() const { return PropertyAttributes & OBJC_PR_direct; }
894
895 ObjCPropertyQueryKind getQueryKind() const {
896 return isClassProperty() ? ObjCPropertyQueryKind::OBJC_PR_query_class :
897 ObjCPropertyQueryKind::OBJC_PR_query_instance;
898 }
899
900 static ObjCPropertyQueryKind getQueryKind(bool isClassProperty) {
901 return isClassProperty ? ObjCPropertyQueryKind::OBJC_PR_query_class :
902 ObjCPropertyQueryKind::OBJC_PR_query_instance;
903 }
904
905 /// getSetterKind - Return the method used for doing assignment in
906 /// the property setter. This is only valid if the property has been
907 /// defined to have a setter.
908 SetterKind getSetterKind() const {
909 if (PropertyAttributes & OBJC_PR_strong)
910 return getType()->isBlockPointerType() ? Copy : Retain;
911 if (PropertyAttributes & OBJC_PR_retain)
912 return Retain;
913 if (PropertyAttributes & OBJC_PR_copy)
914 return Copy;
915 if (PropertyAttributes & OBJC_PR_weak)
916 return Weak;
917 return Assign;
918 }
919
920 Selector getGetterName() const { return GetterName; }
921 SourceLocation getGetterNameLoc() const { return GetterNameLoc; }
922
923 void setGetterName(Selector Sel, SourceLocation Loc = SourceLocation()) {
924 GetterName = Sel;
925 GetterNameLoc = Loc;
926 }
927
928 Selector getSetterName() const { return SetterName; }
929 SourceLocation getSetterNameLoc() const { return SetterNameLoc; }
930
931 void setSetterName(Selector Sel, SourceLocation Loc = SourceLocation()) {
932 SetterName = Sel;
933 SetterNameLoc = Loc;
934 }
935
936 ObjCMethodDecl *getGetterMethodDecl() const { return GetterMethodDecl; }
937 void setGetterMethodDecl(ObjCMethodDecl *gDecl) { GetterMethodDecl = gDecl; }
938
939 ObjCMethodDecl *getSetterMethodDecl() const { return SetterMethodDecl; }
940 void setSetterMethodDecl(ObjCMethodDecl *gDecl) { SetterMethodDecl = gDecl; }
941
942 // Related to \@optional/\@required declared in \@protocol
943 void setPropertyImplementation(PropertyControl pc) {
944 PropertyImplementation = pc;
945 }
946
947 PropertyControl getPropertyImplementation() const {
948 return PropertyControl(PropertyImplementation);
949 }
950
951 bool isOptional() const {
952 return getPropertyImplementation() == PropertyControl::Optional;
953 }
954
955 void setPropertyIvarDecl(ObjCIvarDecl *Ivar) {
956 PropertyIvarDecl = Ivar;
957 }
958
959 ObjCIvarDecl *getPropertyIvarDecl() const {
960 return PropertyIvarDecl;
961 }
962
963 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
964 return SourceRange(AtLoc, getLocation());
965 }
966
967 /// Get the default name of the synthesized ivar.
968 IdentifierInfo *getDefaultSynthIvarName(ASTContext &Ctx) const;
969
970 /// Lookup a property by name in the specified DeclContext.
971 static ObjCPropertyDecl *findPropertyDecl(const DeclContext *DC,
972 const IdentifierInfo *propertyID,
973 ObjCPropertyQueryKind queryKind);
974
975 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
976 static bool classofKind(Kind K) { return K == ObjCProperty; }
977};
978
979/// ObjCContainerDecl - Represents a container for method declarations.
980/// Current sub-classes are ObjCInterfaceDecl, ObjCCategoryDecl,
981/// ObjCProtocolDecl, and ObjCImplDecl.
982///
983class ObjCContainerDecl : public NamedDecl, public DeclContext {
984 // This class stores some data in DeclContext::ObjCContainerDeclBits
985 // to save some space. Use the provided accessors to access it.
986
987 // These two locations in the range mark the end of the method container.
988 // The first points to the '@' token, and the second to the 'end' token.
989 SourceRange AtEnd;
990
991 void anchor() override;
992
993public:
994 ObjCContainerDecl(Kind DK, DeclContext *DC, IdentifierInfo *Id,
995 SourceLocation nameLoc, SourceLocation atStartLoc);
996
997 // Iterator access to instance/class properties.
998 using prop_iterator = specific_decl_iterator<ObjCPropertyDecl>;
999 using prop_range =
1000 llvm::iterator_range<specific_decl_iterator<ObjCPropertyDecl>>;
1001
1002 prop_range properties() const { return prop_range(prop_begin(), prop_end()); }
1003
1004 prop_iterator prop_begin() const {
1005 return prop_iterator(decls_begin());
1006 }
1007
1008 prop_iterator prop_end() const {
1009 return prop_iterator(decls_end());
1010 }
1011
1012 using instprop_iterator =
1013 filtered_decl_iterator<ObjCPropertyDecl,
1014 &ObjCPropertyDecl::isInstanceProperty>;
1015 using instprop_range = llvm::iterator_range<instprop_iterator>;
1016
1017 instprop_range instance_properties() const {
1018 return instprop_range(instprop_begin(), instprop_end());
1019 }
1020
1021 instprop_iterator instprop_begin() const {
1022 return instprop_iterator(decls_begin());
1023 }
1024
1025 instprop_iterator instprop_end() const {
1026 return instprop_iterator(decls_end());
1027 }
1028
1029 using classprop_iterator =
1030 filtered_decl_iterator<ObjCPropertyDecl,
1031 &ObjCPropertyDecl::isClassProperty>;
1032 using classprop_range = llvm::iterator_range<classprop_iterator>;
1033
1034 classprop_range class_properties() const {
1035 return classprop_range(classprop_begin(), classprop_end());
1036 }
1037
1038 classprop_iterator classprop_begin() const {
1039 return classprop_iterator(decls_begin());
1040 }
1041
1042 classprop_iterator classprop_end() const {
1043 return classprop_iterator(decls_end());
1044 }
1045
1046 // Iterator access to instance/class methods.
1047 using method_iterator = specific_decl_iterator<ObjCMethodDecl>;
1048 using method_range =
1049 llvm::iterator_range<specific_decl_iterator<ObjCMethodDecl>>;
1050
1051 method_range methods() const {
1052 return method_range(meth_begin(), meth_end());
1053 }
1054
1055 method_iterator meth_begin() const {
1056 return method_iterator(decls_begin());
1057 }
1058
1059 method_iterator meth_end() const {
1060 return method_iterator(decls_end());
1061 }
1062
1063 using instmeth_iterator =
1064 filtered_decl_iterator<ObjCMethodDecl,
1065 &ObjCMethodDecl::isInstanceMethod>;
1066 using instmeth_range = llvm::iterator_range<instmeth_iterator>;
1067
1068 instmeth_range instance_methods() const {
1069 return instmeth_range(instmeth_begin(), instmeth_end());
1070 }
1071
1072 instmeth_iterator instmeth_begin() const {
1073 return instmeth_iterator(decls_begin());
1074 }
1075
1076 instmeth_iterator instmeth_end() const {
1077 return instmeth_iterator(decls_end());
1078 }
1079
1080 using classmeth_iterator =
1081 filtered_decl_iterator<ObjCMethodDecl,
1082 &ObjCMethodDecl::isClassMethod>;
1083 using classmeth_range = llvm::iterator_range<classmeth_iterator>;
1084
1085 classmeth_range class_methods() const {
1086 return classmeth_range(classmeth_begin(), classmeth_end());
1087 }
1088
1089 classmeth_iterator classmeth_begin() const {
1090 return classmeth_iterator(decls_begin());
1091 }
1092
1093 classmeth_iterator classmeth_end() const {
1094 return classmeth_iterator(decls_end());
1095 }
1096
1097 // Get the local instance/class method declared in this interface.
1098 ObjCMethodDecl *getMethod(Selector Sel, bool isInstance,
1099 bool AllowHidden = false) const;
1100
1101 ObjCMethodDecl *getInstanceMethod(Selector Sel,
1102 bool AllowHidden = false) const {
1103 return getMethod(Sel, true/*isInstance*/, AllowHidden);
1104 }
1105
1106 ObjCMethodDecl *getClassMethod(Selector Sel, bool AllowHidden = false) const {
1107 return getMethod(Sel, false/*isInstance*/, AllowHidden);
1108 }
1109
1110 bool HasUserDeclaredSetterMethod(const ObjCPropertyDecl *P) const;
1111 ObjCIvarDecl *getIvarDecl(IdentifierInfo *Id) const;
1112
1113 ObjCPropertyDecl *
1114 FindPropertyDeclaration(const IdentifierInfo *PropertyId,
1115 ObjCPropertyQueryKind QueryKind) const;
1116
1117 using PropertyMap =
1118 llvm::DenseMap<std::pair<IdentifierInfo *, unsigned/*isClassProperty*/>,
1119 ObjCPropertyDecl *>;
1120 using ProtocolPropertySet = llvm::SmallDenseSet<const ObjCProtocolDecl *, 8>;
1121 using PropertyDeclOrder = llvm::SmallVector<ObjCPropertyDecl *, 8>;
1122
1123 /// This routine collects list of properties to be implemented in the class.
1124 /// This includes, class's and its conforming protocols' properties.
1125 /// Note, the superclass's properties are not included in the list.
1126 virtual void collectPropertiesToImplement(PropertyMap &PM,
1127 PropertyDeclOrder &PO) const {}
1128
1129 SourceLocation getAtStartLoc() const { return ObjCContainerDeclBits.AtStart; }
1130
1131 void setAtStartLoc(SourceLocation Loc) {
1132 ObjCContainerDeclBits.AtStart = Loc;
1133 }
1134
1135 // Marks the end of the container.
1136 SourceRange getAtEndRange() const { return AtEnd; }
1137
1138 void setAtEndRange(SourceRange atEnd) { AtEnd = atEnd; }
1139
1140 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
1141 return SourceRange(getAtStartLoc(), getAtEndRange().getEnd());
1142 }
1143
1144 // Implement isa/cast/dyncast/etc.
1145 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1146
1147 static bool classofKind(Kind K) {
1148 return K >= firstObjCContainer &&
1149 K <= lastObjCContainer;
1150 }
1151
1152 static DeclContext *castToDeclContext(const ObjCContainerDecl *D) {
1153 return static_cast<DeclContext *>(const_cast<ObjCContainerDecl*>(D));
1154 }
1155
1156 static ObjCContainerDecl *castFromDeclContext(const DeclContext *DC) {
1157 return static_cast<ObjCContainerDecl *>(const_cast<DeclContext*>(DC));
1158 }
1159};
1160
1161/// Represents an ObjC class declaration.
1162///
1163/// For example:
1164///
1165/// \code
1166/// // MostPrimitive declares no super class (not particularly useful).
1167/// \@interface MostPrimitive
1168/// // no instance variables or methods.
1169/// \@end
1170///
1171/// // NSResponder inherits from NSObject & implements NSCoding (a protocol).
1172/// \@interface NSResponder : NSObject \<NSCoding>
1173/// { // instance variables are represented by ObjCIvarDecl.
1174/// id nextResponder; // nextResponder instance variable.
1175/// }
1176/// - (NSResponder *)nextResponder; // return a pointer to NSResponder.
1177/// - (void)mouseMoved:(NSEvent *)theEvent; // return void, takes a pointer
1178/// \@end // to an NSEvent.
1179/// \endcode
1180///
1181/// Unlike C/C++, forward class declarations are accomplished with \@class.
1182/// Unlike C/C++, \@class allows for a list of classes to be forward declared.
1183/// Unlike C++, ObjC is a single-rooted class model. In Cocoa, classes
1184/// typically inherit from NSObject (an exception is NSProxy).
1185///
1186class ObjCInterfaceDecl : public ObjCContainerDecl
1187 , public Redeclarable<ObjCInterfaceDecl> {
1188 friend class ASTContext;
1189
1190 /// TypeForDecl - This indicates the Type object that represents this
1191 /// TypeDecl. It is a cache maintained by ASTContext::getObjCInterfaceType
1192 mutable const Type *TypeForDecl = nullptr;
1193
1194 struct DefinitionData {
1195 /// The definition of this class, for quick access from any
1196 /// declaration.
1197 ObjCInterfaceDecl *Definition = nullptr;
1198
1199 /// When non-null, this is always an ObjCObjectType.
1200 TypeSourceInfo *SuperClassTInfo = nullptr;
1201
1202 /// Protocols referenced in the \@interface declaration
1203 ObjCProtocolList ReferencedProtocols;
1204
1205 /// Protocols reference in both the \@interface and class extensions.
1206 ObjCList<ObjCProtocolDecl> AllReferencedProtocols;
1207
1208 /// List of categories and class extensions defined for this class.
1209 ///
1210 /// Categories are stored as a linked list in the AST, since the categories
1211 /// and class extensions come long after the initial interface declaration,
1212 /// and we avoid dynamically-resized arrays in the AST wherever possible.
1213 ObjCCategoryDecl *CategoryList = nullptr;
1214
1215 /// IvarList - List of all ivars defined by this class; including class
1216 /// extensions and implementation. This list is built lazily.
1217 ObjCIvarDecl *IvarList = nullptr;
1218
1219 /// Indicates that the contents of this Objective-C class will be
1220 /// completed by the external AST source when required.
1221 mutable unsigned ExternallyCompleted : 1;
1222
1223 /// Indicates that the ivar cache does not yet include ivars
1224 /// declared in the implementation.
1225 mutable unsigned IvarListMissingImplementation : 1;
1226
1227 /// Indicates that this interface decl contains at least one initializer
1228 /// marked with the 'objc_designated_initializer' attribute.
1229 unsigned HasDesignatedInitializers : 1;
1230
1231 enum InheritedDesignatedInitializersState {
1232 /// We didn't calculate whether the designated initializers should be
1233 /// inherited or not.
1234 IDI_Unknown = 0,
1235
1236 /// Designated initializers are inherited for the super class.
1237 IDI_Inherited = 1,
1238
1239 /// The class does not inherit designated initializers.
1240 IDI_NotInherited = 2
1241 };
1242
1243 /// One of the \c InheritedDesignatedInitializersState enumeratos.
1244 mutable unsigned InheritedDesignatedInitializers : 2;
1245
1246 /// The location of the last location in this declaration, before
1247 /// the properties/methods. For example, this will be the '>', '}', or
1248 /// identifier,
1249 SourceLocation EndLoc;
1250
1251 DefinitionData()
1252 : ExternallyCompleted(false), IvarListMissingImplementation(true),
1253 HasDesignatedInitializers(false),
1254 InheritedDesignatedInitializers(IDI_Unknown) {}
1255 };
1256
1257 /// The type parameters associated with this class, if any.
1258 ObjCTypeParamList *TypeParamList = nullptr;
1259
1260 /// Contains a pointer to the data associated with this class,
1261 /// which will be NULL if this class has not yet been defined.
1262 ///
1263 /// The bit indicates when we don't need to check for out-of-date
1264 /// declarations. It will be set unless modules are enabled.
1265 llvm::PointerIntPair<DefinitionData *, 1, bool> Data;
1266
1267 ObjCInterfaceDecl(const ASTContext &C, DeclContext *DC, SourceLocation AtLoc,
1268 IdentifierInfo *Id, ObjCTypeParamList *typeParamList,
1269 SourceLocation CLoc, ObjCInterfaceDecl *PrevDecl,
1270 bool IsInternal);
1271
1272 void anchor() override;
1273
1274 void LoadExternalDefinition() const;
1275
1276 DefinitionData &data() const {
1277 assert(Data.getPointer() && "Declaration has no definition!")((Data.getPointer() && "Declaration has no definition!"
) ? static_cast<void> (0) : __assert_fail ("Data.getPointer() && \"Declaration has no definition!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclObjC.h"
, 1277, __PRETTY_FUNCTION__))
;
1278 return *Data.getPointer();
1279 }
1280
1281 /// Allocate the definition data for this class.
1282 void allocateDefinitionData();
1283
1284 using redeclarable_base = Redeclarable<ObjCInterfaceDecl>;
1285
1286 ObjCInterfaceDecl *getNextRedeclarationImpl() override {
1287 return getNextRedeclaration();
1288 }
1289
1290 ObjCInterfaceDecl *getPreviousDeclImpl() override {
1291 return getPreviousDecl();
1292 }
1293
1294 ObjCInterfaceDecl *getMostRecentDeclImpl() override {
1295 return getMostRecentDecl();
1296 }
1297
1298public:
1299 static ObjCInterfaceDecl *Create(const ASTContext &C, DeclContext *DC,
1300 SourceLocation atLoc,
1301 IdentifierInfo *Id,
1302 ObjCTypeParamList *typeParamList,
1303 ObjCInterfaceDecl *PrevDecl,
1304 SourceLocation ClassLoc = SourceLocation(),
1305 bool isInternal = false);
1306
1307 static ObjCInterfaceDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
1308
1309 /// Retrieve the type parameters of this class.
1310 ///
1311 /// This function looks for a type parameter list for the given
1312 /// class; if the class has been declared (with \c \@class) but not
1313 /// defined (with \c \@interface), it will search for a declaration that
1314 /// has type parameters, skipping any declarations that do not.
1315 ObjCTypeParamList *getTypeParamList() const;
1316
1317 /// Set the type parameters of this class.
1318 ///
1319 /// This function is used by the AST importer, which must import the type
1320 /// parameters after creating their DeclContext to avoid loops.
1321 void setTypeParamList(ObjCTypeParamList *TPL);
1322
1323 /// Retrieve the type parameters written on this particular declaration of
1324 /// the class.
1325 ObjCTypeParamList *getTypeParamListAsWritten() const {
1326 return TypeParamList;
1327 }
1328
1329 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
1330 if (isThisDeclarationADefinition())
1331 return ObjCContainerDecl::getSourceRange();
1332
1333 return SourceRange(getAtStartLoc(), getLocation());
1334 }
1335
1336 /// Indicate that this Objective-C class is complete, but that
1337 /// the external AST source will be responsible for filling in its contents
1338 /// when a complete class is required.
1339 void setExternallyCompleted();
1340
1341 /// Indicate that this interface decl contains at least one initializer
1342 /// marked with the 'objc_designated_initializer' attribute.
1343 void setHasDesignatedInitializers();
1344
1345 /// Returns true if this interface decl contains at least one initializer
1346 /// marked with the 'objc_designated_initializer' attribute.
1347 bool hasDesignatedInitializers() const;
1348
1349 /// Returns true if this interface decl declares a designated initializer
1350 /// or it inherites one from its super class.
1351 bool declaresOrInheritsDesignatedInitializers() const {
1352 return hasDesignatedInitializers() || inheritsDesignatedInitializers();
1353 }
1354
1355 const ObjCProtocolList &getReferencedProtocols() const {
1356 assert(hasDefinition() && "Caller did not check for forward reference!")((hasDefinition() && "Caller did not check for forward reference!"
) ? static_cast<void> (0) : __assert_fail ("hasDefinition() && \"Caller did not check for forward reference!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclObjC.h"
, 1356, __PRETTY_FUNCTION__))
;
1357 if (data().ExternallyCompleted)
1358 LoadExternalDefinition();
1359
1360 return data().ReferencedProtocols;
1361 }
1362
1363 ObjCImplementationDecl *getImplementation() const;
1364 void setImplementation(ObjCImplementationDecl *ImplD);
1365
1366 ObjCCategoryDecl *FindCategoryDeclaration(IdentifierInfo *CategoryId) const;
1367
1368 // Get the local instance/class method declared in a category.
1369 ObjCMethodDecl *getCategoryInstanceMethod(Selector Sel) const;
1370 ObjCMethodDecl *getCategoryClassMethod(Selector Sel) const;
1371
1372 ObjCMethodDecl *getCategoryMethod(Selector Sel, bool isInstance) const {
1373 return isInstance ? getCategoryInstanceMethod(Sel)
1374 : getCategoryClassMethod(Sel);
1375 }
1376
1377 using protocol_iterator = ObjCProtocolList::iterator;
1378 using protocol_range = llvm::iterator_range<protocol_iterator>;
1379
1380 protocol_range protocols() const {
1381 return protocol_range(protocol_begin(), protocol_end());
1382 }
1383
1384 protocol_iterator protocol_begin() const {
1385 // FIXME: Should make sure no callers ever do this.
1386 if (!hasDefinition())
1387 return protocol_iterator();
1388
1389 if (data().ExternallyCompleted)
1390 LoadExternalDefinition();
1391
1392 return data().ReferencedProtocols.begin();
1393 }
1394
1395 protocol_iterator protocol_end() const {
1396 // FIXME: Should make sure no callers ever do this.
1397 if (!hasDefinition())
1398 return protocol_iterator();
1399
1400 if (data().ExternallyCompleted)
1401 LoadExternalDefinition();
1402
1403 return data().ReferencedProtocols.end();
1404 }
1405
1406 using protocol_loc_iterator = ObjCProtocolList::loc_iterator;
1407 using protocol_loc_range = llvm::iterator_range<protocol_loc_iterator>;
1408
1409 protocol_loc_range protocol_locs() const {
1410 return protocol_loc_range(protocol_loc_begin(), protocol_loc_end());
1411 }
1412
1413 protocol_loc_iterator protocol_loc_begin() const {
1414 // FIXME: Should make sure no callers ever do this.
1415 if (!hasDefinition())
1416 return protocol_loc_iterator();
1417
1418 if (data().ExternallyCompleted)
1419 LoadExternalDefinition();
1420
1421 return data().ReferencedProtocols.loc_begin();
1422 }
1423
1424 protocol_loc_iterator protocol_loc_end() const {
1425 // FIXME: Should make sure no callers ever do this.
1426 if (!hasDefinition())
1427 return protocol_loc_iterator();
1428
1429 if (data().ExternallyCompleted)
1430 LoadExternalDefinition();
1431
1432 return data().ReferencedProtocols.loc_end();
1433 }
1434
1435 using all_protocol_iterator = ObjCList<ObjCProtocolDecl>::iterator;
1436 using all_protocol_range = llvm::iterator_range<all_protocol_iterator>;
1437
1438 all_protocol_range all_referenced_protocols() const {
1439 return all_protocol_range(all_referenced_protocol_begin(),
1440 all_referenced_protocol_end());
1441 }
1442
1443 all_protocol_iterator all_referenced_protocol_begin() const {
1444 // FIXME: Should make sure no callers ever do this.
1445 if (!hasDefinition())
1446 return all_protocol_iterator();
1447
1448 if (data().ExternallyCompleted)
1449 LoadExternalDefinition();
1450
1451 return data().AllReferencedProtocols.empty()
1452 ? protocol_begin()
1453 : data().AllReferencedProtocols.begin();
1454 }
1455
1456 all_protocol_iterator all_referenced_protocol_end() const {
1457 // FIXME: Should make sure no callers ever do this.
1458 if (!hasDefinition())
1459 return all_protocol_iterator();
1460
1461 if (data().ExternallyCompleted)
1462 LoadExternalDefinition();
1463
1464 return data().AllReferencedProtocols.empty()
1465 ? protocol_end()
1466 : data().AllReferencedProtocols.end();
1467 }
1468
1469 using ivar_iterator = specific_decl_iterator<ObjCIvarDecl>;
1470 using ivar_range = llvm::iterator_range<specific_decl_iterator<ObjCIvarDecl>>;
1471
1472 ivar_range ivars() const { return ivar_range(ivar_begin(), ivar_end()); }
1473
1474 ivar_iterator ivar_begin() const {
1475 if (const ObjCInterfaceDecl *Def = getDefinition())
1476 return ivar_iterator(Def->decls_begin());
1477
1478 // FIXME: Should make sure no callers ever do this.
1479 return ivar_iterator();
1480 }
1481
1482 ivar_iterator ivar_end() const {
1483 if (const ObjCInterfaceDecl *Def = getDefinition())
1484 return ivar_iterator(Def->decls_end());
1485
1486 // FIXME: Should make sure no callers ever do this.
1487 return ivar_iterator();
1488 }
1489
1490 unsigned ivar_size() const {
1491 return std::distance(ivar_begin(), ivar_end());
1492 }
1493
1494 bool ivar_empty() const { return ivar_begin() == ivar_end(); }
1495
1496 ObjCIvarDecl *all_declared_ivar_begin();
1497 const ObjCIvarDecl *all_declared_ivar_begin() const {
1498 // Even though this modifies IvarList, it's conceptually const:
1499 // the ivar chain is essentially a cached property of ObjCInterfaceDecl.
1500 return const_cast<ObjCInterfaceDecl *>(this)->all_declared_ivar_begin();
1501 }
1502 void setIvarList(ObjCIvarDecl *ivar) { data().IvarList = ivar; }
1503
1504 /// setProtocolList - Set the list of protocols that this interface
1505 /// implements.
1506 void setProtocolList(ObjCProtocolDecl *const* List, unsigned Num,
1507 const SourceLocation *Locs, ASTContext &C) {
1508 data().ReferencedProtocols.set(List, Num, Locs, C);
1509 }
1510
1511 /// mergeClassExtensionProtocolList - Merge class extension's protocol list
1512 /// into the protocol list for this class.
1513 void mergeClassExtensionProtocolList(ObjCProtocolDecl *const* List,
1514 unsigned Num,
1515 ASTContext &C);
1516
1517 /// Produce a name to be used for class's metadata. It comes either via
1518 /// objc_runtime_name attribute or class name.
1519 StringRef getObjCRuntimeNameAsString() const;
1520
1521 /// Returns the designated initializers for the interface.
1522 ///
1523 /// If this declaration does not have methods marked as designated
1524 /// initializers then the interface inherits the designated initializers of
1525 /// its super class.
1526 void getDesignatedInitializers(
1527 llvm::SmallVectorImpl<const ObjCMethodDecl *> &Methods) const;
1528
1529 /// Returns true if the given selector is a designated initializer for the
1530 /// interface.
1531 ///
1532 /// If this declaration does not have methods marked as designated
1533 /// initializers then the interface inherits the designated initializers of
1534 /// its super class.
1535 ///
1536 /// \param InitMethod if non-null and the function returns true, it receives
1537 /// the method that was marked as a designated initializer.
1538 bool
1539 isDesignatedInitializer(Selector Sel,
1540 const ObjCMethodDecl **InitMethod = nullptr) const;
1541
1542 /// Determine whether this particular declaration of this class is
1543 /// actually also a definition.
1544 bool isThisDeclarationADefinition() const {
1545 return getDefinition() == this;
1546 }
1547
1548 /// Determine whether this class has been defined.
1549 bool hasDefinition() const {
1550 // If the name of this class is out-of-date, bring it up-to-date, which
1551 // might bring in a definition.
1552 // Note: a null value indicates that we don't have a definition and that
1553 // modules are enabled.
1554 if (!Data.getOpaqueValue())
2
Assuming the condition is false
3
Taking false branch
1555 getMostRecentDecl();
1556
1557 return Data.getPointer();
4
Returning value, which participates in a condition later
1558 }
1559
1560 /// Retrieve the definition of this class, or NULL if this class
1561 /// has been forward-declared (with \@class) but not yet defined (with
1562 /// \@interface).
1563 ObjCInterfaceDecl *getDefinition() {
1564 return hasDefinition()? Data.getPointer()->Definition : nullptr;
1565 }
1566
1567 /// Retrieve the definition of this class, or NULL if this class
1568 /// has been forward-declared (with \@class) but not yet defined (with
1569 /// \@interface).
1570 const ObjCInterfaceDecl *getDefinition() const {
1571 return hasDefinition()? Data.getPointer()->Definition : nullptr;
15
Assuming the condition is true
16
'?' condition is true
17
Returning pointer, which participates in a condition later
1572 }
1573
1574 /// Starts the definition of this Objective-C class, taking it from
1575 /// a forward declaration (\@class) to a definition (\@interface).
1576 void startDefinition();
1577
1578 /// Retrieve the superclass type.
1579 const ObjCObjectType *getSuperClassType() const {
1580 if (TypeSourceInfo *TInfo = getSuperClassTInfo())
1581 return TInfo->getType()->castAs<ObjCObjectType>();
1582
1583 return nullptr;
1584 }
1585
1586 // Retrieve the type source information for the superclass.
1587 TypeSourceInfo *getSuperClassTInfo() const {
1588 // FIXME: Should make sure no callers ever do this.
1589 if (!hasDefinition())
1590 return nullptr;
1591
1592 if (data().ExternallyCompleted)
1593 LoadExternalDefinition();
1594
1595 return data().SuperClassTInfo;
1596 }
1597
1598 // Retrieve the declaration for the superclass of this class, which
1599 // does not include any type arguments that apply to the superclass.
1600 ObjCInterfaceDecl *getSuperClass() const;
1601
1602 void setSuperClass(TypeSourceInfo *superClass) {
1603 data().SuperClassTInfo = superClass;
1604 }
1605
1606 /// Iterator that walks over the list of categories, filtering out
1607 /// those that do not meet specific criteria.
1608 ///
1609 /// This class template is used for the various permutations of category
1610 /// and extension iterators.
1611 template<bool (*Filter)(ObjCCategoryDecl *)>
1612 class filtered_category_iterator {
1613 ObjCCategoryDecl *Current = nullptr;
1614
1615 void findAcceptableCategory();
1616
1617 public:
1618 using value_type = ObjCCategoryDecl *;
1619 using reference = value_type;
1620 using pointer = value_type;
1621 using difference_type = std::ptrdiff_t;
1622 using iterator_category = std::input_iterator_tag;
1623
1624 filtered_category_iterator() = default;
1625 explicit filtered_category_iterator(ObjCCategoryDecl *Current)
1626 : Current(Current) {
1627 findAcceptableCategory();
1628 }
1629
1630 reference operator*() const { return Current; }
1631 pointer operator->() const { return Current; }
1632
1633 filtered_category_iterator &operator++();
1634
1635 filtered_category_iterator operator++(int) {
1636 filtered_category_iterator Tmp = *this;
1637 ++(*this);
1638 return Tmp;
1639 }
1640
1641 friend bool operator==(filtered_category_iterator X,
1642 filtered_category_iterator Y) {
1643 return X.Current == Y.Current;
1644 }
1645
1646 friend bool operator!=(filtered_category_iterator X,
1647 filtered_category_iterator Y) {
1648 return X.Current != Y.Current;
1649 }
1650 };
1651
1652private:
1653 /// Test whether the given category is visible.
1654 ///
1655 /// Used in the \c visible_categories_iterator.
1656 static bool isVisibleCategory(ObjCCategoryDecl *Cat);
1657
1658public:
1659 /// Iterator that walks over the list of categories and extensions
1660 /// that are visible, i.e., not hidden in a non-imported submodule.
1661 using visible_categories_iterator =
1662 filtered_category_iterator<isVisibleCategory>;
1663
1664 using visible_categories_range =
1665 llvm::iterator_range<visible_categories_iterator>;
1666
1667 visible_categories_range visible_categories() const {
1668 return visible_categories_range(visible_categories_begin(),
1669 visible_categories_end());
1670 }
1671
1672 /// Retrieve an iterator to the beginning of the visible-categories
1673 /// list.
1674 visible_categories_iterator visible_categories_begin() const {
1675 return visible_categories_iterator(getCategoryListRaw());
1676 }
1677
1678 /// Retrieve an iterator to the end of the visible-categories list.
1679 visible_categories_iterator visible_categories_end() const {
1680 return visible_categories_iterator();
1681 }
1682
1683 /// Determine whether the visible-categories list is empty.
1684 bool visible_categories_empty() const {
1685 return visible_categories_begin() == visible_categories_end();
1686 }
1687
1688private:
1689 /// Test whether the given category... is a category.
1690 ///
1691 /// Used in the \c known_categories_iterator.
1692 static bool isKnownCategory(ObjCCategoryDecl *) { return true; }
1693
1694public:
1695 /// Iterator that walks over all of the known categories and
1696 /// extensions, including those that are hidden.
1697 using known_categories_iterator = filtered_category_iterator<isKnownCategory>;
1698 using known_categories_range =
1699 llvm::iterator_range<known_categories_iterator>;
1700
1701 known_categories_range known_categories() const {
1702 return known_categories_range(known_categories_begin(),
1703 known_categories_end());
1704 }
1705
1706 /// Retrieve an iterator to the beginning of the known-categories
1707 /// list.
1708 known_categories_iterator known_categories_begin() const {
1709 return known_categories_iterator(getCategoryListRaw());
1710 }
1711
1712 /// Retrieve an iterator to the end of the known-categories list.
1713 known_categories_iterator known_categories_end() const {
1714 return known_categories_iterator();
1715 }
1716
1717 /// Determine whether the known-categories list is empty.
1718 bool known_categories_empty() const {
1719 return known_categories_begin() == known_categories_end();
1720 }
1721
1722private:
1723 /// Test whether the given category is a visible extension.
1724 ///
1725 /// Used in the \c visible_extensions_iterator.
1726 static bool isVisibleExtension(ObjCCategoryDecl *Cat);
1727
1728public:
1729 /// Iterator that walks over all of the visible extensions, skipping
1730 /// any that are known but hidden.
1731 using visible_extensions_iterator =
1732 filtered_category_iterator<isVisibleExtension>;
1733
1734 using visible_extensions_range =
1735 llvm::iterator_range<visible_extensions_iterator>;
1736
1737 visible_extensions_range visible_extensions() const {
1738 return visible_extensions_range(visible_extensions_begin(),
1739 visible_extensions_end());
1740 }
1741
1742 /// Retrieve an iterator to the beginning of the visible-extensions
1743 /// list.
1744 visible_extensions_iterator visible_extensions_begin() const {
1745 return visible_extensions_iterator(getCategoryListRaw());
1746 }
1747
1748 /// Retrieve an iterator to the end of the visible-extensions list.
1749 visible_extensions_iterator visible_extensions_end() const {
1750 return visible_extensions_iterator();
1751 }
1752
1753 /// Determine whether the visible-extensions list is empty.
1754 bool visible_extensions_empty() const {
1755 return visible_extensions_begin() == visible_extensions_end();
1756 }
1757
1758private:
1759 /// Test whether the given category is an extension.
1760 ///
1761 /// Used in the \c known_extensions_iterator.
1762 static bool isKnownExtension(ObjCCategoryDecl *Cat);
1763
1764public:
1765 friend class ASTDeclReader;
1766 friend class ASTDeclWriter;
1767 friend class ASTReader;
1768
1769 /// Iterator that walks over all of the known extensions.
1770 using known_extensions_iterator =
1771 filtered_category_iterator<isKnownExtension>;
1772 using known_extensions_range =
1773 llvm::iterator_range<known_extensions_iterator>;
1774
1775 known_extensions_range known_extensions() const {
1776 return known_extensions_range(known_extensions_begin(),
1777 known_extensions_end());
1778 }
1779
1780 /// Retrieve an iterator to the beginning of the known-extensions
1781 /// list.
1782 known_extensions_iterator known_extensions_begin() const {
1783 return known_extensions_iterator(getCategoryListRaw());
1784 }
1785
1786 /// Retrieve an iterator to the end of the known-extensions list.
1787 known_extensions_iterator known_extensions_end() const {
1788 return known_extensions_iterator();
1789 }
1790
1791 /// Determine whether the known-extensions list is empty.
1792 bool known_extensions_empty() const {
1793 return known_extensions_begin() == known_extensions_end();
1794 }
1795
1796 /// Retrieve the raw pointer to the start of the category/extension
1797 /// list.
1798 ObjCCategoryDecl* getCategoryListRaw() const {
1799 // FIXME: Should make sure no callers ever do this.
1800 if (!hasDefinition())
1801 return nullptr;
1802
1803 if (data().ExternallyCompleted)
1804 LoadExternalDefinition();
1805
1806 return data().CategoryList;
1807 }
1808
1809 /// Set the raw pointer to the start of the category/extension
1810 /// list.
1811 void setCategoryListRaw(ObjCCategoryDecl *category) {
1812 data().CategoryList = category;
1813 }
1814
1815 ObjCPropertyDecl
1816 *FindPropertyVisibleInPrimaryClass(IdentifierInfo *PropertyId,
1817 ObjCPropertyQueryKind QueryKind) const;
1818
1819 void collectPropertiesToImplement(PropertyMap &PM,
1820 PropertyDeclOrder &PO) const override;
1821
1822 /// isSuperClassOf - Return true if this class is the specified class or is a
1823 /// super class of the specified interface class.
1824 bool isSuperClassOf(const ObjCInterfaceDecl *I) const {
1825 // If RHS is derived from LHS it is OK; else it is not OK.
1826 while (I != nullptr) {
1827 if (declaresSameEntity(this, I))
1828 return true;
1829
1830 I = I->getSuperClass();
1831 }
1832 return false;
1833 }
1834
1835 /// isArcWeakrefUnavailable - Checks for a class or one of its super classes
1836 /// to be incompatible with __weak references. Returns true if it is.
1837 bool isArcWeakrefUnavailable() const;
1838
1839 /// isObjCRequiresPropertyDefs - Checks that a class or one of its super
1840 /// classes must not be auto-synthesized. Returns class decl. if it must not
1841 /// be; 0, otherwise.
1842 const ObjCInterfaceDecl *isObjCRequiresPropertyDefs() const;
1843
1844 ObjCIvarDecl *lookupInstanceVariable(IdentifierInfo *IVarName,
1845 ObjCInterfaceDecl *&ClassDeclared);
1846 ObjCIvarDecl *lookupInstanceVariable(IdentifierInfo *IVarName) {
1847 ObjCInterfaceDecl *ClassDeclared;
1848 return lookupInstanceVariable(IVarName, ClassDeclared);
1849 }
1850
1851 ObjCProtocolDecl *lookupNestedProtocol(IdentifierInfo *Name);
1852
1853 // Lookup a method. First, we search locally. If a method isn't
1854 // found, we search referenced protocols and class categories.
1855 ObjCMethodDecl *lookupMethod(Selector Sel, bool isInstance,
1856 bool shallowCategoryLookup = false,
1857 bool followSuper = true,
1858 const ObjCCategoryDecl *C = nullptr) const;
1859
1860 /// Lookup an instance method for a given selector.
1861 ObjCMethodDecl *lookupInstanceMethod(Selector Sel) const {
1862 return lookupMethod(Sel, true/*isInstance*/);
1863 }
1864
1865 /// Lookup a class method for a given selector.
1866 ObjCMethodDecl *lookupClassMethod(Selector Sel) const {
1867 return lookupMethod(Sel, false/*isInstance*/);
1868 }
1869
1870 ObjCInterfaceDecl *lookupInheritedClass(const IdentifierInfo *ICName);
1871
1872 /// Lookup a method in the classes implementation hierarchy.
1873 ObjCMethodDecl *lookupPrivateMethod(const Selector &Sel,
1874 bool Instance=true) const;
1875
1876 ObjCMethodDecl *lookupPrivateClassMethod(const Selector &Sel) {
1877 return lookupPrivateMethod(Sel, false);
1878 }
1879
1880 /// Lookup a setter or getter in the class hierarchy,
1881 /// including in all categories except for category passed
1882 /// as argument.
1883 ObjCMethodDecl *lookupPropertyAccessor(const Selector Sel,
1884 const ObjCCategoryDecl *Cat,
1885 bool IsClassProperty) const {
1886 return lookupMethod(Sel, !IsClassProperty/*isInstance*/,
1887 false/*shallowCategoryLookup*/,
1888 true /* followsSuper */,
1889 Cat);
1890 }
1891
1892 SourceLocation getEndOfDefinitionLoc() const {
1893 if (!hasDefinition())
1894 return getLocation();
1895
1896 return data().EndLoc;
1897 }
1898
1899 void setEndOfDefinitionLoc(SourceLocation LE) { data().EndLoc = LE; }
1900
1901 /// Retrieve the starting location of the superclass.
1902 SourceLocation getSuperClassLoc() const;
1903
1904 /// isImplicitInterfaceDecl - check that this is an implicitly declared
1905 /// ObjCInterfaceDecl node. This is for legacy objective-c \@implementation
1906 /// declaration without an \@interface declaration.
1907 bool isImplicitInterfaceDecl() const {
1908 return hasDefinition() ? data().Definition->isImplicit() : isImplicit();
1909 }
1910
1911 /// ClassImplementsProtocol - Checks that 'lProto' protocol
1912 /// has been implemented in IDecl class, its super class or categories (if
1913 /// lookupCategory is true).
1914 bool ClassImplementsProtocol(ObjCProtocolDecl *lProto,
1915 bool lookupCategory,
1916 bool RHSIsQualifiedID = false);
1917
1918 using redecl_range = redeclarable_base::redecl_range;
1919 using redecl_iterator = redeclarable_base::redecl_iterator;
1920
1921 using redeclarable_base::redecls_begin;
1922 using redeclarable_base::redecls_end;
1923 using redeclarable_base::redecls;
1924 using redeclarable_base::getPreviousDecl;
1925 using redeclarable_base::getMostRecentDecl;
1926 using redeclarable_base::isFirstDecl;
1927
1928 /// Retrieves the canonical declaration of this Objective-C class.
1929 ObjCInterfaceDecl *getCanonicalDecl() override { return getFirstDecl(); }
1930 const ObjCInterfaceDecl *getCanonicalDecl() const { return getFirstDecl(); }
1931
1932 // Low-level accessor
1933 const Type *getTypeForDecl() const { return TypeForDecl; }
1934 void setTypeForDecl(const Type *TD) const { TypeForDecl = TD; }
1935
1936 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1937 static bool classofKind(Kind K) { return K == ObjCInterface; }
1938
1939private:
1940 const ObjCInterfaceDecl *findInterfaceWithDesignatedInitializers() const;
1941 bool inheritsDesignatedInitializers() const;
1942};
1943
1944/// ObjCIvarDecl - Represents an ObjC instance variable. In general, ObjC
1945/// instance variables are identical to C. The only exception is Objective-C
1946/// supports C++ style access control. For example:
1947///
1948/// \@interface IvarExample : NSObject
1949/// {
1950/// id defaultToProtected;
1951/// \@public:
1952/// id canBePublic; // same as C++.
1953/// \@protected:
1954/// id canBeProtected; // same as C++.
1955/// \@package:
1956/// id canBePackage; // framework visibility (not available in C++).
1957/// }
1958///
1959class ObjCIvarDecl : public FieldDecl {
1960 void anchor() override;
1961
1962public:
1963 enum AccessControl {
1964 None, Private, Protected, Public, Package
1965 };
1966
1967private:
1968 ObjCIvarDecl(ObjCContainerDecl *DC, SourceLocation StartLoc,
1969 SourceLocation IdLoc, IdentifierInfo *Id,
1970 QualType T, TypeSourceInfo *TInfo, AccessControl ac, Expr *BW,
1971 bool synthesized)
1972 : FieldDecl(ObjCIvar, DC, StartLoc, IdLoc, Id, T, TInfo, BW,
1973 /*Mutable=*/false, /*HasInit=*/ICIS_NoInit),
1974 DeclAccess(ac), Synthesized(synthesized) {}
1975
1976public:
1977 static ObjCIvarDecl *Create(ASTContext &C, ObjCContainerDecl *DC,
1978 SourceLocation StartLoc, SourceLocation IdLoc,
1979 IdentifierInfo *Id, QualType T,
1980 TypeSourceInfo *TInfo,
1981 AccessControl ac, Expr *BW = nullptr,
1982 bool synthesized=false);
1983
1984 static ObjCIvarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1985
1986 /// Return the class interface that this ivar is logically contained
1987 /// in; this is either the interface where the ivar was declared, or the
1988 /// interface the ivar is conceptually a part of in the case of synthesized
1989 /// ivars.
1990 const ObjCInterfaceDecl *getContainingInterface() const;
1991
1992 ObjCIvarDecl *getNextIvar() { return NextIvar; }
1993 const ObjCIvarDecl *getNextIvar() const { return NextIvar; }
1994 void setNextIvar(ObjCIvarDecl *ivar) { NextIvar = ivar; }
1995
1996 void setAccessControl(AccessControl ac) { DeclAccess = ac; }
1997
1998 AccessControl getAccessControl() const { return AccessControl(DeclAccess); }
1999
2000 AccessControl getCanonicalAccessControl() const {
2001 return DeclAccess == None ? Protected : AccessControl(DeclAccess);
2002 }
2003
2004 void setSynthesize(bool synth) { Synthesized = synth; }
2005 bool getSynthesize() const { return Synthesized; }
2006
2007 /// Retrieve the type of this instance variable when viewed as a member of a
2008 /// specific object type.
2009 QualType getUsageType(QualType objectType) const;
2010
2011 // Implement isa/cast/dyncast/etc.
2012 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2013 static bool classofKind(Kind K) { return K == ObjCIvar; }
2014
2015private:
2016 /// NextIvar - Next Ivar in the list of ivars declared in class; class's
2017 /// extensions and class's implementation
2018 ObjCIvarDecl *NextIvar = nullptr;
2019
2020 // NOTE: VC++ treats enums as signed, avoid using the AccessControl enum
2021 unsigned DeclAccess : 3;
2022 unsigned Synthesized : 1;
2023};
2024
2025/// Represents a field declaration created by an \@defs(...).
2026class ObjCAtDefsFieldDecl : public FieldDecl {
2027 ObjCAtDefsFieldDecl(DeclContext *DC, SourceLocation StartLoc,
2028 SourceLocation IdLoc, IdentifierInfo *Id,
2029 QualType T, Expr *BW)
2030 : FieldDecl(ObjCAtDefsField, DC, StartLoc, IdLoc, Id, T,
2031 /*TInfo=*/nullptr, // FIXME: Do ObjCAtDefs have declarators ?
2032 BW, /*Mutable=*/false, /*HasInit=*/ICIS_NoInit) {}
2033
2034 void anchor() override;
2035
2036public:
2037 static ObjCAtDefsFieldDecl *Create(ASTContext &C, DeclContext *DC,
2038 SourceLocation StartLoc,
2039 SourceLocation IdLoc, IdentifierInfo *Id,
2040 QualType T, Expr *BW);
2041
2042 static ObjCAtDefsFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2043
2044 // Implement isa/cast/dyncast/etc.
2045 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2046 static bool classofKind(Kind K) { return K == ObjCAtDefsField; }
2047};
2048
2049/// Represents an Objective-C protocol declaration.
2050///
2051/// Objective-C protocols declare a pure abstract type (i.e., no instance
2052/// variables are permitted). Protocols originally drew inspiration from
2053/// C++ pure virtual functions (a C++ feature with nice semantics and lousy
2054/// syntax:-). Here is an example:
2055///
2056/// \code
2057/// \@protocol NSDraggingInfo <refproto1, refproto2>
2058/// - (NSWindow *)draggingDestinationWindow;
2059/// - (NSImage *)draggedImage;
2060/// \@end
2061/// \endcode
2062///
2063/// This says that NSDraggingInfo requires two methods and requires everything
2064/// that the two "referenced protocols" 'refproto1' and 'refproto2' require as
2065/// well.
2066///
2067/// \code
2068/// \@interface ImplementsNSDraggingInfo : NSObject \<NSDraggingInfo>
2069/// \@end
2070/// \endcode
2071///
2072/// ObjC protocols inspired Java interfaces. Unlike Java, ObjC classes and
2073/// protocols are in distinct namespaces. For example, Cocoa defines both
2074/// an NSObject protocol and class (which isn't allowed in Java). As a result,
2075/// protocols are referenced using angle brackets as follows:
2076///
2077/// id \<NSDraggingInfo> anyObjectThatImplementsNSDraggingInfo;
2078class ObjCProtocolDecl : public ObjCContainerDecl,
2079 public Redeclarable<ObjCProtocolDecl> {
2080 struct DefinitionData {
2081 // The declaration that defines this protocol.
2082 ObjCProtocolDecl *Definition;
2083
2084 /// Referenced protocols
2085 ObjCProtocolList ReferencedProtocols;
2086 };
2087
2088 /// Contains a pointer to the data associated with this class,
2089 /// which will be NULL if this class has not yet been defined.
2090 ///
2091 /// The bit indicates when we don't need to check for out-of-date
2092 /// declarations. It will be set unless modules are enabled.
2093 llvm::PointerIntPair<DefinitionData *, 1, bool> Data;
2094
2095 ObjCProtocolDecl(ASTContext &C, DeclContext *DC, IdentifierInfo *Id,
2096 SourceLocation nameLoc, SourceLocation atStartLoc,
2097 ObjCProtocolDecl *PrevDecl);
2098
2099 void anchor() override;
2100
2101 DefinitionData &data() const {
2102 assert(Data.getPointer() && "Objective-C protocol has no definition!")((Data.getPointer() && "Objective-C protocol has no definition!"
) ? static_cast<void> (0) : __assert_fail ("Data.getPointer() && \"Objective-C protocol has no definition!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclObjC.h"
, 2102, __PRETTY_FUNCTION__))
;
2103 return *Data.getPointer();
2104 }
2105
2106 void allocateDefinitionData();
2107
2108 using redeclarable_base = Redeclarable<ObjCProtocolDecl>;
2109
2110 ObjCProtocolDecl *getNextRedeclarationImpl() override {
2111 return getNextRedeclaration();
2112 }
2113
2114 ObjCProtocolDecl *getPreviousDeclImpl() override {
2115 return getPreviousDecl();
2116 }
2117
2118 ObjCProtocolDecl *getMostRecentDeclImpl() override {
2119 return getMostRecentDecl();
2120 }
2121
2122public:
2123 friend class ASTDeclReader;
2124 friend class ASTDeclWriter;
2125 friend class ASTReader;
2126
2127 static ObjCProtocolDecl *Create(ASTContext &C, DeclContext *DC,
2128 IdentifierInfo *Id,
2129 SourceLocation nameLoc,
2130 SourceLocation atStartLoc,
2131 ObjCProtocolDecl *PrevDecl);
2132
2133 static ObjCProtocolDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2134
2135 const ObjCProtocolList &getReferencedProtocols() const {
2136 assert(hasDefinition() && "No definition available!")((hasDefinition() && "No definition available!") ? static_cast
<void> (0) : __assert_fail ("hasDefinition() && \"No definition available!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclObjC.h"
, 2136, __PRETTY_FUNCTION__))
;
2137 return data().ReferencedProtocols;
2138 }
2139
2140 using protocol_iterator = ObjCProtocolList::iterator;
2141 using protocol_range = llvm::iterator_range<protocol_iterator>;
2142
2143 protocol_range protocols() const {
2144 return protocol_range(protocol_begin(), protocol_end());
2145 }
2146
2147 protocol_iterator protocol_begin() const {
2148 if (!hasDefinition())
2149 return protocol_iterator();
2150
2151 return data().ReferencedProtocols.begin();
2152 }
2153
2154 protocol_iterator protocol_end() const {
2155 if (!hasDefinition())
2156 return protocol_iterator();
2157
2158 return data().ReferencedProtocols.end();
2159 }
2160
2161 using protocol_loc_iterator = ObjCProtocolList::loc_iterator;
2162 using protocol_loc_range = llvm::iterator_range<protocol_loc_iterator>;
2163
2164 protocol_loc_range protocol_locs() const {
2165 return protocol_loc_range(protocol_loc_begin(), protocol_loc_end());
2166 }
2167
2168 protocol_loc_iterator protocol_loc_begin() const {
2169 if (!hasDefinition())
2170 return protocol_loc_iterator();
2171
2172 return data().ReferencedProtocols.loc_begin();
2173 }
2174
2175 protocol_loc_iterator protocol_loc_end() const {
2176 if (!hasDefinition())
2177 return protocol_loc_iterator();
2178
2179 return data().ReferencedProtocols.loc_end();
2180 }
2181
2182 unsigned protocol_size() const {
2183 if (!hasDefinition())
2184 return 0;
2185
2186 return data().ReferencedProtocols.size();
2187 }
2188
2189 /// setProtocolList - Set the list of protocols that this interface
2190 /// implements.
2191 void setProtocolList(ObjCProtocolDecl *const*List, unsigned Num,
2192 const SourceLocation *Locs, ASTContext &C) {
2193 assert(hasDefinition() && "Protocol is not defined")((hasDefinition() && "Protocol is not defined") ? static_cast
<void> (0) : __assert_fail ("hasDefinition() && \"Protocol is not defined\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclObjC.h"
, 2193, __PRETTY_FUNCTION__))
;
2194 data().ReferencedProtocols.set(List, Num, Locs, C);
2195 }
2196
2197 ObjCProtocolDecl *lookupProtocolNamed(IdentifierInfo *PName);
2198
2199 // Lookup a method. First, we search locally. If a method isn't
2200 // found, we search referenced protocols and class categories.
2201 ObjCMethodDecl *lookupMethod(Selector Sel, bool isInstance) const;
2202
2203 ObjCMethodDecl *lookupInstanceMethod(Selector Sel) const {
2204 return lookupMethod(Sel, true/*isInstance*/);
2205 }
2206
2207 ObjCMethodDecl *lookupClassMethod(Selector Sel) const {
2208 return lookupMethod(Sel, false/*isInstance*/);
2209 }
2210
2211 /// Determine whether this protocol has a definition.
2212 bool hasDefinition() const {
2213 // If the name of this protocol is out-of-date, bring it up-to-date, which
2214 // might bring in a definition.
2215 // Note: a null value indicates that we don't have a definition and that
2216 // modules are enabled.
2217 if (!Data.getOpaqueValue())
2218 getMostRecentDecl();
2219
2220 return Data.getPointer();
2221 }
2222
2223 /// Retrieve the definition of this protocol, if any.
2224 ObjCProtocolDecl *getDefinition() {
2225 return hasDefinition()? Data.getPointer()->Definition : nullptr;
2226 }
2227
2228 /// Retrieve the definition of this protocol, if any.
2229 const ObjCProtocolDecl *getDefinition() const {
2230 return hasDefinition()? Data.getPointer()->Definition : nullptr;
2231 }
2232
2233 /// Determine whether this particular declaration is also the
2234 /// definition.
2235 bool isThisDeclarationADefinition() const {
2236 return getDefinition() == this;
2237 }
2238
2239 /// Starts the definition of this Objective-C protocol.
2240 void startDefinition();
2241
2242 /// Produce a name to be used for protocol's metadata. It comes either via
2243 /// objc_runtime_name attribute or protocol name.
2244 StringRef getObjCRuntimeNameAsString() const;
2245
2246 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
2247 if (isThisDeclarationADefinition())
2248 return ObjCContainerDecl::getSourceRange();
2249
2250 return SourceRange(getAtStartLoc(), getLocation());
2251 }
2252
2253 using redecl_range = redeclarable_base::redecl_range;
2254 using redecl_iterator = redeclarable_base::redecl_iterator;
2255
2256 using redeclarable_base::redecls_begin;
2257 using redeclarable_base::redecls_end;
2258 using redeclarable_base::redecls;
2259 using redeclarable_base::getPreviousDecl;
2260 using redeclarable_base::getMostRecentDecl;
2261 using redeclarable_base::isFirstDecl;
2262
2263 /// Retrieves the canonical declaration of this Objective-C protocol.
2264 ObjCProtocolDecl *getCanonicalDecl() override { return getFirstDecl(); }
2265 const ObjCProtocolDecl *getCanonicalDecl() const { return getFirstDecl(); }
2266
2267 void collectPropertiesToImplement(PropertyMap &PM,
2268 PropertyDeclOrder &PO) const override;
2269
2270 void collectInheritedProtocolProperties(const ObjCPropertyDecl *Property,
2271 ProtocolPropertySet &PS,
2272 PropertyDeclOrder &PO) const;
2273
2274 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2275 static bool classofKind(Kind K) { return K == ObjCProtocol; }
2276};
2277
2278/// ObjCCategoryDecl - Represents a category declaration. A category allows
2279/// you to add methods to an existing class (without subclassing or modifying
2280/// the original class interface or implementation:-). Categories don't allow
2281/// you to add instance data. The following example adds "myMethod" to all
2282/// NSView's within a process:
2283///
2284/// \@interface NSView (MyViewMethods)
2285/// - myMethod;
2286/// \@end
2287///
2288/// Categories also allow you to split the implementation of a class across
2289/// several files (a feature more naturally supported in C++).
2290///
2291/// Categories were originally inspired by dynamic languages such as Common
2292/// Lisp and Smalltalk. More traditional class-based languages (C++, Java)
2293/// don't support this level of dynamism, which is both powerful and dangerous.
2294class ObjCCategoryDecl : public ObjCContainerDecl {
2295 /// Interface belonging to this category
2296 ObjCInterfaceDecl *ClassInterface;
2297
2298 /// The type parameters associated with this category, if any.
2299 ObjCTypeParamList *TypeParamList = nullptr;
2300
2301 /// referenced protocols in this category.
2302 ObjCProtocolList ReferencedProtocols;
2303
2304 /// Next category belonging to this class.
2305 /// FIXME: this should not be a singly-linked list. Move storage elsewhere.
2306 ObjCCategoryDecl *NextClassCategory = nullptr;
2307
2308 /// The location of the category name in this declaration.
2309 SourceLocation CategoryNameLoc;
2310
2311 /// class extension may have private ivars.
2312 SourceLocation IvarLBraceLoc;
2313 SourceLocation IvarRBraceLoc;
2314
2315 ObjCCategoryDecl(DeclContext *DC, SourceLocation AtLoc,
2316 SourceLocation ClassNameLoc, SourceLocation CategoryNameLoc,
2317 IdentifierInfo *Id, ObjCInterfaceDecl *IDecl,
2318 ObjCTypeParamList *typeParamList,
2319 SourceLocation IvarLBraceLoc = SourceLocation(),
2320 SourceLocation IvarRBraceLoc = SourceLocation());
2321
2322 void anchor() override;
2323
2324public:
2325 friend class ASTDeclReader;
2326 friend class ASTDeclWriter;
2327
2328 static ObjCCategoryDecl *Create(ASTContext &C, DeclContext *DC,
2329 SourceLocation AtLoc,
2330 SourceLocation ClassNameLoc,
2331 SourceLocation CategoryNameLoc,
2332 IdentifierInfo *Id,
2333 ObjCInterfaceDecl *IDecl,
2334 ObjCTypeParamList *typeParamList,
2335 SourceLocation IvarLBraceLoc=SourceLocation(),
2336 SourceLocation IvarRBraceLoc=SourceLocation());
2337 static ObjCCategoryDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2338
2339 ObjCInterfaceDecl *getClassInterface() { return ClassInterface; }
2340 const ObjCInterfaceDecl *getClassInterface() const { return ClassInterface; }
2341
2342 /// Retrieve the type parameter list associated with this category or
2343 /// extension.
2344 ObjCTypeParamList *getTypeParamList() const { return TypeParamList; }
2345
2346 /// Set the type parameters of this category.
2347 ///
2348 /// This function is used by the AST importer, which must import the type
2349 /// parameters after creating their DeclContext to avoid loops.
2350 void setTypeParamList(ObjCTypeParamList *TPL);
2351
2352
2353 ObjCCategoryImplDecl *getImplementation() const;
2354 void setImplementation(ObjCCategoryImplDecl *ImplD);
2355
2356 /// setProtocolList - Set the list of protocols that this interface
2357 /// implements.
2358 void setProtocolList(ObjCProtocolDecl *const*List, unsigned Num,
2359 const SourceLocation *Locs, ASTContext &C) {
2360 ReferencedProtocols.set(List, Num, Locs, C);
2361 }
2362
2363 const ObjCProtocolList &getReferencedProtocols() const {
2364 return ReferencedProtocols;
2365 }
2366
2367 using protocol_iterator = ObjCProtocolList::iterator;
2368 using protocol_range = llvm::iterator_range<protocol_iterator>;
2369
2370 protocol_range protocols() const {
2371 return protocol_range(protocol_begin(), protocol_end());
2372 }
2373
2374 protocol_iterator protocol_begin() const {
2375 return ReferencedProtocols.begin();
2376 }
2377
2378 protocol_iterator protocol_end() const { return ReferencedProtocols.end(); }
2379 unsigned protocol_size() const { return ReferencedProtocols.size(); }
2380
2381 using protocol_loc_iterator = ObjCProtocolList::loc_iterator;
2382 using protocol_loc_range = llvm::iterator_range<protocol_loc_iterator>;
2383
2384 protocol_loc_range protocol_locs() const {
2385 return protocol_loc_range(protocol_loc_begin(), protocol_loc_end());
2386 }
2387
2388 protocol_loc_iterator protocol_loc_begin() const {
2389 return ReferencedProtocols.loc_begin();
2390 }
2391
2392 protocol_loc_iterator protocol_loc_end() const {
2393 return ReferencedProtocols.loc_end();
2394 }
2395
2396 ObjCCategoryDecl *getNextClassCategory() const { return NextClassCategory; }
2397
2398 /// Retrieve the pointer to the next stored category (or extension),
2399 /// which may be hidden.
2400 ObjCCategoryDecl *getNextClassCategoryRaw() const {
2401 return NextClassCategory;
2402 }
2403
2404 bool IsClassExtension() const { return getIdentifier() == nullptr; }
2405
2406 using ivar_iterator = specific_decl_iterator<ObjCIvarDecl>;
2407 using ivar_range = llvm::iterator_range<specific_decl_iterator<ObjCIvarDecl>>;
2408
2409 ivar_range ivars() const { return ivar_range(ivar_begin(), ivar_end()); }
2410
2411 ivar_iterator ivar_begin() const {
2412 return ivar_iterator(decls_begin());
2413 }
2414
2415 ivar_iterator ivar_end() const {
2416 return ivar_iterator(decls_end());
2417 }
2418
2419 unsigned ivar_size() const {
2420 return std::distance(ivar_begin(), ivar_end());
2421 }
2422
2423 bool ivar_empty() const {
2424 return ivar_begin() == ivar_end();
2425 }
2426
2427 SourceLocation getCategoryNameLoc() const { return CategoryNameLoc; }
2428 void setCategoryNameLoc(SourceLocation Loc) { CategoryNameLoc = Loc; }
2429
2430 void setIvarLBraceLoc(SourceLocation Loc) { IvarLBraceLoc = Loc; }
2431 SourceLocation getIvarLBraceLoc() const { return IvarLBraceLoc; }
2432 void setIvarRBraceLoc(SourceLocation Loc) { IvarRBraceLoc = Loc; }
2433 SourceLocation getIvarRBraceLoc() const { return IvarRBraceLoc; }
2434
2435 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2436 static bool classofKind(Kind K) { return K == ObjCCategory; }
2437};
2438
2439class ObjCImplDecl : public ObjCContainerDecl {
2440 /// Class interface for this class/category implementation
2441 ObjCInterfaceDecl *ClassInterface;
2442
2443 void anchor() override;
2444
2445protected:
2446 ObjCImplDecl(Kind DK, DeclContext *DC,
2447 ObjCInterfaceDecl *classInterface,
2448 IdentifierInfo *Id,
2449 SourceLocation nameLoc, SourceLocation atStartLoc)
2450 : ObjCContainerDecl(DK, DC, Id, nameLoc, atStartLoc),
2451 ClassInterface(classInterface) {}
2452
2453public:
2454 const ObjCInterfaceDecl *getClassInterface() const { return ClassInterface; }
2455 ObjCInterfaceDecl *getClassInterface() { return ClassInterface; }
2456 void setClassInterface(ObjCInterfaceDecl *IFace);
2457
2458 void addInstanceMethod(ObjCMethodDecl *method) {
2459 // FIXME: Context should be set correctly before we get here.
2460 method->setLexicalDeclContext(this);
2461 addDecl(method);
2462 }
2463
2464 void addClassMethod(ObjCMethodDecl *method) {
2465 // FIXME: Context should be set correctly before we get here.
2466 method->setLexicalDeclContext(this);
2467 addDecl(method);
2468 }
2469
2470 void addPropertyImplementation(ObjCPropertyImplDecl *property);
2471
2472 ObjCPropertyImplDecl *FindPropertyImplDecl(IdentifierInfo *propertyId,
2473 ObjCPropertyQueryKind queryKind) const;
2474 ObjCPropertyImplDecl *FindPropertyImplIvarDecl(IdentifierInfo *ivarId) const;
2475
2476 // Iterator access to properties.
2477 using propimpl_iterator = specific_decl_iterator<ObjCPropertyImplDecl>;
2478 using propimpl_range =
2479 llvm::iterator_range<specific_decl_iterator<ObjCPropertyImplDecl>>;
2480
2481 propimpl_range property_impls() const {
2482 return propimpl_range(propimpl_begin(), propimpl_end());
2483 }
2484
2485 propimpl_iterator propimpl_begin() const {
2486 return propimpl_iterator(decls_begin());
2487 }
2488
2489 propimpl_iterator propimpl_end() const {
2490 return propimpl_iterator(decls_end());
2491 }
2492
2493 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2494
2495 static bool classofKind(Kind K) {
2496 return K >= firstObjCImpl && K <= lastObjCImpl;
2497 }
2498};
2499
2500/// ObjCCategoryImplDecl - An object of this class encapsulates a category
2501/// \@implementation declaration. If a category class has declaration of a
2502/// property, its implementation must be specified in the category's
2503/// \@implementation declaration. Example:
2504/// \@interface I \@end
2505/// \@interface I(CATEGORY)
2506/// \@property int p1, d1;
2507/// \@end
2508/// \@implementation I(CATEGORY)
2509/// \@dynamic p1,d1;
2510/// \@end
2511///
2512/// ObjCCategoryImplDecl
2513class ObjCCategoryImplDecl : public ObjCImplDecl {
2514 // Category name location
2515 SourceLocation CategoryNameLoc;
2516
2517 ObjCCategoryImplDecl(DeclContext *DC, IdentifierInfo *Id,
2518 ObjCInterfaceDecl *classInterface,
2519 SourceLocation nameLoc, SourceLocation atStartLoc,
2520 SourceLocation CategoryNameLoc)
2521 : ObjCImplDecl(ObjCCategoryImpl, DC, classInterface, Id,
2522 nameLoc, atStartLoc),
2523 CategoryNameLoc(CategoryNameLoc) {}
2524
2525 void anchor() override;
2526
2527public:
2528 friend class ASTDeclReader;
2529 friend class ASTDeclWriter;
2530
2531 static ObjCCategoryImplDecl *Create(ASTContext &C, DeclContext *DC,
2532 IdentifierInfo *Id,
2533 ObjCInterfaceDecl *classInterface,
2534 SourceLocation nameLoc,
2535 SourceLocation atStartLoc,
2536 SourceLocation CategoryNameLoc);
2537 static ObjCCategoryImplDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2538
2539 ObjCCategoryDecl *getCategoryDecl() const;
2540
2541 SourceLocation getCategoryNameLoc() const { return CategoryNameLoc; }
2542
2543 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2544 static bool classofKind(Kind K) { return K == ObjCCategoryImpl;}
2545};
2546
2547raw_ostream &operator<<(raw_ostream &OS, const ObjCCategoryImplDecl &CID);
2548
2549/// ObjCImplementationDecl - Represents a class definition - this is where
2550/// method definitions are specified. For example:
2551///
2552/// @code
2553/// \@implementation MyClass
2554/// - (void)myMethod { /* do something */ }
2555/// \@end
2556/// @endcode
2557///
2558/// In a non-fragile runtime, instance variables can appear in the class
2559/// interface, class extensions (nameless categories), and in the implementation
2560/// itself, as well as being synthesized as backing storage for properties.
2561///
2562/// In a fragile runtime, instance variables are specified in the class
2563/// interface, \em not in the implementation. Nevertheless (for legacy reasons),
2564/// we allow instance variables to be specified in the implementation. When
2565/// specified, they need to be \em identical to the interface.
2566class ObjCImplementationDecl : public ObjCImplDecl {
2567 /// Implementation Class's super class.
2568 ObjCInterfaceDecl *SuperClass;
2569 SourceLocation SuperLoc;
2570
2571 /// \@implementation may have private ivars.
2572 SourceLocation IvarLBraceLoc;
2573 SourceLocation IvarRBraceLoc;
2574
2575 /// Support for ivar initialization.
2576 /// The arguments used to initialize the ivars
2577 LazyCXXCtorInitializersPtr IvarInitializers;
2578 unsigned NumIvarInitializers = 0;
2579
2580 /// Do the ivars of this class require initialization other than
2581 /// zero-initialization?
2582 bool HasNonZeroConstructors : 1;
2583
2584 /// Do the ivars of this class require non-trivial destruction?
2585 bool HasDestructors : 1;
2586
2587 ObjCImplementationDecl(DeclContext *DC,
2588 ObjCInterfaceDecl *classInterface,
2589 ObjCInterfaceDecl *superDecl,
2590 SourceLocation nameLoc, SourceLocation atStartLoc,
2591 SourceLocation superLoc = SourceLocation(),
2592 SourceLocation IvarLBraceLoc=SourceLocation(),
2593 SourceLocation IvarRBraceLoc=SourceLocation())
2594 : ObjCImplDecl(ObjCImplementation, DC, classInterface,
2595 classInterface ? classInterface->getIdentifier()
2596 : nullptr,
2597 nameLoc, atStartLoc),
2598 SuperClass(superDecl), SuperLoc(superLoc),
2599 IvarLBraceLoc(IvarLBraceLoc), IvarRBraceLoc(IvarRBraceLoc),
2600 HasNonZeroConstructors(false), HasDestructors(false) {}
2601
2602 void anchor() override;
2603
2604public:
2605 friend class ASTDeclReader;
2606 friend class ASTDeclWriter;
2607
2608 static ObjCImplementationDecl *Create(ASTContext &C, DeclContext *DC,
2609 ObjCInterfaceDecl *classInterface,
2610 ObjCInterfaceDecl *superDecl,
2611 SourceLocation nameLoc,
2612 SourceLocation atStartLoc,
2613 SourceLocation superLoc = SourceLocation(),
2614 SourceLocation IvarLBraceLoc=SourceLocation(),
2615 SourceLocation IvarRBraceLoc=SourceLocation());
2616
2617 static ObjCImplementationDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2618
2619 /// init_iterator - Iterates through the ivar initializer list.
2620 using init_iterator = CXXCtorInitializer **;
2621
2622 /// init_const_iterator - Iterates through the ivar initializer list.
2623 using init_const_iterator = CXXCtorInitializer * const *;
2624
2625 using init_range = llvm::iterator_range<init_iterator>;
2626 using init_const_range = llvm::iterator_range<init_const_iterator>;
2627
2628 init_range inits() { return init_range(init_begin(), init_end()); }
2629
2630 init_const_range inits() const {
2631 return init_const_range(init_begin(), init_end());
2632 }
2633
2634 /// init_begin() - Retrieve an iterator to the first initializer.
2635 init_iterator init_begin() {
2636 const auto *ConstThis = this;
2637 return const_cast<init_iterator>(ConstThis->init_begin());
2638 }
2639
2640 /// begin() - Retrieve an iterator to the first initializer.
2641 init_const_iterator init_begin() const;
2642
2643 /// init_end() - Retrieve an iterator past the last initializer.
2644 init_iterator init_end() {
2645 return init_begin() + NumIvarInitializers;
2646 }
2647
2648 /// end() - Retrieve an iterator past the last initializer.
2649 init_const_iterator init_end() const {
2650 return init_begin() + NumIvarInitializers;
2651 }
2652
2653 /// getNumArgs - Number of ivars which must be initialized.
2654 unsigned getNumIvarInitializers() const {
2655 return NumIvarInitializers;
2656 }
2657
2658 void setNumIvarInitializers(unsigned numNumIvarInitializers) {
2659 NumIvarInitializers = numNumIvarInitializers;
2660 }
2661
2662 void setIvarInitializers(ASTContext &C,
2663 CXXCtorInitializer ** initializers,
2664 unsigned numInitializers);
2665
2666 /// Do any of the ivars of this class (not counting its base classes)
2667 /// require construction other than zero-initialization?
2668 bool hasNonZeroConstructors() const { return HasNonZeroConstructors; }
2669 void setHasNonZeroConstructors(bool val) { HasNonZeroConstructors = val; }
2670
2671 /// Do any of the ivars of this class (not counting its base classes)
2672 /// require non-trivial destruction?
2673 bool hasDestructors() const { return HasDestructors; }
2674 void setHasDestructors(bool val) { HasDestructors = val; }
2675
2676 /// getIdentifier - Get the identifier that names the class
2677 /// interface associated with this implementation.
2678 IdentifierInfo *getIdentifier() const {
2679 return getClassInterface()->getIdentifier();
2680 }
2681
2682 /// getName - Get the name of identifier for the class interface associated
2683 /// with this implementation as a StringRef.
2684 //
2685 // FIXME: This is a bad API, we are hiding NamedDecl::getName with a different
2686 // meaning.
2687 StringRef getName() const {
2688 assert(getIdentifier() && "Name is not a simple identifier")((getIdentifier() && "Name is not a simple identifier"
) ? static_cast<void> (0) : __assert_fail ("getIdentifier() && \"Name is not a simple identifier\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclObjC.h"
, 2688, __PRETTY_FUNCTION__))
;
2689 return getIdentifier()->getName();
2690 }
2691
2692 /// Get the name of the class associated with this interface.
2693 //
2694 // FIXME: Move to StringRef API.
2695 std::string getNameAsString() const { return std::string(getName()); }
2696
2697 /// Produce a name to be used for class's metadata. It comes either via
2698 /// class's objc_runtime_name attribute or class name.
2699 StringRef getObjCRuntimeNameAsString() const;
2700
2701 const ObjCInterfaceDecl *getSuperClass() const { return SuperClass; }
2702 ObjCInterfaceDecl *getSuperClass() { return SuperClass; }
2703 SourceLocation getSuperClassLoc() const { return SuperLoc; }
2704
2705 void setSuperClass(ObjCInterfaceDecl * superCls) { SuperClass = superCls; }
2706
2707 void setIvarLBraceLoc(SourceLocation Loc) { IvarLBraceLoc = Loc; }
2708 SourceLocation getIvarLBraceLoc() const { return IvarLBraceLoc; }
2709 void setIvarRBraceLoc(SourceLocation Loc) { IvarRBraceLoc = Loc; }
2710 SourceLocation getIvarRBraceLoc() const { return IvarRBraceLoc; }
2711
2712 using ivar_iterator = specific_decl_iterator<ObjCIvarDecl>;
2713 using ivar_range = llvm::iterator_range<specific_decl_iterator<ObjCIvarDecl>>;
2714
2715 ivar_range ivars() const { return ivar_range(ivar_begin(), ivar_end()); }
2716
2717 ivar_iterator ivar_begin() const {
2718 return ivar_iterator(decls_begin());
2719 }
2720
2721 ivar_iterator ivar_end() const {
2722 return ivar_iterator(decls_end());
2723 }
2724
2725 unsigned ivar_size() const {
2726 return std::distance(ivar_begin(), ivar_end());
2727 }
2728
2729 bool ivar_empty() const {
2730 return ivar_begin() == ivar_end();
28
Calling 'operator=='
34
Returning from 'operator=='
35
Returning zero, which participates in a condition later
2731 }
2732
2733 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2734 static bool classofKind(Kind K) { return K == ObjCImplementation; }
2735};
2736
2737raw_ostream &operator<<(raw_ostream &OS, const ObjCImplementationDecl &ID);
2738
2739/// ObjCCompatibleAliasDecl - Represents alias of a class. This alias is
2740/// declared as \@compatibility_alias alias class.
2741class ObjCCompatibleAliasDecl : public NamedDecl {
2742 /// Class that this is an alias of.
2743 ObjCInterfaceDecl *AliasedClass;
2744
2745 ObjCCompatibleAliasDecl(DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
2746 ObjCInterfaceDecl* aliasedClass)
2747 : NamedDecl(ObjCCompatibleAlias, DC, L, Id), AliasedClass(aliasedClass) {}
2748
2749 void anchor() override;
2750
2751public:
2752 static ObjCCompatibleAliasDecl *Create(ASTContext &C, DeclContext *DC,
2753 SourceLocation L, IdentifierInfo *Id,
2754 ObjCInterfaceDecl* aliasedClass);
2755
2756 static ObjCCompatibleAliasDecl *CreateDeserialized(ASTContext &C,
2757 unsigned ID);
2758
2759 const ObjCInterfaceDecl *getClassInterface() const { return AliasedClass; }
2760 ObjCInterfaceDecl *getClassInterface() { return AliasedClass; }
2761 void setClassInterface(ObjCInterfaceDecl *D) { AliasedClass = D; }
2762
2763 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2764 static bool classofKind(Kind K) { return K == ObjCCompatibleAlias; }
2765};
2766
2767/// ObjCPropertyImplDecl - Represents implementation declaration of a property
2768/// in a class or category implementation block. For example:
2769/// \@synthesize prop1 = ivar1;
2770///
2771class ObjCPropertyImplDecl : public Decl {
2772public:
2773 enum Kind {
2774 Synthesize,
2775 Dynamic
2776 };
2777
2778private:
2779 SourceLocation AtLoc; // location of \@synthesize or \@dynamic
2780
2781 /// For \@synthesize, the location of the ivar, if it was written in
2782 /// the source code.
2783 ///
2784 /// \code
2785 /// \@synthesize int a = b
2786 /// \endcode
2787 SourceLocation IvarLoc;
2788
2789 /// Property declaration being implemented
2790 ObjCPropertyDecl *PropertyDecl;
2791
2792 /// Null for \@dynamic. Required for \@synthesize.
2793 ObjCIvarDecl *PropertyIvarDecl;
2794
2795 /// The getter's definition, which has an empty body if synthesized.
2796 ObjCMethodDecl *GetterMethodDecl = nullptr;
2797 /// The getter's definition, which has an empty body if synthesized.
2798 ObjCMethodDecl *SetterMethodDecl = nullptr;
2799
2800 /// Null for \@dynamic. Non-null if property must be copy-constructed in
2801 /// getter.
2802 Expr *GetterCXXConstructor = nullptr;
2803
2804 /// Null for \@dynamic. Non-null if property has assignment operator to call
2805 /// in Setter synthesis.
2806 Expr *SetterCXXAssignment = nullptr;
2807
2808 ObjCPropertyImplDecl(DeclContext *DC, SourceLocation atLoc, SourceLocation L,
2809 ObjCPropertyDecl *property,
2810 Kind PK,
2811 ObjCIvarDecl *ivarDecl,
2812 SourceLocation ivarLoc)
2813 : Decl(ObjCPropertyImpl, DC, L), AtLoc(atLoc),
2814 IvarLoc(ivarLoc), PropertyDecl(property), PropertyIvarDecl(ivarDecl) {
2815 assert(PK == Dynamic || PropertyIvarDecl)((PK == Dynamic || PropertyIvarDecl) ? static_cast<void>
(0) : __assert_fail ("PK == Dynamic || PropertyIvarDecl", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclObjC.h"
, 2815, __PRETTY_FUNCTION__))
;
2816 }
2817
2818public:
2819 friend class ASTDeclReader;
2820
2821 static ObjCPropertyImplDecl *Create(ASTContext &C, DeclContext *DC,
2822 SourceLocation atLoc, SourceLocation L,
2823 ObjCPropertyDecl *property,
2824 Kind PK,
2825 ObjCIvarDecl *ivarDecl,
2826 SourceLocation ivarLoc);
2827
2828 static ObjCPropertyImplDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2829
2830 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
2831
2832 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return AtLoc; }
2833 void setAtLoc(SourceLocation Loc) { AtLoc = Loc; }
2834
2835 ObjCPropertyDecl *getPropertyDecl() const {
2836 return PropertyDecl;
2837 }
2838 void setPropertyDecl(ObjCPropertyDecl *Prop) { PropertyDecl = Prop; }
2839
2840 Kind getPropertyImplementation() const {
2841 return PropertyIvarDecl ? Synthesize : Dynamic;
2842 }
2843
2844 ObjCIvarDecl *getPropertyIvarDecl() const {
2845 return PropertyIvarDecl;
2846 }
2847 SourceLocation getPropertyIvarDeclLoc() const { return IvarLoc; }
2848
2849 void setPropertyIvarDecl(ObjCIvarDecl *Ivar,
2850 SourceLocation IvarLoc) {
2851 PropertyIvarDecl = Ivar;
2852 this->IvarLoc = IvarLoc;
2853 }
2854
2855 /// For \@synthesize, returns true if an ivar name was explicitly
2856 /// specified.
2857 ///
2858 /// \code
2859 /// \@synthesize int a = b; // true
2860 /// \@synthesize int a; // false
2861 /// \endcode
2862 bool isIvarNameSpecified() const {
2863 return IvarLoc.isValid() && IvarLoc != getLocation();
2864 }
2865
2866 ObjCMethodDecl *getGetterMethodDecl() const { return GetterMethodDecl; }
2867 void setGetterMethodDecl(ObjCMethodDecl *MD) { GetterMethodDecl = MD; }
2868
2869 ObjCMethodDecl *getSetterMethodDecl() const { return SetterMethodDecl; }
2870 void setSetterMethodDecl(ObjCMethodDecl *MD) { SetterMethodDecl = MD; }
2871
2872 Expr *getGetterCXXConstructor() const {
2873 return GetterCXXConstructor;
2874 }
2875
2876 void setGetterCXXConstructor(Expr *getterCXXConstructor) {
2877 GetterCXXConstructor = getterCXXConstructor;
2878 }
2879
2880 Expr *getSetterCXXAssignment() const {
2881 return SetterCXXAssignment;
2882 }
2883
2884 void setSetterCXXAssignment(Expr *setterCXXAssignment) {
2885 SetterCXXAssignment = setterCXXAssignment;
2886 }
2887
2888 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2889 static bool classofKind(Decl::Kind K) { return K == ObjCPropertyImpl; }
2890};
2891
2892template<bool (*Filter)(ObjCCategoryDecl *)>
2893void
2894ObjCInterfaceDecl::filtered_category_iterator<Filter>::
2895findAcceptableCategory() {
2896 while (Current && !Filter(Current))
2897 Current = Current->getNextClassCategoryRaw();
2898}
2899
2900template<bool (*Filter)(ObjCCategoryDecl *)>
2901inline ObjCInterfaceDecl::filtered_category_iterator<Filter> &
2902ObjCInterfaceDecl::filtered_category_iterator<Filter>::operator++() {
2903 Current = Current->getNextClassCategoryRaw();
2904 findAcceptableCategory();
2905 return *this;
2906}
2907
2908inline bool ObjCInterfaceDecl::isVisibleCategory(ObjCCategoryDecl *Cat) {
2909 return !Cat->isHidden();
2910}
2911
2912inline bool ObjCInterfaceDecl::isVisibleExtension(ObjCCategoryDecl *Cat) {
2913 return Cat->IsClassExtension() && !Cat->isHidden();
2914}
2915
2916inline bool ObjCInterfaceDecl::isKnownExtension(ObjCCategoryDecl *Cat) {
2917 return Cat->IsClassExtension();
2918}
2919
2920} // namespace clang
2921
2922#endif // LLVM_CLANG_AST_DECLOBJC_H

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h

1//===- DeclBase.h - Base Classes for representing declarations --*- C++ -*-===//
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 defines the Decl and DeclContext interfaces.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_AST_DECLBASE_H
14#define LLVM_CLANG_AST_DECLBASE_H
15
16#include "clang/AST/ASTDumperUtils.h"
17#include "clang/AST/AttrIterator.h"
18#include "clang/AST/DeclarationName.h"
19#include "clang/Basic/IdentifierTable.h"
20#include "clang/Basic/LLVM.h"
21#include "clang/Basic/SourceLocation.h"
22#include "clang/Basic/Specifiers.h"
23#include "llvm/ADT/ArrayRef.h"
24#include "llvm/ADT/PointerIntPair.h"
25#include "llvm/ADT/PointerUnion.h"
26#include "llvm/ADT/iterator.h"
27#include "llvm/ADT/iterator_range.h"
28#include "llvm/Support/Casting.h"
29#include "llvm/Support/Compiler.h"
30#include "llvm/Support/PrettyStackTrace.h"
31#include "llvm/Support/VersionTuple.h"
32#include <algorithm>
33#include <cassert>
34#include <cstddef>
35#include <iterator>
36#include <string>
37#include <type_traits>
38#include <utility>
39
40namespace clang {
41
42class ASTContext;
43class ASTMutationListener;
44class Attr;
45class BlockDecl;
46class DeclContext;
47class ExternalSourceSymbolAttr;
48class FunctionDecl;
49class FunctionType;
50class IdentifierInfo;
51enum Linkage : unsigned char;
52class LinkageSpecDecl;
53class Module;
54class NamedDecl;
55class ObjCCategoryDecl;
56class ObjCCategoryImplDecl;
57class ObjCContainerDecl;
58class ObjCImplDecl;
59class ObjCImplementationDecl;
60class ObjCInterfaceDecl;
61class ObjCMethodDecl;
62class ObjCProtocolDecl;
63struct PrintingPolicy;
64class RecordDecl;
65class SourceManager;
66class Stmt;
67class StoredDeclsMap;
68class TemplateDecl;
69class TranslationUnitDecl;
70class UsingDirectiveDecl;
71
72/// Captures the result of checking the availability of a
73/// declaration.
74enum AvailabilityResult {
75 AR_Available = 0,
76 AR_NotYetIntroduced,
77 AR_Deprecated,
78 AR_Unavailable
79};
80
81/// Decl - This represents one declaration (or definition), e.g. a variable,
82/// typedef, function, struct, etc.
83///
84/// Note: There are objects tacked on before the *beginning* of Decl
85/// (and its subclasses) in its Decl::operator new(). Proper alignment
86/// of all subclasses (not requiring more than the alignment of Decl) is
87/// asserted in DeclBase.cpp.
88class alignas(8) Decl {
89public:
90 /// Lists the kind of concrete classes of Decl.
91 enum Kind {
92#define DECL(DERIVED, BASE) DERIVED,
93#define ABSTRACT_DECL(DECL)
94#define DECL_RANGE(BASE, START, END) \
95 first##BASE = START, last##BASE = END,
96#define LAST_DECL_RANGE(BASE, START, END) \
97 first##BASE = START, last##BASE = END
98#include "clang/AST/DeclNodes.inc"
99 };
100
101 /// A placeholder type used to construct an empty shell of a
102 /// decl-derived type that will be filled in later (e.g., by some
103 /// deserialization method).
104 struct EmptyShell {};
105
106 /// IdentifierNamespace - The different namespaces in which
107 /// declarations may appear. According to C99 6.2.3, there are
108 /// four namespaces, labels, tags, members and ordinary
109 /// identifiers. C++ describes lookup completely differently:
110 /// certain lookups merely "ignore" certain kinds of declarations,
111 /// usually based on whether the declaration is of a type, etc.
112 ///
113 /// These are meant as bitmasks, so that searches in
114 /// C++ can look into the "tag" namespace during ordinary lookup.
115 ///
116 /// Decl currently provides 15 bits of IDNS bits.
117 enum IdentifierNamespace {
118 /// Labels, declared with 'x:' and referenced with 'goto x'.
119 IDNS_Label = 0x0001,
120
121 /// Tags, declared with 'struct foo;' and referenced with
122 /// 'struct foo'. All tags are also types. This is what
123 /// elaborated-type-specifiers look for in C.
124 /// This also contains names that conflict with tags in the
125 /// same scope but that are otherwise ordinary names (non-type
126 /// template parameters and indirect field declarations).
127 IDNS_Tag = 0x0002,
128
129 /// Types, declared with 'struct foo', typedefs, etc.
130 /// This is what elaborated-type-specifiers look for in C++,
131 /// but note that it's ill-formed to find a non-tag.
132 IDNS_Type = 0x0004,
133
134 /// Members, declared with object declarations within tag
135 /// definitions. In C, these can only be found by "qualified"
136 /// lookup in member expressions. In C++, they're found by
137 /// normal lookup.
138 IDNS_Member = 0x0008,
139
140 /// Namespaces, declared with 'namespace foo {}'.
141 /// Lookup for nested-name-specifiers find these.
142 IDNS_Namespace = 0x0010,
143
144 /// Ordinary names. In C, everything that's not a label, tag,
145 /// member, or function-local extern ends up here.
146 IDNS_Ordinary = 0x0020,
147
148 /// Objective C \@protocol.
149 IDNS_ObjCProtocol = 0x0040,
150
151 /// This declaration is a friend function. A friend function
152 /// declaration is always in this namespace but may also be in
153 /// IDNS_Ordinary if it was previously declared.
154 IDNS_OrdinaryFriend = 0x0080,
155
156 /// This declaration is a friend class. A friend class
157 /// declaration is always in this namespace but may also be in
158 /// IDNS_Tag|IDNS_Type if it was previously declared.
159 IDNS_TagFriend = 0x0100,
160
161 /// This declaration is a using declaration. A using declaration
162 /// *introduces* a number of other declarations into the current
163 /// scope, and those declarations use the IDNS of their targets,
164 /// but the actual using declarations go in this namespace.
165 IDNS_Using = 0x0200,
166
167 /// This declaration is a C++ operator declared in a non-class
168 /// context. All such operators are also in IDNS_Ordinary.
169 /// C++ lexical operator lookup looks for these.
170 IDNS_NonMemberOperator = 0x0400,
171
172 /// This declaration is a function-local extern declaration of a
173 /// variable or function. This may also be IDNS_Ordinary if it
174 /// has been declared outside any function. These act mostly like
175 /// invisible friend declarations, but are also visible to unqualified
176 /// lookup within the scope of the declaring function.
177 IDNS_LocalExtern = 0x0800,
178
179 /// This declaration is an OpenMP user defined reduction construction.
180 IDNS_OMPReduction = 0x1000,
181
182 /// This declaration is an OpenMP user defined mapper.
183 IDNS_OMPMapper = 0x2000,
184 };
185
186 /// ObjCDeclQualifier - 'Qualifiers' written next to the return and
187 /// parameter types in method declarations. Other than remembering
188 /// them and mangling them into the method's signature string, these
189 /// are ignored by the compiler; they are consumed by certain
190 /// remote-messaging frameworks.
191 ///
192 /// in, inout, and out are mutually exclusive and apply only to
193 /// method parameters. bycopy and byref are mutually exclusive and
194 /// apply only to method parameters (?). oneway applies only to
195 /// results. All of these expect their corresponding parameter to
196 /// have a particular type. None of this is currently enforced by
197 /// clang.
198 ///
199 /// This should be kept in sync with ObjCDeclSpec::ObjCDeclQualifier.
200 enum ObjCDeclQualifier {
201 OBJC_TQ_None = 0x0,
202 OBJC_TQ_In = 0x1,
203 OBJC_TQ_Inout = 0x2,
204 OBJC_TQ_Out = 0x4,
205 OBJC_TQ_Bycopy = 0x8,
206 OBJC_TQ_Byref = 0x10,
207 OBJC_TQ_Oneway = 0x20,
208
209 /// The nullability qualifier is set when the nullability of the
210 /// result or parameter was expressed via a context-sensitive
211 /// keyword.
212 OBJC_TQ_CSNullability = 0x40
213 };
214
215 /// The kind of ownership a declaration has, for visibility purposes.
216 /// This enumeration is designed such that higher values represent higher
217 /// levels of name hiding.
218 enum class ModuleOwnershipKind : unsigned {
219 /// This declaration is not owned by a module.
220 Unowned,
221
222 /// This declaration has an owning module, but is globally visible
223 /// (typically because its owning module is visible and we know that
224 /// modules cannot later become hidden in this compilation).
225 /// After serialization and deserialization, this will be converted
226 /// to VisibleWhenImported.
227 Visible,
228
229 /// This declaration has an owning module, and is visible when that
230 /// module is imported.
231 VisibleWhenImported,
232
233 /// This declaration has an owning module, but is only visible to
234 /// lookups that occur within that module.
235 ModulePrivate
236 };
237
238protected:
239 /// The next declaration within the same lexical
240 /// DeclContext. These pointers form the linked list that is
241 /// traversed via DeclContext's decls_begin()/decls_end().
242 ///
243 /// The extra two bits are used for the ModuleOwnershipKind.
244 llvm::PointerIntPair<Decl *, 2, ModuleOwnershipKind> NextInContextAndBits;
245
246private:
247 friend class DeclContext;
248
249 struct MultipleDC {
250 DeclContext *SemanticDC;
251 DeclContext *LexicalDC;
252 };
253
254 /// DeclCtx - Holds either a DeclContext* or a MultipleDC*.
255 /// For declarations that don't contain C++ scope specifiers, it contains
256 /// the DeclContext where the Decl was declared.
257 /// For declarations with C++ scope specifiers, it contains a MultipleDC*
258 /// with the context where it semantically belongs (SemanticDC) and the
259 /// context where it was lexically declared (LexicalDC).
260 /// e.g.:
261 ///
262 /// namespace A {
263 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
264 /// }
265 /// void A::f(); // SemanticDC == namespace 'A'
266 /// // LexicalDC == global namespace
267 llvm::PointerUnion<DeclContext*, MultipleDC*> DeclCtx;
268
269 bool isInSemaDC() const { return DeclCtx.is<DeclContext*>(); }
270 bool isOutOfSemaDC() const { return DeclCtx.is<MultipleDC*>(); }
271
272 MultipleDC *getMultipleDC() const {
273 return DeclCtx.get<MultipleDC*>();
274 }
275
276 DeclContext *getSemanticDC() const {
277 return DeclCtx.get<DeclContext*>();
278 }
279
280 /// Loc - The location of this decl.
281 SourceLocation Loc;
282
283 /// DeclKind - This indicates which class this is.
284 unsigned DeclKind : 7;
285
286 /// InvalidDecl - This indicates a semantic error occurred.
287 unsigned InvalidDecl : 1;
288
289 /// HasAttrs - This indicates whether the decl has attributes or not.
290 unsigned HasAttrs : 1;
291
292 /// Implicit - Whether this declaration was implicitly generated by
293 /// the implementation rather than explicitly written by the user.
294 unsigned Implicit : 1;
295
296 /// Whether this declaration was "used", meaning that a definition is
297 /// required.
298 unsigned Used : 1;
299
300 /// Whether this declaration was "referenced".
301 /// The difference with 'Used' is whether the reference appears in a
302 /// evaluated context or not, e.g. functions used in uninstantiated templates
303 /// are regarded as "referenced" but not "used".
304 unsigned Referenced : 1;
305
306 /// Whether this declaration is a top-level declaration (function,
307 /// global variable, etc.) that is lexically inside an objc container
308 /// definition.
309 unsigned TopLevelDeclInObjCContainer : 1;
310
311 /// Whether statistic collection is enabled.
312 static bool StatisticsEnabled;
313
314protected:
315 friend class ASTDeclReader;
316 friend class ASTDeclWriter;
317 friend class ASTNodeImporter;
318 friend class ASTReader;
319 friend class CXXClassMemberWrapper;
320 friend class LinkageComputer;
321 template<typename decl_type> friend class Redeclarable;
322
323 /// Access - Used by C++ decls for the access specifier.
324 // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum
325 unsigned Access : 2;
326
327 /// Whether this declaration was loaded from an AST file.
328 unsigned FromASTFile : 1;
329
330 /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in.
331 unsigned IdentifierNamespace : 14;
332
333 /// If 0, we have not computed the linkage of this declaration.
334 /// Otherwise, it is the linkage + 1.
335 mutable unsigned CacheValidAndLinkage : 3;
336
337 /// Allocate memory for a deserialized declaration.
338 ///
339 /// This routine must be used to allocate memory for any declaration that is
340 /// deserialized from a module file.
341 ///
342 /// \param Size The size of the allocated object.
343 /// \param Ctx The context in which we will allocate memory.
344 /// \param ID The global ID of the deserialized declaration.
345 /// \param Extra The amount of extra space to allocate after the object.
346 void *operator new(std::size_t Size, const ASTContext &Ctx, unsigned ID,
347 std::size_t Extra = 0);
348
349 /// Allocate memory for a non-deserialized declaration.
350 void *operator new(std::size_t Size, const ASTContext &Ctx,
351 DeclContext *Parent, std::size_t Extra = 0);
352
353private:
354 bool AccessDeclContextSanity() const;
355
356 /// Get the module ownership kind to use for a local lexical child of \p DC,
357 /// which may be either a local or (rarely) an imported declaration.
358 static ModuleOwnershipKind getModuleOwnershipKindForChildOf(DeclContext *DC) {
359 if (DC) {
360 auto *D = cast<Decl>(DC);
361 auto MOK = D->getModuleOwnershipKind();
362 if (MOK != ModuleOwnershipKind::Unowned &&
363 (!D->isFromASTFile() || D->hasLocalOwningModuleStorage()))
364 return MOK;
365 // If D is not local and we have no local module storage, then we don't
366 // need to track module ownership at all.
367 }
368 return ModuleOwnershipKind::Unowned;
369 }
370
371public:
372 Decl() = delete;
373 Decl(const Decl&) = delete;
374 Decl(Decl &&) = delete;
375 Decl &operator=(const Decl&) = delete;
376 Decl &operator=(Decl&&) = delete;
377
378protected:
379 Decl(Kind DK, DeclContext *DC, SourceLocation L)
380 : NextInContextAndBits(nullptr, getModuleOwnershipKindForChildOf(DC)),
381 DeclCtx(DC), Loc(L), DeclKind(DK), InvalidDecl(false), HasAttrs(false),
382 Implicit(false), Used(false), Referenced(false),
383 TopLevelDeclInObjCContainer(false), Access(AS_none), FromASTFile(0),
384 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
385 CacheValidAndLinkage(0) {
386 if (StatisticsEnabled) add(DK);
387 }
388
389 Decl(Kind DK, EmptyShell Empty)
390 : DeclKind(DK), InvalidDecl(false), HasAttrs(false), Implicit(false),
391 Used(false), Referenced(false), TopLevelDeclInObjCContainer(false),
392 Access(AS_none), FromASTFile(0),
393 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
394 CacheValidAndLinkage(0) {
395 if (StatisticsEnabled) add(DK);
396 }
397
398 virtual ~Decl();
399
400 /// Update a potentially out-of-date declaration.
401 void updateOutOfDate(IdentifierInfo &II) const;
402
403 Linkage getCachedLinkage() const {
404 return Linkage(CacheValidAndLinkage - 1);
405 }
406
407 void setCachedLinkage(Linkage L) const {
408 CacheValidAndLinkage = L + 1;
409 }
410
411 bool hasCachedLinkage() const {
412 return CacheValidAndLinkage;
413 }
414
415public:
416 /// Source range that this declaration covers.
417 virtual SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) {
418 return SourceRange(getLocation(), getLocation());
419 }
420
421 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
422 return getSourceRange().getBegin();
423 }
424
425 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
426 return getSourceRange().getEnd();
427 }
428
429 SourceLocation getLocation() const { return Loc; }
430 void setLocation(SourceLocation L) { Loc = L; }
431
432 Kind getKind() const { return static_cast<Kind>(DeclKind); }
433 const char *getDeclKindName() const;
434
435 Decl *getNextDeclInContext() { return NextInContextAndBits.getPointer(); }
436 const Decl *getNextDeclInContext() const {return NextInContextAndBits.getPointer();}
437
438 DeclContext *getDeclContext() {
439 if (isInSemaDC())
440 return getSemanticDC();
441 return getMultipleDC()->SemanticDC;
442 }
443 const DeclContext *getDeclContext() const {
444 return const_cast<Decl*>(this)->getDeclContext();
445 }
446
447 /// Find the innermost non-closure ancestor of this declaration,
448 /// walking up through blocks, lambdas, etc. If that ancestor is
449 /// not a code context (!isFunctionOrMethod()), returns null.
450 ///
451 /// A declaration may be its own non-closure context.
452 Decl *getNonClosureContext();
453 const Decl *getNonClosureContext() const {
454 return const_cast<Decl*>(this)->getNonClosureContext();
455 }
456
457 TranslationUnitDecl *getTranslationUnitDecl();
458 const TranslationUnitDecl *getTranslationUnitDecl() const {
459 return const_cast<Decl*>(this)->getTranslationUnitDecl();
460 }
461
462 bool isInAnonymousNamespace() const;
463
464 bool isInStdNamespace() const;
465
466 ASTContext &getASTContext() const LLVM_READONLY__attribute__((__pure__));
467
468 void setAccess(AccessSpecifier AS) {
469 Access = AS;
470 assert(AccessDeclContextSanity())((AccessDeclContextSanity()) ? static_cast<void> (0) : __assert_fail
("AccessDeclContextSanity()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 470, __PRETTY_FUNCTION__))
;
471 }
472
473 AccessSpecifier getAccess() const {
474 assert(AccessDeclContextSanity())((AccessDeclContextSanity()) ? static_cast<void> (0) : __assert_fail
("AccessDeclContextSanity()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 474, __PRETTY_FUNCTION__))
;
475 return AccessSpecifier(Access);
476 }
477
478 /// Retrieve the access specifier for this declaration, even though
479 /// it may not yet have been properly set.
480 AccessSpecifier getAccessUnsafe() const {
481 return AccessSpecifier(Access);
482 }
483
484 bool hasAttrs() const { return HasAttrs; }
485
486 void setAttrs(const AttrVec& Attrs) {
487 return setAttrsImpl(Attrs, getASTContext());
488 }
489
490 AttrVec &getAttrs() {
491 return const_cast<AttrVec&>(const_cast<const Decl*>(this)->getAttrs());
492 }
493
494 const AttrVec &getAttrs() const;
495 void dropAttrs();
496 void addAttr(Attr *A);
497
498 using attr_iterator = AttrVec::const_iterator;
499 using attr_range = llvm::iterator_range<attr_iterator>;
500
501 attr_range attrs() const {
502 return attr_range(attr_begin(), attr_end());
503 }
504
505 attr_iterator attr_begin() const {
506 return hasAttrs() ? getAttrs().begin() : nullptr;
507 }
508 attr_iterator attr_end() const {
509 return hasAttrs() ? getAttrs().end() : nullptr;
510 }
511
512 template <typename T>
513 void dropAttr() {
514 if (!HasAttrs) return;
515
516 AttrVec &Vec = getAttrs();
517 Vec.erase(std::remove_if(Vec.begin(), Vec.end(), isa<T, Attr*>), Vec.end());
518
519 if (Vec.empty())
520 HasAttrs = false;
521 }
522
523 template <typename T>
524 llvm::iterator_range<specific_attr_iterator<T>> specific_attrs() const {
525 return llvm::make_range(specific_attr_begin<T>(), specific_attr_end<T>());
526 }
527
528 template <typename T>
529 specific_attr_iterator<T> specific_attr_begin() const {
530 return specific_attr_iterator<T>(attr_begin());
531 }
532
533 template <typename T>
534 specific_attr_iterator<T> specific_attr_end() const {
535 return specific_attr_iterator<T>(attr_end());
536 }
537
538 template<typename T> T *getAttr() const {
539 return hasAttrs() ? getSpecificAttr<T>(getAttrs()) : nullptr;
540 }
541
542 template<typename T> bool hasAttr() const {
543 return hasAttrs() && hasSpecificAttr<T>(getAttrs());
544 }
545
546 /// getMaxAlignment - return the maximum alignment specified by attributes
547 /// on this decl, 0 if there are none.
548 unsigned getMaxAlignment() const;
549
550 /// setInvalidDecl - Indicates the Decl had a semantic error. This
551 /// allows for graceful error recovery.
552 void setInvalidDecl(bool Invalid = true);
553 bool isInvalidDecl() const { return (bool) InvalidDecl; }
554
555 /// isImplicit - Indicates whether the declaration was implicitly
556 /// generated by the implementation. If false, this declaration
557 /// was written explicitly in the source code.
558 bool isImplicit() const { return Implicit; }
559 void setImplicit(bool I = true) { Implicit = I; }
560
561 /// Whether *any* (re-)declaration of the entity was used, meaning that
562 /// a definition is required.
563 ///
564 /// \param CheckUsedAttr When true, also consider the "used" attribute
565 /// (in addition to the "used" bit set by \c setUsed()) when determining
566 /// whether the function is used.
567 bool isUsed(bool CheckUsedAttr = true) const;
568
569 /// Set whether the declaration is used, in the sense of odr-use.
570 ///
571 /// This should only be used immediately after creating a declaration.
572 /// It intentionally doesn't notify any listeners.
573 void setIsUsed() { getCanonicalDecl()->Used = true; }
574
575 /// Mark the declaration used, in the sense of odr-use.
576 ///
577 /// This notifies any mutation listeners in addition to setting a bit
578 /// indicating the declaration is used.
579 void markUsed(ASTContext &C);
580
581 /// Whether any declaration of this entity was referenced.
582 bool isReferenced() const;
583
584 /// Whether this declaration was referenced. This should not be relied
585 /// upon for anything other than debugging.
586 bool isThisDeclarationReferenced() const { return Referenced; }
587
588 void setReferenced(bool R = true) { Referenced = R; }
589
590 /// Whether this declaration is a top-level declaration (function,
591 /// global variable, etc.) that is lexically inside an objc container
592 /// definition.
593 bool isTopLevelDeclInObjCContainer() const {
594 return TopLevelDeclInObjCContainer;
595 }
596
597 void setTopLevelDeclInObjCContainer(bool V = true) {
598 TopLevelDeclInObjCContainer = V;
599 }
600
601 /// Looks on this and related declarations for an applicable
602 /// external source symbol attribute.
603 ExternalSourceSymbolAttr *getExternalSourceSymbolAttr() const;
604
605 /// Whether this declaration was marked as being private to the
606 /// module in which it was defined.
607 bool isModulePrivate() const {
608 return getModuleOwnershipKind() == ModuleOwnershipKind::ModulePrivate;
609 }
610
611 /// Return true if this declaration has an attribute which acts as
612 /// definition of the entity, such as 'alias' or 'ifunc'.
613 bool hasDefiningAttr() const;
614
615 /// Return this declaration's defining attribute if it has one.
616 const Attr *getDefiningAttr() const;
617
618protected:
619 /// Specify that this declaration was marked as being private
620 /// to the module in which it was defined.
621 void setModulePrivate() {
622 // The module-private specifier has no effect on unowned declarations.
623 // FIXME: We should track this in some way for source fidelity.
624 if (getModuleOwnershipKind() == ModuleOwnershipKind::Unowned)
625 return;
626 setModuleOwnershipKind(ModuleOwnershipKind::ModulePrivate);
627 }
628
629 /// Set the owning module ID.
630 void setOwningModuleID(unsigned ID) {
631 assert(isFromASTFile() && "Only works on a deserialized declaration")((isFromASTFile() && "Only works on a deserialized declaration"
) ? static_cast<void> (0) : __assert_fail ("isFromASTFile() && \"Only works on a deserialized declaration\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 631, __PRETTY_FUNCTION__))
;
632 *((unsigned*)this - 2) = ID;
633 }
634
635public:
636 /// Determine the availability of the given declaration.
637 ///
638 /// This routine will determine the most restrictive availability of
639 /// the given declaration (e.g., preferring 'unavailable' to
640 /// 'deprecated').
641 ///
642 /// \param Message If non-NULL and the result is not \c
643 /// AR_Available, will be set to a (possibly empty) message
644 /// describing why the declaration has not been introduced, is
645 /// deprecated, or is unavailable.
646 ///
647 /// \param EnclosingVersion The version to compare with. If empty, assume the
648 /// deployment target version.
649 ///
650 /// \param RealizedPlatform If non-NULL and the availability result is found
651 /// in an available attribute it will set to the platform which is written in
652 /// the available attribute.
653 AvailabilityResult
654 getAvailability(std::string *Message = nullptr,
655 VersionTuple EnclosingVersion = VersionTuple(),
656 StringRef *RealizedPlatform = nullptr) const;
657
658 /// Retrieve the version of the target platform in which this
659 /// declaration was introduced.
660 ///
661 /// \returns An empty version tuple if this declaration has no 'introduced'
662 /// availability attributes, or the version tuple that's specified in the
663 /// attribute otherwise.
664 VersionTuple getVersionIntroduced() const;
665
666 /// Determine whether this declaration is marked 'deprecated'.
667 ///
668 /// \param Message If non-NULL and the declaration is deprecated,
669 /// this will be set to the message describing why the declaration
670 /// was deprecated (which may be empty).
671 bool isDeprecated(std::string *Message = nullptr) const {
672 return getAvailability(Message) == AR_Deprecated;
673 }
674
675 /// Determine whether this declaration is marked 'unavailable'.
676 ///
677 /// \param Message If non-NULL and the declaration is unavailable,
678 /// this will be set to the message describing why the declaration
679 /// was made unavailable (which may be empty).
680 bool isUnavailable(std::string *Message = nullptr) const {
681 return getAvailability(Message) == AR_Unavailable;
682 }
683
684 /// Determine whether this is a weak-imported symbol.
685 ///
686 /// Weak-imported symbols are typically marked with the
687 /// 'weak_import' attribute, but may also be marked with an
688 /// 'availability' attribute where we're targing a platform prior to
689 /// the introduction of this feature.
690 bool isWeakImported() const;
691
692 /// Determines whether this symbol can be weak-imported,
693 /// e.g., whether it would be well-formed to add the weak_import
694 /// attribute.
695 ///
696 /// \param IsDefinition Set to \c true to indicate that this
697 /// declaration cannot be weak-imported because it has a definition.
698 bool canBeWeakImported(bool &IsDefinition) const;
699
700 /// Determine whether this declaration came from an AST file (such as
701 /// a precompiled header or module) rather than having been parsed.
702 bool isFromASTFile() const { return FromASTFile; }
703
704 /// Retrieve the global declaration ID associated with this
705 /// declaration, which specifies where this Decl was loaded from.
706 unsigned getGlobalID() const {
707 if (isFromASTFile())
708 return *((const unsigned*)this - 1);
709 return 0;
710 }
711
712 /// Retrieve the global ID of the module that owns this particular
713 /// declaration.
714 unsigned getOwningModuleID() const {
715 if (isFromASTFile())
716 return *((const unsigned*)this - 2);
717 return 0;
718 }
719
720private:
721 Module *getOwningModuleSlow() const;
722
723protected:
724 bool hasLocalOwningModuleStorage() const;
725
726public:
727 /// Get the imported owning module, if this decl is from an imported
728 /// (non-local) module.
729 Module *getImportedOwningModule() const {
730 if (!isFromASTFile() || !hasOwningModule())
731 return nullptr;
732
733 return getOwningModuleSlow();
734 }
735
736 /// Get the local owning module, if known. Returns nullptr if owner is
737 /// not yet known or declaration is not from a module.
738 Module *getLocalOwningModule() const {
739 if (isFromASTFile() || !hasOwningModule())
740 return nullptr;
741
742 assert(hasLocalOwningModuleStorage() &&((hasLocalOwningModuleStorage() && "owned local decl but no local module storage"
) ? static_cast<void> (0) : __assert_fail ("hasLocalOwningModuleStorage() && \"owned local decl but no local module storage\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 743, __PRETTY_FUNCTION__))
743 "owned local decl but no local module storage")((hasLocalOwningModuleStorage() && "owned local decl but no local module storage"
) ? static_cast<void> (0) : __assert_fail ("hasLocalOwningModuleStorage() && \"owned local decl but no local module storage\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 743, __PRETTY_FUNCTION__))
;
744 return reinterpret_cast<Module *const *>(this)[-1];
745 }
746 void setLocalOwningModule(Module *M) {
747 assert(!isFromASTFile() && hasOwningModule() &&((!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage
() && "should not have a cached owning module") ? static_cast
<void> (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 749, __PRETTY_FUNCTION__))
748 hasLocalOwningModuleStorage() &&((!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage
() && "should not have a cached owning module") ? static_cast
<void> (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 749, __PRETTY_FUNCTION__))
749 "should not have a cached owning module")((!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage
() && "should not have a cached owning module") ? static_cast
<void> (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 749, __PRETTY_FUNCTION__))
;
750 reinterpret_cast<Module **>(this)[-1] = M;
751 }
752
753 /// Is this declaration owned by some module?
754 bool hasOwningModule() const {
755 return getModuleOwnershipKind() != ModuleOwnershipKind::Unowned;
756 }
757
758 /// Get the module that owns this declaration (for visibility purposes).
759 Module *getOwningModule() const {
760 return isFromASTFile() ? getImportedOwningModule() : getLocalOwningModule();
761 }
762
763 /// Get the module that owns this declaration for linkage purposes.
764 /// There only ever is such a module under the C++ Modules TS.
765 ///
766 /// \param IgnoreLinkage Ignore the linkage of the entity; assume that
767 /// all declarations in a global module fragment are unowned.
768 Module *getOwningModuleForLinkage(bool IgnoreLinkage = false) const;
769
770 /// Determine whether this declaration might be hidden from name
771 /// lookup. Note that the declaration might be visible even if this returns
772 /// \c false, if the owning module is visible within the query context.
773 // FIXME: Rename this to make it clearer what it does.
774 bool isHidden() const {
775 return (int)getModuleOwnershipKind() > (int)ModuleOwnershipKind::Visible;
776 }
777
778 /// Set that this declaration is globally visible, even if it came from a
779 /// module that is not visible.
780 void setVisibleDespiteOwningModule() {
781 if (isHidden())
782 setModuleOwnershipKind(ModuleOwnershipKind::Visible);
783 }
784
785 /// Get the kind of module ownership for this declaration.
786 ModuleOwnershipKind getModuleOwnershipKind() const {
787 return NextInContextAndBits.getInt();
788 }
789
790 /// Set whether this declaration is hidden from name lookup.
791 void setModuleOwnershipKind(ModuleOwnershipKind MOK) {
792 assert(!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&((!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&
MOK != ModuleOwnershipKind::Unowned && !isFromASTFile
() && !hasLocalOwningModuleStorage()) && "no storage available for owning module for this declaration"
) ? static_cast<void> (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 795, __PRETTY_FUNCTION__))
793 MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() &&((!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&
MOK != ModuleOwnershipKind::Unowned && !isFromASTFile
() && !hasLocalOwningModuleStorage()) && "no storage available for owning module for this declaration"
) ? static_cast<void> (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 795, __PRETTY_FUNCTION__))
794 !hasLocalOwningModuleStorage()) &&((!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&
MOK != ModuleOwnershipKind::Unowned && !isFromASTFile
() && !hasLocalOwningModuleStorage()) && "no storage available for owning module for this declaration"
) ? static_cast<void> (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 795, __PRETTY_FUNCTION__))
795 "no storage available for owning module for this declaration")((!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&
MOK != ModuleOwnershipKind::Unowned && !isFromASTFile
() && !hasLocalOwningModuleStorage()) && "no storage available for owning module for this declaration"
) ? static_cast<void> (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 795, __PRETTY_FUNCTION__))
;
796 NextInContextAndBits.setInt(MOK);
797 }
798
799 unsigned getIdentifierNamespace() const {
800 return IdentifierNamespace;
801