Coverage Report

Created: 2024-01-17 10:31

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