Coverage Report

Created: 2021-08-24 07:12

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Sema/SemaDeclObjC.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- SemaDeclObjC.cpp - Semantic Analysis for ObjC Declarations -------===//
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 semantic analysis for Objective C declarations.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "TypeLocBuilder.h"
14
#include "clang/AST/ASTConsumer.h"
15
#include "clang/AST/ASTContext.h"
16
#include "clang/AST/ASTMutationListener.h"
17
#include "clang/AST/DeclObjC.h"
18
#include "clang/AST/Expr.h"
19
#include "clang/AST/ExprObjC.h"
20
#include "clang/AST/RecursiveASTVisitor.h"
21
#include "clang/Basic/SourceManager.h"
22
#include "clang/Basic/TargetInfo.h"
23
#include "clang/Sema/DeclSpec.h"
24
#include "clang/Sema/Lookup.h"
25
#include "clang/Sema/Scope.h"
26
#include "clang/Sema/ScopeInfo.h"
27
#include "clang/Sema/SemaInternal.h"
28
#include "llvm/ADT/DenseMap.h"
29
#include "llvm/ADT/DenseSet.h"
30
31
using namespace clang;
32
33
/// Check whether the given method, which must be in the 'init'
34
/// family, is a valid member of that family.
35
///
36
/// \param receiverTypeIfCall - if null, check this as if declaring it;
37
///   if non-null, check this as if making a call to it with the given
38
///   receiver type
39
///
40
/// \return true to indicate that there was an error and appropriate
41
///   actions were taken
42
bool Sema::checkInitMethod(ObjCMethodDecl *method,
43
2.07k
                           QualType receiverTypeIfCall) {
44
2.07k
  if (method->isInvalidDecl()) 
return true0
;
45
46
  // This castAs is safe: methods that don't return an object
47
  // pointer won't be inferred as inits and will reject an explicit
48
  // objc_method_family(init).
49
50
  // We ignore protocols here.  Should we?  What about Class?
51
52
2.07k
  const ObjCObjectType *result =
53
2.07k
      method->getReturnType()->castAs<ObjCObjectPointerType>()->getObjectType();
54
55
2.07k
  if (result->isObjCId()) {
56
1.85k
    return false;
57
1.85k
  } else 
if (217
result->isObjCClass()217
) {
58
    // fall through: always an error
59
217
  } else {
60
217
    ObjCInterfaceDecl *resultClass = result->getInterface();
61
217
    assert(resultClass && "unexpected object type!");
62
63
    // It's okay for the result type to still be a forward declaration
64
    // if we're checking an interface declaration.
65
217
    if (!resultClass->hasDefinition()) {
66
45
      if (receiverTypeIfCall.isNull() &&
67
45
          
!isa<ObjCImplementationDecl>(method->getDeclContext())42
)
68
24
        return false;
69
70
    // Otherwise, we try to compare class types.
71
172
    } else {
72
      // If this method was declared in a protocol, we can't check
73
      // anything unless we have a receiver type that's an interface.
74
172
      const ObjCInterfaceDecl *receiverClass = nullptr;
75
172
      if (isa<ObjCProtocolDecl>(method->getDeclContext())) {
76
0
        if (receiverTypeIfCall.isNull())
77
0
          return false;
78
79
0
        receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>()
80
0
          ->getInterfaceDecl();
81
82
        // This can be null for calls to e.g. id<Foo>.
83
0
        if (!receiverClass) return false;
84
172
      } else {
85
172
        receiverClass = method->getClassInterface();
86
172
        assert(receiverClass && "method not associated with a class!");
87
172
      }
88
89
      // If either class is a subclass of the other, it's fine.
90
172
      if (receiverClass->isSuperClassOf(resultClass) ||
91
172
          
resultClass->isSuperClassOf(receiverClass)72
)
92
136
        return false;
93
172
    }
94
217
  }
95
96
57
  SourceLocation loc = method->getLocation();
97
98
  // If we're in a system header, and this is not a call, just make
99
  // the method unusable.
100
57
  if (receiverTypeIfCall.isNull() && 
getSourceManager().isInSystemHeader(loc)54
) {
101
0
    method->addAttr(UnavailableAttr::CreateImplicit(Context, "",
102
0
                      UnavailableAttr::IR_ARCInitReturnsUnrelated, loc));
103
0
    return true;
104
0
  }
105
106
  // Otherwise, it's an error.
107
57
  Diag(loc, diag::err_arc_init_method_unrelated_result_type);
108
57
  method->setInvalidDecl();
109
57
  return true;
110
57
}
111
112
/// Issue a warning if the parameter of the overridden method is non-escaping
113
/// but the parameter of the overriding method is not.
114
static bool diagnoseNoescape(const ParmVarDecl *NewD, const ParmVarDecl *OldD,
115
90.3k
                             Sema &S) {
116
90.3k
  if (OldD->hasAttr<NoEscapeAttr>() && 
!NewD->hasAttr<NoEscapeAttr>()3.48k
) {
117
6
    S.Diag(NewD->getLocation(), diag::warn_overriding_method_missing_noescape);
118
6
    S.Diag(OldD->getLocation(), diag::note_overridden_marked_noescape);
119
6
    return false;
120
6
  }
121
122
90.3k
  return true;
123
90.3k
}
124
125
/// Produce additional diagnostics if a category conforms to a protocol that
126
/// defines a method taking a non-escaping parameter.
127
static void diagnoseNoescape(const ParmVarDecl *NewD, const ParmVarDecl *OldD,
128
                             const ObjCCategoryDecl *CD,
129
6
                             const ObjCProtocolDecl *PD, Sema &S) {
130
6
  if (!diagnoseNoescape(NewD, OldD, S))
131
2
    S.Diag(CD->getLocation(), diag::note_cat_conform_to_noescape_prot)
132
2
        << CD->IsClassExtension() << PD
133
2
        << cast<ObjCMethodDecl>(NewD->getDeclContext());
134
6
}
135
136
void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
137
144k
                                   const ObjCMethodDecl *Overridden) {
138
144k
  if (Overridden->hasRelatedResultType() &&
139
144k
      
!NewMethod->hasRelatedResultType()28.5k
) {
140
    // This can only happen when the method follows a naming convention that
141
    // implies a related result type, and the original (overridden) method has
142
    // a suitable return type, but the new (overriding) method does not have
143
    // a suitable return type.
144
42
    QualType ResultType = NewMethod->getReturnType();
145
42
    SourceRange ResultTypeRange = NewMethod->getReturnTypeSourceRange();
146
147
    // Figure out which class this method is part of, if any.
148
42
    ObjCInterfaceDecl *CurrentClass
149
42
      = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext());
150
42
    if (!CurrentClass) {
151
37
      DeclContext *DC = NewMethod->getDeclContext();
152
37
      if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC))
153
0
        CurrentClass = Cat->getClassInterface();
154
37
      else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC))
155
34
        CurrentClass = Impl->getClassInterface();
156
3
      else if (ObjCCategoryImplDecl *CatImpl
157
3
               = dyn_cast<ObjCCategoryImplDecl>(DC))
158
0
        CurrentClass = CatImpl->getClassInterface();
159
37
    }
160
161
42
    if (CurrentClass) {
162
39
      Diag(NewMethod->getLocation(),
163
39
           diag::warn_related_result_type_compatibility_class)
164
39
        << Context.getObjCInterfaceType(CurrentClass)
165
39
        << ResultType
166
39
        << ResultTypeRange;
167
39
    } else {
168
3
      Diag(NewMethod->getLocation(),
169
3
           diag::warn_related_result_type_compatibility_protocol)
170
3
        << ResultType
171
3
        << ResultTypeRange;
172
3
    }
173
174
42
    if (ObjCMethodFamily Family = Overridden->getMethodFamily())
175
36
      Diag(Overridden->getLocation(),
176
36
           diag::note_related_result_type_family)
177
36
        << /*overridden method*/ 0
178
36
        << Family;
179
6
    else
180
6
      Diag(Overridden->getLocation(),
181
6
           diag::note_related_result_type_overridden);
182
42
  }
183
184
144k
  if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() !=
185
144k
       Overridden->hasAttr<NSReturnsRetainedAttr>())) {
186
11
    Diag(NewMethod->getLocation(),
187
11
         getLangOpts().ObjCAutoRefCount
188
11
             ? 
diag::err_nsreturns_retained_attribute_mismatch1
189
11
             : 
diag::warn_nsreturns_retained_attribute_mismatch10
)
190
11
        << 1;
191
11
    Diag(Overridden->getLocation(), diag::note_previous_decl) << "method";
192
11
  }
193
144k
  if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() !=
194
144k
       Overridden->hasAttr<NSReturnsNotRetainedAttr>())) {
195
1
    Diag(NewMethod->getLocation(),
196
1
         getLangOpts().ObjCAutoRefCount
197
1
             ? diag::err_nsreturns_retained_attribute_mismatch
198
1
             : 
diag::warn_nsreturns_retained_attribute_mismatch0
)
199
1
        << 0;
200
1
    Diag(Overridden->getLocation(), diag::note_previous_decl)  << "method";
201
1
  }
202
203
144k
  ObjCMethodDecl::param_const_iterator oi = Overridden->param_begin(),
204
144k
                                       oe = Overridden->param_end();
205
144k
  for (ObjCMethodDecl::param_iterator ni = NewMethod->param_begin(),
206
144k
                                      ne = NewMethod->param_end();
207
235k
       ni != ne && 
oi != oe90.3k
;
++ni, ++oi90.3k
) {
208
90.3k
    const ParmVarDecl *oldDecl = (*oi);
209
90.3k
    ParmVarDecl *newDecl = (*ni);
210
90.3k
    if (newDecl->hasAttr<NSConsumedAttr>() !=
211
90.3k
        oldDecl->hasAttr<NSConsumedAttr>()) {
212
3
      Diag(newDecl->getLocation(),
213
3
           getLangOpts().ObjCAutoRefCount
214
3
               ? 
diag::err_nsconsumed_attribute_mismatch2
215
3
               : 
diag::warn_nsconsumed_attribute_mismatch1
);
216
3
      Diag(oldDecl->getLocation(), diag::note_previous_decl) << "parameter";
217
3
    }
218
219
90.3k
    diagnoseNoescape(newDecl, oldDecl, *this);
220
90.3k
  }
221
144k
}
222
223
/// Check a method declaration for compatibility with the Objective-C
224
/// ARC conventions.
225
29.3k
bool Sema::CheckARCMethodDecl(ObjCMethodDecl *method) {
226
29.3k
  ObjCMethodFamily family = method->getMethodFamily();
227
29.3k
  switch (family) {
228
25.9k
  case OMF_None:
229
26.0k
  case OMF_finalize:
230
26.1k
  case OMF_retain:
231
26.3k
  case OMF_release:
232
26.4k
  case OMF_autorelease:
233
26.5k
  case OMF_retainCount:
234
26.5k
  case OMF_self:
235
26.5k
  case OMF_initialize:
236
26.5k
  case OMF_performSelector:
237
26.5k
    return false;
238
239
236
  case OMF_dealloc:
240
236
    if (!Context.hasSameType(method->getReturnType(), Context.VoidTy)) {
241
4
      SourceRange ResultTypeRange = method->getReturnTypeSourceRange();
242
4
      if (ResultTypeRange.isInvalid())
243
2
        Diag(method->getLocation(), diag::err_dealloc_bad_result_type)
244
2
            << method->getReturnType()
245
2
            << FixItHint::CreateInsertion(method->getSelectorLoc(0), "(void)");
246
2
      else
247
2
        Diag(method->getLocation(), diag::err_dealloc_bad_result_type)
248
2
            << method->getReturnType()
249
2
            << FixItHint::CreateReplacement(ResultTypeRange, "void");
250
4
      return true;
251
4
    }
252
232
    return false;
253
254
1.87k
  case OMF_init:
255
    // If the method doesn't obey the init rules, don't bother annotating it.
256
1.87k
    if (checkInitMethod(method, QualType()))
257
54
      return true;
258
259
1.81k
    method->addAttr(NSConsumesSelfAttr::CreateImplicit(Context));
260
261
    // Don't add a second copy of this attribute, but otherwise don't
262
    // let it be suppressed.
263
1.81k
    if (method->hasAttr<NSReturnsRetainedAttr>())
264
479
      return false;
265
1.33k
    break;
266
267
1.33k
  case OMF_alloc:
268
300
  case OMF_copy:
269
405
  case OMF_mutableCopy:
270
672
  case OMF_new:
271
672
    if (method->hasAttr<NSReturnsRetainedAttr>() ||
272
672
        
method->hasAttr<NSReturnsNotRetainedAttr>()590
||
273
672
        
method->hasAttr<NSReturnsAutoreleasedAttr>()583
)
274
89
      return false;
275
583
    break;
276
29.3k
  }
277
278
1.92k
  method->addAttr(NSReturnsRetainedAttr::CreateImplicit(Context));
279
1.92k
  return false;
280
29.3k
}
281
282
static void DiagnoseObjCImplementedDeprecations(Sema &S, const NamedDecl *ND,
283
6.27k
                                                SourceLocation ImplLoc) {
284
6.27k
  if (!ND)
285
0
    return;
286
6.27k
  bool IsCategory = false;
287
6.27k
  StringRef RealizedPlatform;
288
6.27k
  AvailabilityResult Availability = ND->getAvailability(
289
6.27k
      /*Message=*/nullptr, /*EnclosingVersion=*/VersionTuple(),
290
6.27k
      &RealizedPlatform);
291
6.27k
  if (Availability != AR_Deprecated) {
292
6.26k
    if (isa<ObjCMethodDecl>(ND)) {
293
956
      if (Availability != AR_Unavailable)
294
944
        return;
295
12
      if (RealizedPlatform.empty())
296
7
        RealizedPlatform = S.Context.getTargetInfo().getPlatformName();
297
      // Warn about implementing unavailable methods, unless the unavailable
298
      // is for an app extension.
299
12
      if (RealizedPlatform.endswith("_app_extension"))
300
2
        return;
301
10
      S.Diag(ImplLoc, diag::warn_unavailable_def);
302
10
      S.Diag(ND->getLocation(), diag::note_method_declared_at)
303
10
          << ND->getDeclName();
304
10
      return;
305
12
    }
306
5.30k
    if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND)) {
307
499
      if (!CD->getClassInterface()->isDeprecated())
308
496
        return;
309
3
      ND = CD->getClassInterface();
310
3
      IsCategory = true;
311
3
    } else
312
4.80k
      return;
313
5.30k
  }
314
16
  S.Diag(ImplLoc, diag::warn_deprecated_def)
315
16
      << (isa<ObjCMethodDecl>(ND)
316
16
              ? /*Method*/ 
07
317
16
              : 
isa<ObjCCategoryDecl>(ND)9
||
IsCategory6
? /*Category*/
26
318
9
                                                        : /*Class*/ 
13
);
319
16
  if (isa<ObjCMethodDecl>(ND))
320
7
    S.Diag(ND->getLocation(), diag::note_method_declared_at)
321
7
        << ND->getDeclName();
322
9
  else
323
9
    S.Diag(ND->getLocation(), diag::note_previous_decl)
324
9
        << (isa<ObjCCategoryDecl>(ND) ? 
"category"3
:
"class"6
);
325
16
}
326
327
/// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
328
/// pool.
329
7.77k
void Sema::AddAnyMethodToGlobalPool(Decl *D) {
330
7.77k
  ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
331
332
  // If we don't have a valid method decl, simply return.
333
7.77k
  if (!MDecl)
334
0
    return;
335
7.77k
  if (MDecl->isInstanceMethod())
336
6.56k
    AddInstanceMethodToGlobalPool(MDecl, true);
337
1.21k
  else
338
1.21k
    AddFactoryMethodToGlobalPool(MDecl, true);
339
7.77k
}
340
341
/// HasExplicitOwnershipAttr - returns true when pointer to ObjC pointer
342
/// has explicit ownership attribute; false otherwise.
343
static bool
344
319
HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) {
345
319
  QualType T = Param->getType();
346
347
319
  if (const PointerType *PT = T->getAs<PointerType>()) {
348
96
    T = PT->getPointeeType();
349
223
  } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
350
4
    T = RT->getPointeeType();
351
219
  } else {
352
219
    return true;
353
219
  }
354
355
  // If we have a lifetime qualifier, but it's local, we must have
356
  // inferred it. So, it is implicit.
357
100
  return !T.getLocalQualifiers().hasObjCLifetime();
358
319
}
359
360
/// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
361
/// and user declared, in the method definition's AST.
362
7.27k
void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
363
7.27k
  ImplicitlyRetainedSelfLocs.clear();
364
7.27k
  assert((getCurMethodDecl() == nullptr) && "Methodparsing confused");
365
0
  ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
366
367
7.27k
  PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
368
369
  // If we don't have a valid method decl, simply return.
370
7.27k
  if (!MDecl)
371
0
    return;
372
373
7.27k
  QualType ResultType = MDecl->getReturnType();
374
7.27k
  if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
375
7.27k
      
!MDecl->isInvalidDecl()3.80k
&&
376
7.27k
      RequireCompleteType(MDecl->getLocation(), ResultType,
377
3.76k
                          diag::err_func_def_incomplete_result))
378
1
    MDecl->setInvalidDecl();
379
380
  // Allow all of Sema to see that we are entering a method definition.
381
7.27k
  PushDeclContext(FnBodyScope, MDecl);
382
7.27k
  PushFunctionScope();
383
384
  // Create Decl objects for each parameter, entrring them in the scope for
385
  // binding to their use.
386
387
  // Insert the invisible arguments, self and _cmd!
388
7.27k
  MDecl->createImplicitParams(Context, MDecl->getClassInterface());
389
390
7.27k
  PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
391
7.27k
  PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
392
393
  // The ObjC parser requires parameter names so there's no need to check.
394
7.27k
  CheckParmsForFunctionDef(MDecl->parameters(),
395
7.27k
                           /*CheckParameterNames=*/false);
396
397
  // Introduce all of the other parameters into this scope.
398
7.27k
  for (auto *Param : MDecl->parameters()) {
399
3.75k
    if (!Param->isInvalidDecl() &&
400
3.75k
        
getLangOpts().ObjCAutoRefCount3.75k
&&
401
3.75k
        
!HasExplicitOwnershipAttr(*this, Param)319
)
402
20
      Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) <<
403
20
            Param->getType();
404
405
3.75k
    if (Param->getIdentifier())
406
3.75k
      PushOnScopeChains(Param, FnBodyScope);
407
3.75k
  }
408
409
  // In ARC, disallow definition of retain/release/autorelease/retainCount
410
7.27k
  if (getLangOpts().ObjCAutoRefCount) {
411
922
    switch (MDecl->getMethodFamily()) {
412
5
    case OMF_retain:
413
10
    case OMF_retainCount:
414
15
    case OMF_release:
415
20
    case OMF_autorelease:
416
20
      Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def)
417
20
        << 0 << MDecl->getSelector();
418
20
      break;
419
420
572
    case OMF_None:
421
678
    case OMF_dealloc:
422
711
    case OMF_finalize:
423
715
    case OMF_alloc:
424
878
    case OMF_init:
425
880
    case OMF_mutableCopy:
426
886
    case OMF_copy:
427
899
    case OMF_new:
428
899
    case OMF_self:
429
899
    case OMF_initialize:
430
902
    case OMF_performSelector:
431
902
      break;
432
922
    }
433
922
  }
434
435
  // Warn on deprecated methods under -Wdeprecated-implementations,
436
  // and prepare for warning on missing super calls.
437
7.27k
  if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) {
438
7.25k
    ObjCMethodDecl *IMD =
439
7.25k
      IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod());
440
441
7.25k
    if (IMD) {
442
4.73k
      ObjCImplDecl *ImplDeclOfMethodDef =
443
4.73k
        dyn_cast<ObjCImplDecl>(MDecl->getDeclContext());
444
4.73k
      ObjCContainerDecl *ContDeclOfMethodDecl =
445
4.73k
        dyn_cast<ObjCContainerDecl>(IMD->getDeclContext());
446
4.73k
      ObjCImplDecl *ImplDeclOfMethodDecl = nullptr;
447
4.73k
      if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl))
448
4.04k
        ImplDeclOfMethodDecl = OID->getImplementation();
449
690
      else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContDeclOfMethodDecl)) {
450
379
        if (CD->IsClassExtension()) {
451
59
          if (ObjCInterfaceDecl *OID = CD->getClassInterface())
452
59
            ImplDeclOfMethodDecl = OID->getImplementation();
453
59
        } else
454
320
            ImplDeclOfMethodDecl = CD->getImplementation();
455
379
      }
456
      // No need to issue deprecated warning if deprecated mehod in class/category
457
      // is being implemented in its own implementation (no overriding is involved).
458
4.73k
      if (!ImplDeclOfMethodDecl || 
ImplDeclOfMethodDecl != ImplDeclOfMethodDef3.95k
)
459
963
        DiagnoseObjCImplementedDeprecations(*this, IMD, MDecl->getLocation());
460
4.73k
    }
461
462
7.25k
    if (MDecl->getMethodFamily() == OMF_init) {
463
870
      if (MDecl->isDesignatedInitializerForTheInterface()) {
464
145
        getCurFunction()->ObjCIsDesignatedInit = true;
465
145
        getCurFunction()->ObjCWarnForNoDesignatedInitChain =
466
145
            IC->getSuperClass() != nullptr;
467
725
      } else if (IC->hasDesignatedInitializers()) {
468
11
        getCurFunction()->ObjCIsSecondaryInit = true;
469
11
        getCurFunction()->ObjCWarnForNoInitDelegation = true;
470
11
      }
471
870
    }
472
473
    // If this is "dealloc" or "finalize", set some bit here.
474
    // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false.
475
    // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set.
476
    // Only do this if the current class actually has a superclass.
477
7.25k
    if (const ObjCInterfaceDecl *SuperClass = IC->getSuperClass()) {
478
4.13k
      ObjCMethodFamily Family = MDecl->getMethodFamily();
479
4.13k
      if (Family == OMF_dealloc) {
480
272
        if (!(getLangOpts().ObjCAutoRefCount ||
481
272
              
getLangOpts().getGC() == LangOptions::GCOnly207
))
482
205
          getCurFunction()->ObjCShouldCallSuper = true;
483
484
3.86k
      } else if (Family == OMF_finalize) {
485
12
        if (Context.getLangOpts().getGC() != LangOptions::NonGC)
486
4
          getCurFunction()->ObjCShouldCallSuper = true;
487
488
3.85k
      } else {
489
3.85k
        const ObjCMethodDecl *SuperMethod =
490
3.85k
          SuperClass->lookupMethod(MDecl->getSelector(),
491
3.85k
                                   MDecl->isInstanceMethod());
492
3.85k
        getCurFunction()->ObjCShouldCallSuper =
493
3.85k
          (SuperMethod && 
SuperMethod->hasAttr<ObjCRequiresSuperAttr>()950
);
494
3.85k
      }
495
4.13k
    }
496
7.25k
  }
497
7.27k
}
498
499
namespace {
500
501
// Callback to only accept typo corrections that are Objective-C classes.
502
// If an ObjCInterfaceDecl* is given to the constructor, then the validation
503
// function will reject corrections to that class.
504
class ObjCInterfaceValidatorCCC final : public CorrectionCandidateCallback {
505
 public:
506
61
  ObjCInterfaceValidatorCCC() : CurrentIDecl(nullptr) {}
507
  explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl)
508
4
      : CurrentIDecl(IDecl) {}
509
510
26
  bool ValidateCandidate(const TypoCorrection &candidate) override {
511
26
    ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>();
512
26
    return ID && 
!declaresSameEntity(ID, CurrentIDecl)24
;
513
26
  }
514
515
63
  std::unique_ptr<CorrectionCandidateCallback> clone() override {
516
63
    return std::make_unique<ObjCInterfaceValidatorCCC>(*this);
517
63
  }
518
519
 private:
520
  ObjCInterfaceDecl *CurrentIDecl;
521
};
522
523
} // end anonymous namespace
524
525
static void diagnoseUseOfProtocols(Sema &TheSema,
526
                                   ObjCContainerDecl *CD,
527
                                   ObjCProtocolDecl *const *ProtoRefs,
528
                                   unsigned NumProtoRefs,
529
39.4k
                                   const SourceLocation *ProtoLocs) {
530
39.4k
  assert(ProtoRefs);
531
  // Diagnose availability in the context of the ObjC container.
532
0
  Sema::ContextRAII SavedContext(TheSema, CD);
533
95.4k
  for (unsigned i = 0; i < NumProtoRefs; 
++i55.9k
) {
534
55.9k
    (void)TheSema.DiagnoseUseOfDecl(ProtoRefs[i], ProtoLocs[i],
535
55.9k
                                    /*UnknownObjCClass=*/nullptr,
536
55.9k
                                    /*ObjCPropertyAccess=*/false,
537
55.9k
                                    /*AvoidPartialAvailabilityChecks=*/true);
538
55.9k
  }
539
39.4k
}
540
541
void Sema::
542
ActOnSuperClassOfClassInterface(Scope *S,
543
                                SourceLocation AtInterfaceLoc,
544
                                ObjCInterfaceDecl *IDecl,
545
                                IdentifierInfo *ClassName,
546
                                SourceLocation ClassLoc,
547
                                IdentifierInfo *SuperName,
548
                                SourceLocation SuperLoc,
549
                                ArrayRef<ParsedType> SuperTypeArgs,
550
62.8k
                                SourceRange SuperTypeArgsRange) {
551
  // Check if a different kind of symbol declared in this scope.
552
62.8k
  NamedDecl *PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
553
62.8k
                                         LookupOrdinaryName);
554
555
62.8k
  if (!PrevDecl) {
556
    // Try to correct for a typo in the superclass name without correcting
557
    // to the class we're defining.
558
4
    ObjCInterfaceValidatorCCC CCC(IDecl);
559
4
    if (TypoCorrection Corrected = CorrectTypo(
560
4
            DeclarationNameInfo(SuperName, SuperLoc), LookupOrdinaryName,
561
4
            TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
562
1
      diagnoseTypo(Corrected, PDiag(diag::err_undef_superclass_suggest)
563
1
                   << SuperName << ClassName);
564
1
      PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
565
1
    }
566
4
  }
567
568
62.8k
  if (declaresSameEntity(PrevDecl, IDecl)) {
569
1
    Diag(SuperLoc, diag::err_recursive_superclass)
570
1
      << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
571
1
    IDecl->setEndOfDefinitionLoc(ClassLoc);
572
62.8k
  } else {
573
62.8k
    ObjCInterfaceDecl *SuperClassDecl =
574
62.8k
    dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
575
62.8k
    QualType SuperClassType;
576
577
    // Diagnose classes that inherit from deprecated classes.
578
62.8k
    if (SuperClassDecl) {
579
62.6k
      (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
580
62.6k
      SuperClassType = Context.getObjCInterfaceType(SuperClassDecl);
581
62.6k
    }
582
583
62.8k
    if (PrevDecl && 
!SuperClassDecl62.8k
) {
584
      // The previous declaration was not a class decl. Check if we have a
585
      // typedef. If we do, get the underlying class type.
586
136
      if (const TypedefNameDecl *TDecl =
587
136
          dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
588
136
        QualType T = TDecl->getUnderlyingType();
589
136
        if (T->isObjCObjectType()) {
590
135
          if (NamedDecl *IDecl = T->castAs<ObjCObjectType>()->getInterface()) {
591
135
            SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
592
135
            SuperClassType = Context.getTypeDeclType(TDecl);
593
594
            // This handles the following case:
595
            // @interface NewI @end
596
            // typedef NewI DeprI __attribute__((deprecated("blah")))
597
            // @interface SI : DeprI /* warn here */ @end
598
135
            (void)DiagnoseUseOfDecl(const_cast<TypedefNameDecl*>(TDecl), SuperLoc);
599
135
          }
600
135
        }
601
136
      }
602
603
      // This handles the following case:
604
      //
605
      // typedef int SuperClass;
606
      // @interface MyClass : SuperClass {} @end
607
      //
608
136
      if (!SuperClassDecl) {
609
1
        Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
610
1
        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
611
1
      }
612
136
    }
613
614
62.8k
    if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
615
62.6k
      if (!SuperClassDecl)
616
3
        Diag(SuperLoc, diag::err_undef_superclass)
617
3
          << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
618
62.6k
      else if (RequireCompleteType(SuperLoc,
619
62.6k
                                   SuperClassType,
620
62.6k
                                   diag::err_forward_superclass,
621
62.6k
                                   SuperClassDecl->getDeclName(),
622
62.6k
                                   ClassName,
623
62.6k
                                   SourceRange(AtInterfaceLoc, ClassLoc))) {
624
5
        SuperClassDecl = nullptr;
625
5
        SuperClassType = QualType();
626
5
      }
627
62.6k
    }
628
629
62.8k
    if (SuperClassType.isNull()) {
630
9
      assert(!SuperClassDecl && "Failed to set SuperClassType?");
631
0
      return;
632
9
    }
633
634
    // Handle type arguments on the superclass.
635
62.8k
    TypeSourceInfo *SuperClassTInfo = nullptr;
636
62.8k
    if (!SuperTypeArgs.empty()) {
637
1.34k
      TypeResult fullSuperClassType = actOnObjCTypeArgsAndProtocolQualifiers(
638
1.34k
                                        S,
639
1.34k
                                        SuperLoc,
640
1.34k
                                        CreateParsedType(SuperClassType,
641
1.34k
                                                         nullptr),
642
1.34k
                                        SuperTypeArgsRange.getBegin(),
643
1.34k
                                        SuperTypeArgs,
644
1.34k
                                        SuperTypeArgsRange.getEnd(),
645
1.34k
                                        SourceLocation(),
646
1.34k
                                        { },
647
1.34k
                                        { },
648
1.34k
                                        SourceLocation());
649
1.34k
      if (!fullSuperClassType.isUsable())
650
0
        return;
651
652
1.34k
      SuperClassType = GetTypeFromParser(fullSuperClassType.get(),
653
1.34k
                                         &SuperClassTInfo);
654
1.34k
    }
655
656
62.8k
    if (!SuperClassTInfo) {
657
61.4k
      SuperClassTInfo = Context.getTrivialTypeSourceInfo(SuperClassType,
658
61.4k
                                                         SuperLoc);
659
61.4k
    }
660
661
62.8k
    IDecl->setSuperClass(SuperClassTInfo);
662
62.8k
    IDecl->setEndOfDefinitionLoc(SuperClassTInfo->getTypeLoc().getEndLoc());
663
62.8k
  }
664
62.8k
}
665
666
DeclResult Sema::actOnObjCTypeParam(Scope *S,
667
                                    ObjCTypeParamVariance variance,
668
                                    SourceLocation varianceLoc,
669
                                    unsigned index,
670
                                    IdentifierInfo *paramName,
671
                                    SourceLocation paramLoc,
672
                                    SourceLocation colonLoc,
673
46.4k
                                    ParsedType parsedTypeBound) {
674
  // If there was an explicitly-provided type bound, check it.
675
46.4k
  TypeSourceInfo *typeBoundInfo = nullptr;
676
46.4k
  if (parsedTypeBound) {
677
    // The type bound can be any Objective-C pointer type.
678
404
    QualType typeBound = GetTypeFromParser(parsedTypeBound, &typeBoundInfo);
679
404
    if (typeBound->isObjCObjectPointerType()) {
680
      // okay
681
402
    } else 
if (2
typeBound->isObjCObjectType()2
) {
682
      // The user forgot the * on an Objective-C pointer type, e.g.,
683
      // "T : NSView".
684
1
      SourceLocation starLoc = getLocForEndOfToken(
685
1
                                 typeBoundInfo->getTypeLoc().getEndLoc());
686
1
      Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
687
1
           diag::err_objc_type_param_bound_missing_pointer)
688
1
        << typeBound << paramName
689
1
        << FixItHint::CreateInsertion(starLoc, " *");
690
691
      // Create a new type location builder so we can update the type
692
      // location information we have.
693
1
      TypeLocBuilder builder;
694
1
      builder.pushFullCopy(typeBoundInfo->getTypeLoc());
695
696
      // Create the Objective-C pointer type.
697
1
      typeBound = Context.getObjCObjectPointerType(typeBound);
698
1
      ObjCObjectPointerTypeLoc newT
699
1
        = builder.push<ObjCObjectPointerTypeLoc>(typeBound);
700
1
      newT.setStarLoc(starLoc);
701
702
      // Form the new type source information.
703
1
      typeBoundInfo = builder.getTypeSourceInfo(Context, typeBound);
704
1
    } else {
705
      // Not a valid type bound.
706
1
      Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
707
1
           diag::err_objc_type_param_bound_nonobject)
708
1
        << typeBound << paramName;
709
710
      // Forget the bound; we'll default to id later.
711
1
      typeBoundInfo = nullptr;
712
1
    }
713
714
    // Type bounds cannot have qualifiers (even indirectly) or explicit
715
    // nullability.
716
404
    if (typeBoundInfo) {
717
403
      QualType typeBound = typeBoundInfo->getType();
718
403
      TypeLoc qual = typeBoundInfo->getTypeLoc().findExplicitQualifierLoc();
719
403
      if (qual || 
typeBound.hasQualifiers()388
) {
720
19
        bool diagnosed = false;
721
19
        SourceRange rangeToRemove;
722
19
        if (qual) {
723
15
          if (auto attr = qual.getAs<AttributedTypeLoc>()) {
724
11
            rangeToRemove = attr.getLocalSourceRange();
725
11
            if (attr.getTypePtr()->getImmediateNullability()) {
726
1
              Diag(attr.getBeginLoc(),
727
1
                   diag::err_objc_type_param_bound_explicit_nullability)
728
1
                  << paramName << typeBound
729
1
                  << FixItHint::CreateRemoval(rangeToRemove);
730
1
              diagnosed = true;
731
1
            }
732
11
          }
733
15
        }
734
735
19
        if (!diagnosed) {
736
18
          Diag(qual ? 
qual.getBeginLoc()14
737
18
                    : 
typeBoundInfo->getTypeLoc().getBeginLoc()4
,
738
18
               diag::err_objc_type_param_bound_qualified)
739
18
              << paramName << typeBound
740
18
              << typeBound.getQualifiers().getAsString()
741
18
              << FixItHint::CreateRemoval(rangeToRemove);
742
18
        }
743
744
        // If the type bound has qualifiers other than CVR, we need to strip
745
        // them or we'll probably assert later when trying to apply new
746
        // qualifiers.
747
19
        Qualifiers quals = typeBound.getQualifiers();
748
19
        quals.removeCVRQualifiers();
749
19
        if (!quals.empty()) {
750
14
          typeBoundInfo =
751
14
             Context.getTrivialTypeSourceInfo(typeBound.getUnqualifiedType());
752
14
        }
753
19
      }
754
403
    }
755
404
  }
756
757
  // If there was no explicit type bound (or we removed it due to an error),
758
  // use 'id' instead.
759
46.4k
  if (!typeBoundInfo) {
760
46.0k
    colonLoc = SourceLocation();
761
46.0k
    typeBoundInfo = Context.getTrivialTypeSourceInfo(Context.getObjCIdType());
762
46.0k
  }
763
764
  // Create the type parameter.
765
46.4k
  return ObjCTypeParamDecl::Create(Context, CurContext, variance, varianceLoc,
766
46.4k
                                   index, paramLoc, paramName, colonLoc,
767
46.4k
                                   typeBoundInfo);
768
46.4k
}
769
770
ObjCTypeParamList *Sema::actOnObjCTypeParamList(Scope *S,
771
                                                SourceLocation lAngleLoc,
772
                                                ArrayRef<Decl *> typeParamsIn,
773
35.2k
                                                SourceLocation rAngleLoc) {
774
  // We know that the array only contains Objective-C type parameters.
775
35.2k
  ArrayRef<ObjCTypeParamDecl *>
776
35.2k
    typeParams(
777
35.2k
      reinterpret_cast<ObjCTypeParamDecl * const *>(typeParamsIn.data()),
778
35.2k
      typeParamsIn.size());
779
780
  // Diagnose redeclarations of type parameters.
781
  // We do this now because Objective-C type parameters aren't pushed into
782
  // scope until later (after the instance variable block), but we want the
783
  // diagnostics to occur right after we parse the type parameter list.
784
35.2k
  llvm::SmallDenseMap<IdentifierInfo *, ObjCTypeParamDecl *> knownParams;
785
46.4k
  for (auto typeParam : typeParams) {
786
46.4k
    auto known = knownParams.find(typeParam->getIdentifier());
787
46.4k
    if (known != knownParams.end()) {
788
2
      Diag(typeParam->getLocation(), diag::err_objc_type_param_redecl)
789
2
        << typeParam->getIdentifier()
790
2
        << SourceRange(known->second->getLocation());
791
792
2
      typeParam->setInvalidDecl();
793
46.4k
    } else {
794
46.4k
      knownParams.insert(std::make_pair(typeParam->getIdentifier(), typeParam));
795
796
      // Push the type parameter into scope.
797
46.4k
      PushOnScopeChains(typeParam, S, /*AddToContext=*/false);
798
46.4k
    }
799
46.4k
  }
800
801
  // Create the parameter list.
802
35.2k
  return ObjCTypeParamList::create(Context, lAngleLoc, typeParams, rAngleLoc);
803
35.2k
}
804
805
35.2k
void Sema::popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList) {
806
46.4k
  for (auto typeParam : *typeParamList) {
807
46.4k
    if (!typeParam->isInvalidDecl()) {
808
46.4k
      S->RemoveDecl(typeParam);
809
46.4k
      IdResolver.RemoveDecl(typeParam);
810
46.4k
    }
811
46.4k
  }
812
35.2k
}
813
814
namespace {
815
  /// The context in which an Objective-C type parameter list occurs, for use
816
  /// in diagnostics.
817
  enum class TypeParamListContext {
818
    ForwardDeclaration,
819
    Definition,
820
    Category,
821
    Extension
822
  };
823
} // end anonymous namespace
824
825
/// Check consistency between two Objective-C type parameter lists, e.g.,
826
/// between a category/extension and an \@interface or between an \@class and an
827
/// \@interface.
828
static bool checkTypeParamListConsistency(Sema &S,
829
                                          ObjCTypeParamList *prevTypeParams,
830
                                          ObjCTypeParamList *newTypeParams,
831
31.3k
                                          TypeParamListContext newContext) {
832
  // If the sizes don't match, complain about that.
833
31.3k
  if (prevTypeParams->size() != newTypeParams->size()) {
834
2
    SourceLocation diagLoc;
835
2
    if (newTypeParams->size() > prevTypeParams->size()) {
836
1
      diagLoc = newTypeParams->begin()[prevTypeParams->size()]->getLocation();
837
1
    } else {
838
1
      diagLoc = S.getLocForEndOfToken(newTypeParams->back()->getEndLoc());
839
1
    }
840
841
2
    S.Diag(diagLoc, diag::err_objc_type_param_arity_mismatch)
842
2
      << static_cast<unsigned>(newContext)
843
2
      << (newTypeParams->size() > prevTypeParams->size())
844
2
      << prevTypeParams->size()
845
2
      << newTypeParams->size();
846
847
2
    return true;
848
2
  }
849
850
  // Match up the type parameters.
851
72.8k
  
for (unsigned i = 0, n = prevTypeParams->size(); 31.3k
i != n;
++i41.5k
) {
852
41.5k
    ObjCTypeParamDecl *prevTypeParam = prevTypeParams->begin()[i];
853
41.5k
    ObjCTypeParamDecl *newTypeParam = newTypeParams->begin()[i];
854
855
    // Check for consistency of the variance.
856
41.5k
    if (newTypeParam->getVariance() != prevTypeParam->getVariance()) {
857
36.3k
      if (newTypeParam->getVariance() == ObjCTypeParamVariance::Invariant &&
858
36.3k
          
newContext != TypeParamListContext::Definition35.4k
) {
859
        // When the new type parameter is invariant and is not part
860
        // of the definition, just propagate the variance.
861
35.4k
        newTypeParam->setVariance(prevTypeParam->getVariance());
862
35.4k
      } else 
if (870
prevTypeParam->getVariance()
863
870
                   == ObjCTypeParamVariance::Invariant &&
864
870
                 
!(866
isa<ObjCInterfaceDecl>(prevTypeParam->getDeclContext())866
&&
865
866
                   cast<ObjCInterfaceDecl>(prevTypeParam->getDeclContext())
866
866
                     ->getDefinition() == prevTypeParam->getDeclContext())) {
867
        // When the old parameter is invariant and was not part of the
868
        // definition, just ignore the difference because it doesn't
869
        // matter.
870
866
      } else {
871
4
        {
872
          // Diagnose the conflict and update the second declaration.
873
4
          SourceLocation diagLoc = newTypeParam->getVarianceLoc();
874
4
          if (diagLoc.isInvalid())
875
1
            diagLoc = newTypeParam->getBeginLoc();
876
877
4
          auto diag = S.Diag(diagLoc,
878
4
                             diag::err_objc_type_param_variance_conflict)
879
4
                        << static_cast<unsigned>(newTypeParam->getVariance())
880
4
                        << newTypeParam->getDeclName()
881
4
                        << static_cast<unsigned>(prevTypeParam->getVariance())
882
4
                        << prevTypeParam->getDeclName();
883
4
          switch (prevTypeParam->getVariance()) {
884
0
          case ObjCTypeParamVariance::Invariant:
885
0
            diag << FixItHint::CreateRemoval(newTypeParam->getVarianceLoc());
886
0
            break;
887
888
2
          case ObjCTypeParamVariance::Covariant:
889
4
          case ObjCTypeParamVariance::Contravariant: {
890
4
            StringRef newVarianceStr
891
4
               = prevTypeParam->getVariance() == ObjCTypeParamVariance::Covariant
892
4
                   ? 
"__covariant"2
893
4
                   : 
"__contravariant"2
;
894
4
            if (newTypeParam->getVariance()
895
4
                  == ObjCTypeParamVariance::Invariant) {
896
1
              diag << FixItHint::CreateInsertion(newTypeParam->getBeginLoc(),
897
1
                                                 (newVarianceStr + " ").str());
898
3
            } else {
899
3
              diag << FixItHint::CreateReplacement(newTypeParam->getVarianceLoc(),
900
3
                                               newVarianceStr);
901
3
            }
902
4
          }
903
4
          }
904
4
        }
905
906
4
        S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
907
4
          << prevTypeParam->getDeclName();
908
909
        // Override the variance.
910
4
        newTypeParam->setVariance(prevTypeParam->getVariance());
911
4
      }
912
36.3k
    }
913
914
    // If the bound types match, there's nothing to do.
915
41.5k
    if (S.Context.hasSameType(prevTypeParam->getUnderlyingType(),
916
41.5k
                              newTypeParam->getUnderlyingType()))
917
41.5k
      continue;
918
919
    // If the new type parameter's bound was explicit, complain about it being
920
    // different from the original.
921
16
    if (newTypeParam->hasExplicitBound()) {
922
5
      SourceRange newBoundRange = newTypeParam->getTypeSourceInfo()
923
5
                                    ->getTypeLoc().getSourceRange();
924
5
      S.Diag(newBoundRange.getBegin(), diag::err_objc_type_param_bound_conflict)
925
5
        << newTypeParam->getUnderlyingType()
926
5
        << newTypeParam->getDeclName()
927
5
        << prevTypeParam->hasExplicitBound()
928
5
        << prevTypeParam->getUnderlyingType()
929
5
        << (newTypeParam->getDeclName() == prevTypeParam->getDeclName())
930
5
        << prevTypeParam->getDeclName()
931
5
        << FixItHint::CreateReplacement(
932
5
             newBoundRange,
933
5
             prevTypeParam->getUnderlyingType().getAsString(
934
5
               S.Context.getPrintingPolicy()));
935
936
5
      S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
937
5
        << prevTypeParam->getDeclName();
938
939
      // Override the new type parameter's bound type with the previous type,
940
      // so that it's consistent.
941
5
      S.Context.adjustObjCTypeParamBoundType(prevTypeParam, newTypeParam);
942
5
      continue;
943
5
    }
944
945
    // The new type parameter got the implicit bound of 'id'. That's okay for
946
    // categories and extensions (overwrite it later), but not for forward
947
    // declarations and @interfaces, because those must be standalone.
948
11
    if (newContext == TypeParamListContext::ForwardDeclaration ||
949
11
        
newContext == TypeParamListContext::Definition9
) {
950
      // Diagnose this problem for forward declarations and definitions.
951
3
      SourceLocation insertionLoc
952
3
        = S.getLocForEndOfToken(newTypeParam->getLocation());
953
3
      std::string newCode
954
3
        = " : " + prevTypeParam->getUnderlyingType().getAsString(
955
3
                    S.Context.getPrintingPolicy());
956
3
      S.Diag(newTypeParam->getLocation(),
957
3
             diag::err_objc_type_param_bound_missing)
958
3
        << prevTypeParam->getUnderlyingType()
959
3
        << newTypeParam->getDeclName()
960
3
        << (newContext == TypeParamListContext::ForwardDeclaration)
961
3
        << FixItHint::CreateInsertion(insertionLoc, newCode);
962
963
3
      S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
964
3
        << prevTypeParam->getDeclName();
965
3
    }
966
967
    // Update the new type parameter's bound to match the previous one.
968
11
    S.Context.adjustObjCTypeParamBoundType(prevTypeParam, newTypeParam);
969
11
  }
970
971
31.3k
  return false;
972
31.3k
}
973
974
Decl *Sema::ActOnStartClassInterface(
975
    Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
976
    SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
977
    IdentifierInfo *SuperName, SourceLocation SuperLoc,
978
    ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange,
979
    Decl *const *ProtoRefs, unsigned NumProtoRefs,
980
    const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
981
70.9k
    const ParsedAttributesView &AttrList) {
982
70.9k
  assert(ClassName && "Missing class identifier");
983
984
  // Check for another declaration kind with the same name.
985
0
  NamedDecl *PrevDecl =
986
70.9k
      LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
987
70.9k
                       forRedeclarationInCurContext());
988
989
70.9k
  if (PrevDecl && 
!isa<ObjCInterfaceDecl>(PrevDecl)18.5k
) {
990
2
    Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
991
2
    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
992
2
  }
993
994
  // Create a declaration to describe this @interface.
995
70.9k
  ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
996
997
70.9k
  if (PrevIDecl && 
PrevIDecl->getIdentifier() != ClassName18.5k
) {
998
    // A previous decl with a different name is because of
999
    // @compatibility_alias, for example:
1000
    // \code
1001
    //   @class NewImage;
1002
    //   @compatibility_alias OldImage NewImage;
1003
    // \endcode
1004
    // A lookup for 'OldImage' will return the 'NewImage' decl.
1005
    //
1006
    // In such a case use the real declaration name, instead of the alias one,
1007
    // otherwise we will break IdentifierResolver and redecls-chain invariants.
1008
    // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
1009
    // has been aliased.
1010
3
    ClassName = PrevIDecl->getIdentifier();
1011
3
  }
1012
1013
  // If there was a forward declaration with type parameters, check
1014
  // for consistency.
1015
70.9k
  if (PrevIDecl) {
1016
18.5k
    if (ObjCTypeParamList *prevTypeParamList = PrevIDecl->getTypeParamList()) {
1017
874
      if (typeParamList) {
1018
        // Both have type parameter lists; check for consistency.
1019
873
        if (checkTypeParamListConsistency(*this, prevTypeParamList,
1020
873
                                          typeParamList,
1021
873
                                          TypeParamListContext::Definition)) {
1022
0
          typeParamList = nullptr;
1023
0
        }
1024
873
      } else {
1025
1
        Diag(ClassLoc, diag::err_objc_parameterized_forward_class_first)
1026
1
          << ClassName;
1027
1
        Diag(prevTypeParamList->getLAngleLoc(), diag::note_previous_decl)
1028
1
          << ClassName;
1029
1030
        // Clone the type parameter list.
1031
1
        SmallVector<ObjCTypeParamDecl *, 4> clonedTypeParams;
1032
1
        for (auto typeParam : *prevTypeParamList) {
1033
1
          clonedTypeParams.push_back(
1034
1
            ObjCTypeParamDecl::Create(
1035
1
              Context,
1036
1
              CurContext,
1037
1
              typeParam->getVariance(),
1038
1
              SourceLocation(),
1039
1
              typeParam->getIndex(),
1040
1
              SourceLocation(),
1041
1
              typeParam->getIdentifier(),
1042
1
              SourceLocation(),
1043
1
              Context.getTrivialTypeSourceInfo(typeParam->getUnderlyingType())));
1044
1
        }
1045
1046
1
        typeParamList = ObjCTypeParamList::create(Context,
1047
1
                                                  SourceLocation(),
1048
1
                                                  clonedTypeParams,
1049
1
                                                  SourceLocation());
1050
1
      }
1051
874
    }
1052
18.5k
  }
1053
1054
70.9k
  ObjCInterfaceDecl *IDecl
1055
70.9k
    = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName,
1056
70.9k
                                typeParamList, PrevIDecl, ClassLoc);
1057
70.9k
  if (PrevIDecl) {
1058
    // Class already seen. Was it a definition?
1059
18.5k
    if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
1060
10
      Diag(AtInterfaceLoc, diag::err_duplicate_class_def)
1061
10
        << PrevIDecl->getDeclName();
1062
10
      Diag(Def->getLocation(), diag::note_previous_definition);
1063
10
      IDecl->setInvalidDecl();
1064
10
    }
1065
18.5k
  }
1066
1067
70.9k
  ProcessDeclAttributeList(TUScope, IDecl, AttrList);
1068
70.9k
  AddPragmaAttributes(TUScope, IDecl);
1069
1070
  // Merge attributes from previous declarations.
1071
70.9k
  if (PrevIDecl)
1072
18.5k
    mergeDeclAttributes(IDecl, PrevIDecl);
1073
1074
70.9k
  PushOnScopeChains(IDecl, TUScope);
1075
1076
  // Start the definition of this class. If we're in a redefinition case, there
1077
  // may already be a definition, so we'll end up adding to it.
1078
70.9k
  if (!IDecl->hasDefinition())
1079
70.9k
    IDecl->startDefinition();
1080
1081
70.9k
  if (SuperName) {
1082
    // Diagnose availability in the context of the @interface.
1083
62.8k
    ContextRAII SavedContext(*this, IDecl);
1084
1085
62.8k
    ActOnSuperClassOfClassInterface(S, AtInterfaceLoc, IDecl,
1086
62.8k
                                    ClassName, ClassLoc,
1087
62.8k
                                    SuperName, SuperLoc, SuperTypeArgs,
1088
62.8k
                                    SuperTypeArgsRange);
1089
62.8k
  } else { // we have a root class.
1090
8.13k
    IDecl->setEndOfDefinitionLoc(ClassLoc);
1091
8.13k
  }
1092
1093
  // Check then save referenced protocols.
1094
70.9k
  if (NumProtoRefs) {
1095
25.3k
    diagnoseUseOfProtocols(*this, IDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1096
25.3k
                           NumProtoRefs, ProtoLocs);
1097
25.3k
    IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
1098
25.3k
                           ProtoLocs, Context);
1099
25.3k
    IDecl->setEndOfDefinitionLoc(EndProtoLoc);
1100
25.3k
  }
1101
1102
70.9k
  CheckObjCDeclScope(IDecl);
1103
70.9k
  return ActOnObjCContainerStartDefinition(IDecl);
1104
70.9k
}
1105
1106
/// ActOnTypedefedProtocols - this action finds protocol list as part of the
1107
/// typedef'ed use for a qualified super class and adds them to the list
1108
/// of the protocols.
1109
void Sema::ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
1110
                                  SmallVectorImpl<SourceLocation> &ProtocolLocs,
1111
                                   IdentifierInfo *SuperName,
1112
70.9k
                                   SourceLocation SuperLoc) {
1113
70.9k
  if (!SuperName)
1114
8.13k
    return;
1115
62.8k
  NamedDecl* IDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
1116
62.8k
                                      LookupOrdinaryName);
1117
62.8k
  if (!IDecl)
1118
5
    return;
1119
1120
62.8k
  if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) {
1121
136
    QualType T = TDecl->getUnderlyingType();
1122
136
    if (T->isObjCObjectType())
1123
135
      if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>()) {
1124
135
        ProtocolRefs.append(OPT->qual_begin(), OPT->qual_end());
1125
        // FIXME: Consider whether this should be an invalid loc since the loc
1126
        // is not actually pointing to a protocol name reference but to the
1127
        // typedef reference. Note that the base class name loc is also pointing
1128
        // at the typedef.
1129
135
        ProtocolLocs.append(OPT->getNumProtocols(), SuperLoc);
1130
135
      }
1131
136
  }
1132
62.8k
}
1133
1134
/// ActOnCompatibilityAlias - this action is called after complete parsing of
1135
/// a \@compatibility_alias declaration. It sets up the alias relationships.
1136
Decl *Sema::ActOnCompatibilityAlias(SourceLocation AtLoc,
1137
                                    IdentifierInfo *AliasName,
1138
                                    SourceLocation AliasLocation,
1139
                                    IdentifierInfo *ClassName,
1140
247
                                    SourceLocation ClassLocation) {
1141
  // Look for previous declaration of alias name
1142
247
  NamedDecl *ADecl =
1143
247
      LookupSingleName(TUScope, AliasName, AliasLocation, LookupOrdinaryName,
1144
247
                       forRedeclarationInCurContext());
1145
247
  if (ADecl) {
1146
2
    Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
1147
2
    Diag(ADecl->getLocation(), diag::note_previous_declaration);
1148
2
    return nullptr;
1149
2
  }
1150
  // Check for class declaration
1151
245
  NamedDecl *CDeclU =
1152
245
      LookupSingleName(TUScope, ClassName, ClassLocation, LookupOrdinaryName,
1153
245
                       forRedeclarationInCurContext());
1154
245
  if (const TypedefNameDecl *TDecl =
1155
245
        dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
1156
30
    QualType T = TDecl->getUnderlyingType();
1157
30
    if (T->isObjCObjectType()) {
1158
29
      if (NamedDecl *IDecl = T->castAs<ObjCObjectType>()->getInterface()) {
1159
29
        ClassName = IDecl->getIdentifier();
1160
29
        CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
1161
29
                                  LookupOrdinaryName,
1162
29
                                  forRedeclarationInCurContext());
1163
29
      }
1164
29
    }
1165
30
  }
1166
245
  ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
1167
245
  if (!CDecl) {
1168
2
    Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
1169
2
    if (CDeclU)
1170
1
      Diag(CDeclU->getLocation(), diag::note_previous_declaration);
1171
2
    return nullptr;
1172
2
  }
1173
1174
  // Everything checked out, instantiate a new alias declaration AST.
1175
243
  ObjCCompatibleAliasDecl *AliasDecl =
1176
243
    ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
1177
1178
243
  if (!CheckObjCDeclScope(AliasDecl))
1179
242
    PushOnScopeChains(AliasDecl, TUScope);
1180
1181
243
  return AliasDecl;
1182
245
}
1183
1184
bool Sema::CheckForwardProtocolDeclarationForCircularDependency(
1185
  IdentifierInfo *PName,
1186
  SourceLocation &Ploc, SourceLocation PrevLoc,
1187
9.66k
  const ObjCList<ObjCProtocolDecl> &PList) {
1188
1189
9.66k
  bool res = false;
1190
9.66k
  for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
1191
14.6k
       E = PList.end(); I != E; 
++I4.95k
) {
1192
4.95k
    if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
1193
4.95k
                                                 Ploc)) {
1194
4.95k
      if (PDecl->getIdentifier() == PName) {
1195
1
        Diag(Ploc, diag::err_protocol_has_circular_dependency);
1196
1
        Diag(PrevLoc, diag::note_previous_definition);
1197
1
        res = true;
1198
1
      }
1199
1200
4.95k
      if (!PDecl->hasDefinition())
1201
2
        continue;
1202
1203
4.94k
      if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
1204
4.94k
            PDecl->getLocation(), PDecl->getReferencedProtocols()))
1205
2
        res = true;
1206
4.94k
    }
1207
4.95k
  }
1208
9.66k
  return res;
1209
9.66k
}
1210
1211
Decl *Sema::ActOnStartProtocolInterface(
1212
    SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
1213
    SourceLocation ProtocolLoc, Decl *const *ProtoRefs, unsigned NumProtoRefs,
1214
    const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
1215
17.5k
    const ParsedAttributesView &AttrList) {
1216
17.5k
  bool err = false;
1217
  // FIXME: Deal with AttrList.
1218
17.5k
  assert(ProtocolName && "Missing protocol identifier");
1219
0
  ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc,
1220
17.5k
                                              forRedeclarationInCurContext());
1221
17.5k
  ObjCProtocolDecl *PDecl = nullptr;
1222
17.5k
  if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : nullptr) {
1223
    // If we already have a definition, complain.
1224
13
    Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
1225
13
    Diag(Def->getLocation(), diag::note_previous_definition);
1226
1227
    // Create a new protocol that is completely distinct from previous
1228
    // declarations, and do not make this protocol available for name lookup.
1229
    // That way, we'll end up completely ignoring the duplicate.
1230
    // FIXME: Can we turn this into an error?
1231
13
    PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
1232
13
                                     ProtocolLoc, AtProtoInterfaceLoc,
1233
13
                                     /*PrevDecl=*/nullptr);
1234
1235
    // If we are using modules, add the decl to the context in order to
1236
    // serialize something meaningful.
1237
13
    if (getLangOpts().Modules)
1238
1
      PushOnScopeChains(PDecl, TUScope);
1239
13
    PDecl->startDefinition();
1240
17.5k
  } else {
1241
17.5k
    if (PrevDecl) {
1242
      // Check for circular dependencies among protocol declarations. This can
1243
      // only happen if this protocol was forward-declared.
1244
4.71k
      ObjCList<ObjCProtocolDecl> PList;
1245
4.71k
      PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
1246
4.71k
      err = CheckForwardProtocolDeclarationForCircularDependency(
1247
4.71k
              ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList);
1248
4.71k
    }
1249
1250
    // Create the new declaration.
1251
17.5k
    PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
1252
17.5k
                                     ProtocolLoc, AtProtoInterfaceLoc,
1253
17.5k
                                     /*PrevDecl=*/PrevDecl);
1254
1255
17.5k
    PushOnScopeChains(PDecl, TUScope);
1256
17.5k
    PDecl->startDefinition();
1257
17.5k
  }
1258
1259
17.5k
  ProcessDeclAttributeList(TUScope, PDecl, AttrList);
1260
17.5k
  AddPragmaAttributes(TUScope, PDecl);
1261
1262
  // Merge attributes from previous declarations.
1263
17.5k
  if (PrevDecl)
1264
4.73k
    mergeDeclAttributes(PDecl, PrevDecl);
1265
1266
17.5k
  if (!err && 
NumProtoRefs17.5k
) {
1267
    /// Check then save referenced protocols.
1268
13.0k
    diagnoseUseOfProtocols(*this, PDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1269
13.0k
                           NumProtoRefs, ProtoLocs);
1270
13.0k
    PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
1271
13.0k
                           ProtoLocs, Context);
1272
13.0k
  }
1273
1274
17.5k
  CheckObjCDeclScope(PDecl);
1275
17.5k
  return ActOnObjCContainerStartDefinition(PDecl);
1276
17.5k
}
1277
1278
static bool NestedProtocolHasNoDefinition(ObjCProtocolDecl *PDecl,
1279
61.8k
                                          ObjCProtocolDecl *&UndefinedProtocol) {
1280
61.8k
  if (!PDecl->hasDefinition() ||
1281
61.8k
      
!PDecl->getDefinition()->isUnconditionallyVisible()61.8k
) {
1282
12
    UndefinedProtocol = PDecl;
1283
12
    return true;
1284
12
  }
1285
1286
61.8k
  for (auto *PI : PDecl->protocols())
1287
18.9k
    if (NestedProtocolHasNoDefinition(PI, UndefinedProtocol)) {
1288
1
      UndefinedProtocol = PI;
1289
1
      return true;
1290
1
    }
1291
61.8k
  return false;
1292
61.8k
}
1293
1294
/// FindProtocolDeclaration - This routine looks up protocols and
1295
/// issues an error if they are not declared. It returns list of
1296
/// protocol declarations in its 'Protocols' argument.
1297
void
1298
Sema::FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
1299
                              ArrayRef<IdentifierLocPair> ProtocolId,
1300
15.3k
                              SmallVectorImpl<Decl *> &Protocols) {
1301
15.9k
  for (const IdentifierLocPair &Pair : ProtocolId) {
1302
15.9k
    ObjCProtocolDecl *PDecl = LookupProtocol(Pair.first, Pair.second);
1303
15.9k
    if (!PDecl) {
1304
2
      DeclFilterCCC<ObjCProtocolDecl> CCC{};
1305
2
      TypoCorrection Corrected = CorrectTypo(
1306
2
          DeclarationNameInfo(Pair.first, Pair.second), LookupObjCProtocolName,
1307
2
          TUScope, nullptr, CCC, CTK_ErrorRecovery);
1308
2
      if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>()))
1309
1
        diagnoseTypo(Corrected, PDiag(diag::err_undeclared_protocol_suggest)
1310
1
                                    << Pair.first);
1311
2
    }
1312
1313
15.9k
    if (!PDecl) {
1314
1
      Diag(Pair.second, diag::err_undeclared_protocol) << Pair.first;
1315
1
      continue;
1316
1
    }
1317
    // If this is a forward protocol declaration, get its definition.
1318
15.9k
    if (!PDecl->isThisDeclarationADefinition() && 
PDecl->getDefinition()205
)
1319
184
      PDecl = PDecl->getDefinition();
1320
1321
    // For an objc container, delay protocol reference checking until after we
1322
    // can set the objc decl as the availability context, otherwise check now.
1323
15.9k
    if (!ForObjCContainer) {
1324
18
      (void)DiagnoseUseOfDecl(PDecl, Pair.second);
1325
18
    }
1326
1327
    // If this is a forward declaration and we are supposed to warn in this
1328
    // case, do it.
1329
    // FIXME: Recover nicely in the hidden case.
1330
15.9k
    ObjCProtocolDecl *UndefinedProtocol;
1331
1332
15.9k
    if (WarnOnDeclarations &&
1333
15.9k
        
NestedProtocolHasNoDefinition(PDecl, UndefinedProtocol)2.85k
) {
1334
10
      Diag(Pair.second, diag::warn_undef_protocolref) << Pair.first;
1335
10
      Diag(UndefinedProtocol->getLocation(), diag::note_protocol_decl_undefined)
1336
10
        << UndefinedProtocol;
1337
10
    }
1338
15.9k
    Protocols.push_back(PDecl);
1339
15.9k
  }
1340
15.3k
}
1341
1342
namespace {
1343
// Callback to only accept typo corrections that are either
1344
// Objective-C protocols or valid Objective-C type arguments.
1345
class ObjCTypeArgOrProtocolValidatorCCC final
1346
    : public CorrectionCandidateCallback {
1347
  ASTContext &Context;
1348
  Sema::LookupNameKind LookupKind;
1349
 public:
1350
  ObjCTypeArgOrProtocolValidatorCCC(ASTContext &context,
1351
                                    Sema::LookupNameKind lookupKind)
1352
8
    : Context(context), LookupKind(lookupKind) { }
1353
1354
4
  bool ValidateCandidate(const TypoCorrection &candidate) override {
1355
    // If we're allowed to find protocols and we have a protocol, accept it.
1356
4
    if (LookupKind != Sema::LookupOrdinaryName) {
1357
3
      if (candidate.getCorrectionDeclAs<ObjCProtocolDecl>())
1358
2
        return true;
1359
3
    }
1360
1361
    // If we're allowed to find type names and we have one, accept it.
1362
2
    if (LookupKind != Sema::LookupObjCProtocolName) {
1363
      // If we have a type declaration, we might accept this result.
1364
2
      if (auto typeDecl = candidate.getCorrectionDeclAs<TypeDecl>()) {
1365
        // If we found a tag declaration outside of C++, skip it. This
1366
        // can happy because we look for any name when there is no
1367
        // bias to protocol or type names.
1368
1
        if (isa<RecordDecl>(typeDecl) && 
!Context.getLangOpts().CPlusPlus0
)
1369
0
          return false;
1370
1371
        // Make sure the type is something we would accept as a type
1372
        // argument.
1373
1
        auto type = Context.getTypeDeclType(typeDecl);
1374
1
        if (type->isObjCObjectPointerType() ||
1375
1
            
type->isBlockPointerType()0
||
1376
1
            
type->isDependentType()0
||
1377
1
            
type->isObjCObjectType()0
)
1378
1
          return true;
1379
1380
0
        return false;
1381
1
      }
1382
1383
      // If we have an Objective-C class type, accept it; there will
1384
      // be another fix to add the '*'.
1385
1
      if (candidate.getCorrectionDeclAs<ObjCInterfaceDecl>())
1386
1
        return true;
1387
1388
0
      return false;
1389
1
    }
1390
1391
0
    return false;
1392
2
  }
1393
1394
8
  std::unique_ptr<CorrectionCandidateCallback> clone() override {
1395
8
    return std::make_unique<ObjCTypeArgOrProtocolValidatorCCC>(*this);
1396
8
  }
1397
};
1398
} // end anonymous namespace
1399
1400
void Sema::DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
1401
                                        SourceLocation ProtocolLoc,
1402
                                        IdentifierInfo *TypeArgId,
1403
                                        SourceLocation TypeArgLoc,
1404
4
                                        bool SelectProtocolFirst) {
1405
4
  Diag(TypeArgLoc, diag::err_objc_type_args_and_protocols)
1406
4
      << SelectProtocolFirst << TypeArgId << ProtocolId
1407
4
      << SourceRange(ProtocolLoc);
1408
4
}
1409
1410
void Sema::actOnObjCTypeArgsOrProtocolQualifiers(
1411
       Scope *S,
1412
       ParsedType baseType,
1413
       SourceLocation lAngleLoc,
1414
       ArrayRef<IdentifierInfo *> identifiers,
1415
       ArrayRef<SourceLocation> identifierLocs,
1416
       SourceLocation rAngleLoc,
1417
       SourceLocation &typeArgsLAngleLoc,
1418
       SmallVectorImpl<ParsedType> &typeArgs,
1419
       SourceLocation &typeArgsRAngleLoc,
1420
       SourceLocation &protocolLAngleLoc,
1421
       SmallVectorImpl<Decl *> &protocols,
1422
       SourceLocation &protocolRAngleLoc,
1423
103k
       bool warnOnIncompleteProtocols) {
1424
  // Local function that updates the declaration specifiers with
1425
  // protocol information.
1426
103k
  unsigned numProtocolsResolved = 0;
1427
103k
  auto resolvedAsProtocols = [&] {
1428
46.4k
    assert(numProtocolsResolved == identifiers.size() && "Unresolved protocols");
1429
1430
    // Determine whether the base type is a parameterized class, in
1431
    // which case we want to warn about typos such as
1432
    // "NSArray<NSObject>" (that should be NSArray<NSObject *>).
1433
0
    ObjCInterfaceDecl *baseClass = nullptr;
1434
46.4k
    QualType base = GetTypeFromParser(baseType, nullptr);
1435
46.4k
    bool allAreTypeNames = false;
1436
46.4k
    SourceLocation firstClassNameLoc;
1437
46.4k
    if (!base.isNull()) {
1438
22.3k
      if (const auto *objcObjectType = base->getAs<ObjCObjectType>()) {
1439
5.08k
        baseClass = objcObjectType->getInterface();
1440
5.08k
        if (baseClass) {
1441
5.08k
          if (auto typeParams = baseClass->getTypeParamList()) {
1442
25
            if (typeParams->size() == numProtocolsResolved) {
1443
              // Note that we should be looking for type names, too.
1444
12
              allAreTypeNames = true;
1445
12
            }
1446
25
          }
1447
5.08k
        }
1448
5.08k
      }
1449
22.3k
    }
1450
1451
109k
    for (unsigned i = 0, n = protocols.size(); i != n; 
++i63.2k
) {
1452
63.2k
      ObjCProtocolDecl *&proto
1453
63.2k
        = reinterpret_cast<ObjCProtocolDecl *&>(protocols[i]);
1454
      // For an objc container, delay protocol reference checking until after we
1455
      // can set the objc decl as the availability context, otherwise check now.
1456
63.2k
      if (!warnOnIncompleteProtocols) {
1457
23.2k
        (void)DiagnoseUseOfDecl(proto, identifierLocs[i]);
1458
23.2k
      }
1459
1460
      // If this is a forward protocol declaration, get its definition.
1461
63.2k
      if (!proto->isThisDeclarationADefinition() && 
proto->getDefinition()7.16k
)
1462
567
        proto = proto->getDefinition();
1463
1464
      // If this is a forward declaration and we are supposed to warn in this
1465
      // case, do it.
1466
      // FIXME: Recover nicely in the hidden case.
1467
63.2k
      ObjCProtocolDecl *forwardDecl = nullptr;
1468
63.2k
      if (warnOnIncompleteProtocols &&
1469
63.2k
          
NestedProtocolHasNoDefinition(proto, forwardDecl)40.0k
) {
1470
2
        Diag(identifierLocs[i], diag::warn_undef_protocolref)
1471
2
          << proto->getDeclName();
1472
2
        Diag(forwardDecl->getLocation(), diag::note_protocol_decl_undefined)
1473
2
          << forwardDecl;
1474
2
      }
1475
1476
      // If everything this far has been a type name (and we care
1477
      // about such things), check whether this name refers to a type
1478
      // as well.
1479
63.2k
      if (allAreTypeNames) {
1480
14
        if (auto *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
1481
14
                                          LookupOrdinaryName)) {
1482
3
          if (isa<ObjCInterfaceDecl>(decl)) {
1483
3
            if (firstClassNameLoc.isInvalid())
1484
2
              firstClassNameLoc = identifierLocs[i];
1485
3
          } else 
if (0
!isa<TypeDecl>(decl)0
) {
1486
            // Not a type.
1487
0
            allAreTypeNames = false;
1488
0
          }
1489
11
        } else {
1490
11
          allAreTypeNames = false;
1491
11
        }
1492
14
      }
1493
63.2k
    }
1494
1495
    // All of the protocols listed also have type names, and at least
1496
    // one is an Objective-C class name. Check whether all of the
1497
    // protocol conformances are declared by the base class itself, in
1498
    // which case we warn.
1499
46.4k
    if (allAreTypeNames && 
firstClassNameLoc.isValid()1
) {
1500
1
      llvm::SmallPtrSet<ObjCProtocolDecl*, 8> knownProtocols;
1501
1
      Context.CollectInheritedProtocols(baseClass, knownProtocols);
1502
1
      bool allProtocolsDeclared = true;
1503
1
      for (auto proto : protocols) {
1504
1
        if (knownProtocols.count(static_cast<ObjCProtocolDecl *>(proto)) == 0) {
1505
0
          allProtocolsDeclared = false;
1506
0
          break;
1507
0
        }
1508
1
      }
1509
1510
1
      if (allProtocolsDeclared) {
1511
1
        Diag(firstClassNameLoc, diag::warn_objc_redundant_qualified_class_type)
1512
1
          << baseClass->getDeclName() << SourceRange(lAngleLoc, rAngleLoc)
1513
1
          << FixItHint::CreateInsertion(getLocForEndOfToken(firstClassNameLoc),
1514
1
                                        " *");
1515
1
      }
1516
1
    }
1517
1518
46.4k
    protocolLAngleLoc = lAngleLoc;
1519
46.4k
    protocolRAngleLoc = rAngleLoc;
1520
46.4k
    assert(protocols.size() == identifierLocs.size());
1521
46.4k
  };
1522
1523
  // Attempt to resolve all of the identifiers as protocols.
1524
235k
  for (unsigned i = 0, n = identifiers.size(); i != n; 
++i132k
) {
1525
132k
    ObjCProtocolDecl *proto = LookupProtocol(identifiers[i], identifierLocs[i]);
1526
132k
    protocols.push_back(proto);
1527
132k
    if (proto)
1528
63.2k
      ++numProtocolsResolved;
1529
132k
  }
1530
1531
  // If all of the names were protocols, these were protocol qualifiers.
1532
103k
  if (numProtocolsResolved == identifiers.size())
1533
46.4k
    return resolvedAsProtocols();
1534
1535
  // Attempt to resolve all of the identifiers as type names or
1536
  // Objective-C class names. The latter is technically ill-formed,
1537
  // but is probably something like \c NSArray<NSView *> missing the
1538
  // \c*.
1539
57.0k
  typedef llvm::PointerUnion<TypeDecl *, ObjCInterfaceDecl *> TypeOrClassDecl;
1540
57.0k
  SmallVector<TypeOrClassDecl, 4> typeDecls;
1541
57.0k
  unsigned numTypeDeclsResolved = 0;
1542
125k
  for (unsigned i = 0, n = identifiers.size(); i != n; 
++i68.8k
) {
1543
68.8k
    NamedDecl *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
1544
68.8k
                                       LookupOrdinaryName);
1545
68.8k
    if (!decl) {
1546
16
      typeDecls.push_back(TypeOrClassDecl());
1547
16
      continue;
1548
16
    }
1549
1550
68.7k
    if (auto typeDecl = dyn_cast<TypeDecl>(decl)) {
1551
68.7k
      typeDecls.push_back(typeDecl);
1552
68.7k
      ++numTypeDeclsResolved;
1553
68.7k
      continue;
1554
68.7k
    }
1555
1556
6
    if (auto objcClass = dyn_cast<ObjCInterfaceDecl>(decl)) {
1557
6
      typeDecls.push_back(objcClass);
1558
6
      ++numTypeDeclsResolved;
1559
6
      continue;
1560
6
    }
1561
1562
0
    typeDecls.push_back(TypeOrClassDecl());
1563
0
  }
1564
1565
57.0k
  AttributeFactory attrFactory;
1566
1567
  // Local function that forms a reference to the given type or
1568
  // Objective-C class declaration.
1569
57.0k
  auto resolveTypeReference = [&](TypeOrClassDecl typeDecl, SourceLocation loc)
1570
68.7k
                                -> TypeResult {
1571
    // Form declaration specifiers. They simply refer to the type.
1572
68.7k
    DeclSpec DS(attrFactory);
1573
68.7k
    const char* prevSpec; // unused
1574
68.7k
    unsigned diagID; // unused
1575
68.7k
    QualType type;
1576
68.7k
    if (auto *actualTypeDecl = typeDecl.dyn_cast<TypeDecl *>())
1577
68.7k
      type = Context.getTypeDeclType(actualTypeDecl);
1578
5
    else
1579
5
      type = Context.getObjCInterfaceType(typeDecl.get<ObjCInterfaceDecl *>());
1580
68.7k
    TypeSourceInfo *parsedTSInfo = Context.getTrivialTypeSourceInfo(type, loc);
1581
68.7k
    ParsedType parsedType = CreateParsedType(type, parsedTSInfo);
1582
68.7k
    DS.SetTypeSpecType(DeclSpec::TST_typename, loc, prevSpec, diagID,
1583
68.7k
                       parsedType, Context.getPrintingPolicy());
1584
    // Use the identifier location for the type source range.
1585
68.7k
    DS.SetRangeStart(loc);
1586
68.7k
    DS.SetRangeEnd(loc);
1587
1588
    // Form the declarator.
1589
68.7k
    Declarator D(DS, DeclaratorContext::TypeName);
1590
1591
    // If we have a typedef of an Objective-C class type that is missing a '*',
1592
    // add the '*'.
1593
68.7k
    if (type->getAs<ObjCInterfaceType>()) {
1594
5
      SourceLocation starLoc = getLocForEndOfToken(loc);
1595
5
      D.AddTypeInfo(DeclaratorChunk::getPointer(/*TypeQuals=*/0, starLoc,
1596
5
                                                SourceLocation(),
1597
5
                                                SourceLocation(),
1598
5
                                                SourceLocation(),
1599
5
                                                SourceLocation(),
1600
5
                                                SourceLocation()),
1601
5
                                                starLoc);
1602
1603
      // Diagnose the missing '*'.
1604
5
      Diag(loc, diag::err_objc_type_arg_missing_star)
1605
5
        << type
1606
5
        << FixItHint::CreateInsertion(starLoc, " *");
1607
5
    }
1608
1609
    // Convert this to a type.
1610
68.7k
    return ActOnTypeName(S, D);
1611
68.7k
  };
1612
1613
  // Local function that updates the declaration specifiers with
1614
  // type argument information.
1615
57.0k
  auto resolvedAsTypeDecls = [&] {
1616
    // We did not resolve these as protocols.
1617
57.0k
    protocols.clear();
1618
1619
57.0k
    assert(numTypeDeclsResolved == identifiers.size() && "Unresolved type decl");
1620
    // Map type declarations to type arguments.
1621
125k
    for (unsigned i = 0, n = identifiers.size(); i != n; 
++i68.7k
) {
1622
      // Map type reference to a type.
1623
68.7k
      TypeResult type = resolveTypeReference(typeDecls[i], identifierLocs[i]);
1624
68.7k
      if (!type.isUsable()) {
1625
0
        typeArgs.clear();
1626
0
        return;
1627
0
      }
1628
1629
68.7k
      typeArgs.push_back(type.get());
1630
68.7k
    }
1631
1632
57.0k
    typeArgsLAngleLoc = lAngleLoc;
1633
57.0k
    typeArgsRAngleLoc = rAngleLoc;
1634
57.0k
  };
1635
1636
  // If all of the identifiers can be resolved as type names or
1637
  // Objective-C class names, we have type arguments.
1638
57.0k
  if (numTypeDeclsResolved == identifiers.size())
1639
57.0k
    return resolvedAsTypeDecls();
1640
1641
  // Error recovery: some names weren't found, or we have a mix of
1642
  // type and protocol names. Go resolve all of the unresolved names
1643
  // and complain if we can't find a consistent answer.
1644
9
  LookupNameKind lookupKind = LookupAnyName;
1645
24
  for (unsigned i = 0, n = identifiers.size(); i != n; 
++i15
) {
1646
    // If we already have a protocol or type. Check whether it is the
1647
    // right thing.
1648
20
    if (protocols[i] || 
typeDecls[i]12
) {
1649
      // If we haven't figured out whether we want types or protocols
1650
      // yet, try to figure it out from this name.
1651
12
      if (lookupKind == LookupAnyName) {
1652
        // If this name refers to both a protocol and a type (e.g., \c
1653
        // NSObject), don't conclude anything yet.
1654
10
        if (protocols[i] && 
typeDecls[i]8
)
1655
4
          continue;
1656
1657
        // Otherwise, let this name decide whether we'll be correcting
1658
        // toward types or protocols.
1659
6
        lookupKind = protocols[i] ? 
LookupObjCProtocolName4
1660
6
                                  : 
LookupOrdinaryName2
;
1661
6
        continue;
1662
10
      }
1663
1664
      // If we want protocols and we have a protocol, there's nothing
1665
      // more to do.
1666
2
      if (lookupKind == LookupObjCProtocolName && 
protocols[i]1
)
1667
0
        continue;
1668
1669
      // If we want types and we have a type declaration, there's
1670
      // nothing more to do.
1671
2
      if (lookupKind == LookupOrdinaryName && 
typeDecls[i]1
)
1672
1
        continue;
1673
1674
      // We have a conflict: some names refer to protocols and others
1675
      // refer to types.
1676
1
      DiagnoseTypeArgsAndProtocols(identifiers[0], identifierLocs[0],
1677
1
                                   identifiers[i], identifierLocs[i],
1678
1
                                   protocols[i] != nullptr);
1679
1680
1
      protocols.clear();
1681
1
      typeArgs.clear();
1682
1
      return;
1683
2
    }
1684
1685
    // Perform typo correction on the name.
1686
8
    ObjCTypeArgOrProtocolValidatorCCC CCC(Context, lookupKind);
1687
8
    TypoCorrection corrected =
1688
8
        CorrectTypo(DeclarationNameInfo(identifiers[i], identifierLocs[i]),
1689
8
                    lookupKind, S, nullptr, CCC, CTK_ErrorRecovery);
1690
8
    if (corrected) {
1691
      // Did we find a protocol?
1692
4
      if (auto proto = corrected.getCorrectionDeclAs<ObjCProtocolDecl>()) {
1693
2
        diagnoseTypo(corrected,
1694
2
                     PDiag(diag::err_undeclared_protocol_suggest)
1695
2
                       << identifiers[i]);
1696
2
        lookupKind = LookupObjCProtocolName;
1697
2
        protocols[i] = proto;
1698
2
        ++numProtocolsResolved;
1699
2
        continue;
1700
2
      }
1701
1702
      // Did we find a type?
1703
2
      if (auto typeDecl = corrected.getCorrectionDeclAs<TypeDecl>()) {
1704
1
        diagnoseTypo(corrected,
1705
1
                     PDiag(diag::err_unknown_typename_suggest)
1706
1
                       << identifiers[i]);
1707
1
        lookupKind = LookupOrdinaryName;
1708
1
        typeDecls[i] = typeDecl;
1709
1
        ++numTypeDeclsResolved;
1710
1
        continue;
1711
1
      }
1712
1713
      // Did we find an Objective-C class?
1714
1
      if (auto objcClass = corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1715
1
        diagnoseTypo(corrected,
1716
1
                     PDiag(diag::err_unknown_type_or_class_name_suggest)
1717
1
                       << identifiers[i] << true);
1718
1
        lookupKind = LookupOrdinaryName;
1719
1
        typeDecls[i] = objcClass;
1720
1
        ++numTypeDeclsResolved;
1721
1
        continue;
1722
1
      }
1723
1
    }
1724
1725
    // We couldn't find anything.
1726
4
    Diag(identifierLocs[i],
1727
4
         (lookupKind == LookupAnyName ? 
diag::err_objc_type_arg_missing1
1728
4
          : 
lookupKind == LookupObjCProtocolName3
?
diag::err_undeclared_protocol2
1729
3
          : 
diag::err_unknown_typename1
))
1730
4
      << identifiers[i];
1731
4
    protocols.clear();
1732
4
    typeArgs.clear();
1733
4
    return;
1734
8
  }
1735
1736
  // If all of the names were (corrected to) protocols, these were
1737
  // protocol qualifiers.
1738
4
  if (numProtocolsResolved == identifiers.size())
1739
2
    return resolvedAsProtocols();
1740
1741
  // Otherwise, all of the names were (corrected to) types.
1742
2
  assert(numTypeDeclsResolved == identifiers.size() && "Not all types?");
1743
0
  return resolvedAsTypeDecls();
1744
4
}
1745
1746
/// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
1747
/// a class method in its extension.
1748
///
1749
void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
1750
846
                                            ObjCInterfaceDecl *ID) {
1751
846
  if (!ID)
1752
8
    return;  // Possibly due to previous error
1753
1754
838
  llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
1755
838
  for (auto *MD : ID->methods())
1756
4.89k
    MethodMap[MD->getSelector()] = MD;
1757
1758
838
  if (MethodMap.empty())
1759
197
    return;
1760
2.60k
  
for (const auto *Method : CAT->methods())641
{
1761
2.60k
    const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
1762
2.60k
    if (PrevMethod &&
1763
2.60k
        
(PrevMethod->isInstanceMethod() == Method->isInstanceMethod())31
&&
1764
2.60k
        
!MatchTwoMethodDeclarations(Method, PrevMethod)29
) {
1765
3
      Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1766
3
            << Method->getDeclName();
1767
3
      Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1768
3
    }
1769
2.60k
  }
1770
641
}
1771
1772
/// ActOnForwardProtocolDeclaration - Handle \@protocol foo;
1773
Sema::DeclGroupPtrTy
1774
Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
1775
                                      ArrayRef<IdentifierLocPair> IdentList,
1776
4.69k
                                      const ParsedAttributesView &attrList) {
1777
4.69k
  SmallVector<Decl *, 8> DeclsInGroup;
1778
5.42k
  for (const IdentifierLocPair &IdentPair : IdentList) {
1779
5.42k
    IdentifierInfo *Ident = IdentPair.first;
1780
5.42k
    ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentPair.second,
1781
5.42k
                                                forRedeclarationInCurContext());
1782
5.42k
    ObjCProtocolDecl *PDecl
1783
5.42k
      = ObjCProtocolDecl::Create(Context, CurContext, Ident,
1784
5.42k
                                 IdentPair.second, AtProtocolLoc,
1785
5.42k
                                 PrevDecl);
1786
1787
5.42k
    PushOnScopeChains(PDecl, TUScope);
1788
5.42k
    CheckObjCDeclScope(PDecl);
1789
1790
5.42k
    ProcessDeclAttributeList(TUScope, PDecl, attrList);
1791
5.42k
    AddPragmaAttributes(TUScope, PDecl);
1792
1793
5.42k
    if (PrevDecl)
1794
307
      mergeDeclAttributes(PDecl, PrevDecl);
1795
1796
5.42k
    DeclsInGroup.push_back(PDecl);
1797
5.42k
  }
1798
1799
4.69k
  return BuildDeclaratorGroup(DeclsInGroup);
1800
4.69k
}
1801
1802
Decl *Sema::ActOnStartCategoryInterface(
1803
    SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
1804
    SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
1805
    IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
1806
    Decl *const *ProtoRefs, unsigned NumProtoRefs,
1807
    const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
1808
40.7k
    const ParsedAttributesView &AttrList) {
1809
40.7k
  ObjCCategoryDecl *CDecl;
1810
40.7k
  ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
1811
1812
  /// Check that class of this category is already completely declared.
1813
1814
40.7k
  if (!IDecl
1815
40.7k
      || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1816
40.7k
                             diag::err_category_forward_interface,
1817
40.7k
                             CategoryName == nullptr)) {
1818
    // Create an invalid ObjCCategoryDecl to serve as context for
1819
    // the enclosing method declarations.  We mark the decl invalid
1820
    // to make it clear that this isn't a valid AST.
1821
22
    CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
1822
22
                                     ClassLoc, CategoryLoc, CategoryName,
1823
22
                                     IDecl, typeParamList);
1824
22
    CDecl->setInvalidDecl();
1825
22
    CurContext->addDecl(CDecl);
1826
1827
22
    if (!IDecl)
1828
21
      Diag(ClassLoc, diag::err_undef_interface) << ClassName;
1829
22
    return ActOnObjCContainerStartDefinition(CDecl);
1830
22
  }
1831
1832
40.7k
  if (!CategoryName && 
IDecl->getImplementation()838
) {
1833
1
    Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
1834
1
    Diag(IDecl->getImplementation()->getLocation(),
1835
1
          diag::note_implementation_declared);
1836
1
  }
1837
1838
40.7k
  if (CategoryName) {
1839
    /// Check for duplicate interface declaration for this category
1840
39.8k
    if (ObjCCategoryDecl *Previous
1841
39.8k
          = IDecl->FindCategoryDeclaration(CategoryName)) {
1842
      // Class extensions can be declared multiple times, categories cannot.
1843
25
      Diag(CategoryLoc, diag::warn_dup_category_def)
1844
25
        << ClassName << CategoryName;
1845
25
      Diag(Previous->getLocation(), diag::note_previous_definition);
1846
25
    }
1847
39.8k
  }
1848
1849
  // If we have a type parameter list, check it.
1850
40.7k
  if (typeParamList) {
1851
10.1k
    if (auto prevTypeParamList = IDecl->getTypeParamList()) {
1852
10.1k
      if (checkTypeParamListConsistency(*this, prevTypeParamList, typeParamList,
1853
10.1k
                                        CategoryName
1854
10.1k
                                          ? 
TypeParamListContext::Category10.1k
1855
10.1k
                                          : 
TypeParamListContext::Extension9
))
1856
2
        typeParamList = nullptr;
1857
10.1k
    } else {
1858
2
      Diag(typeParamList->getLAngleLoc(),
1859
2
           diag::err_objc_parameterized_category_nonclass)
1860
2
        << (CategoryName != nullptr)
1861
2
        << ClassName
1862
2
        << typeParamList->getSourceRange();
1863
1864
2
      typeParamList = nullptr;
1865
2
    }
1866
10.1k
  }
1867
1868
40.7k
  CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
1869
40.7k
                                   ClassLoc, CategoryLoc, CategoryName, IDecl,
1870
40.7k
                                   typeParamList);
1871
  // FIXME: PushOnScopeChains?
1872
40.7k
  CurContext->addDecl(CDecl);
1873
1874
  // Process the attributes before looking at protocols to ensure that the
1875
  // availability attribute is attached to the category to provide availability
1876
  // checking for protocol uses.
1877
40.7k
  ProcessDeclAttributeList(TUScope, CDecl, AttrList);
1878
40.7k
  AddPragmaAttributes(TUScope, CDecl);
1879
1880
40.7k
  if (NumProtoRefs) {
1881
1.03k
    diagnoseUseOfProtocols(*this, CDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1882
1.03k
                           NumProtoRefs, ProtoLocs);
1883
1.03k
    CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
1884
1.03k
                           ProtoLocs, Context);
1885
    // Protocols in the class extension belong to the class.
1886
1.03k
    if (CDecl->IsClassExtension())
1887
123
     IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs,
1888
123
                                            NumProtoRefs, Context);
1889
1.03k
  }
1890
1891
40.7k
  CheckObjCDeclScope(CDecl);
1892
40.7k
  return ActOnObjCContainerStartDefinition(CDecl);
1893
40.7k
}
1894
1895
/// ActOnStartCategoryImplementation - Perform semantic checks on the
1896
/// category implementation declaration and build an ObjCCategoryImplDecl
1897
/// object.
1898
Decl *Sema::ActOnStartCategoryImplementation(
1899
                      SourceLocation AtCatImplLoc,
1900
                      IdentifierInfo *ClassName, SourceLocation ClassLoc,
1901
                      IdentifierInfo *CatName, SourceLocation CatLoc,
1902
518
                      const ParsedAttributesView &Attrs) {
1903
518
  ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
1904
518
  ObjCCategoryDecl *CatIDecl = nullptr;
1905
518
  if (IDecl && 
IDecl->hasDefinition()505
) {
1906
503
    CatIDecl = IDecl->FindCategoryDeclaration(CatName);
1907
503
    if (!CatIDecl) {
1908
      // Category @implementation with no corresponding @interface.
1909
      // Create and install one.
1910
110
      CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc,
1911
110
                                          ClassLoc, CatLoc,
1912
110
                                          CatName, IDecl,
1913
110
                                          /*typeParamList=*/nullptr);
1914
110
      CatIDecl->setImplicit();
1915
110
    }
1916
503
  }
1917
1918
518
  ObjCCategoryImplDecl *CDecl =
1919
518
    ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl,
1920
518
                                 ClassLoc, AtCatImplLoc, CatLoc);
1921
  /// Check that class of this category is already completely declared.
1922
518
  if (!IDecl) {
1923
13
    Diag(ClassLoc, diag::err_undef_interface) << ClassName;
1924
13
    CDecl->setInvalidDecl();
1925
505
  } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1926
505
                                 diag::err_undef_interface)) {
1927
2
    CDecl->setInvalidDecl();
1928
2
  }
1929
1930
518
  ProcessDeclAttributeList(TUScope, CDecl, Attrs);
1931
518
  AddPragmaAttributes(TUScope, CDecl);
1932
1933
  // FIXME: PushOnScopeChains?
1934
518
  CurContext->addDecl(CDecl);
1935
1936
  // If the interface has the objc_runtime_visible attribute, we
1937
  // cannot implement a category for it.
1938
518
  if (IDecl && 
IDecl->hasAttr<ObjCRuntimeVisibleAttr>()505
) {
1939
1
    Diag(ClassLoc, diag::err_objc_runtime_visible_category)
1940
1
      << IDecl->getDeclName();
1941
1
  }
1942
1943
  /// Check that CatName, category name, is not used in another implementation.
1944
518
  if (CatIDecl) {
1945
503
    if (CatIDecl->getImplementation()) {
1946
1
      Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
1947
1
        << CatName;
1948
1
      Diag(CatIDecl->getImplementation()->getLocation(),
1949
1
           diag::note_previous_definition);
1950
1
      CDecl->setInvalidDecl();
1951
502
    } else {
1952
502
      CatIDecl->setImplementation(CDecl);
1953
      // Warn on implementating category of deprecated class under
1954
      // -Wdeprecated-implementations flag.
1955
502
      DiagnoseObjCImplementedDeprecations(*this, CatIDecl,
1956
502
                                          CDecl->getLocation());
1957
502
    }
1958
503
  }
1959
1960
518
  CheckObjCDeclScope(CDecl);
1961
518
  return ActOnObjCContainerStartDefinition(CDecl);
1962
518
}
1963
1964
Decl *Sema::ActOnStartClassImplementation(
1965
                      SourceLocation AtClassImplLoc,
1966
                      IdentifierInfo *ClassName, SourceLocation ClassLoc,
1967
                      IdentifierInfo *SuperClassname,
1968
                      SourceLocation SuperClassLoc,
1969
4.81k
                      const ParsedAttributesView &Attrs) {
1970
4.81k
  ObjCInterfaceDecl *IDecl = nullptr;
1971
  // Check for another declaration kind with the same name.
1972
4.81k
  NamedDecl *PrevDecl
1973
4.81k
    = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
1974
4.81k
                       forRedeclarationInCurContext());
1975
4.81k
  if (PrevDecl && 
!isa<ObjCInterfaceDecl>(PrevDecl)4.75k
) {
1976
1
    Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
1977
1
    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1978
4.81k
  } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
1979
    // FIXME: This will produce an error if the definition of the interface has
1980
    // been imported from a module but is not visible.
1981
4.75k
    RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1982
4.75k
                        diag::warn_undef_interface);
1983
4.75k
  } else {
1984
    // We did not find anything with the name ClassName; try to correct for
1985
    // typos in the class name.
1986
61
    ObjCInterfaceValidatorCCC CCC{};
1987
61
    TypoCorrection Corrected =
1988
61
        CorrectTypo(DeclarationNameInfo(ClassName, ClassLoc),
1989
61
                    LookupOrdinaryName, TUScope, nullptr, CCC, CTK_NonError);
1990
61
    if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1991
      // Suggest the (potentially) correct interface name. Don't provide a
1992
      // code-modification hint or use the typo name for recovery, because
1993
      // this is just a warning. The program may actually be correct.
1994
5
      diagnoseTypo(Corrected,
1995
5
                   PDiag(diag::warn_undef_interface_suggest) << ClassName,
1996
5
                   /*ErrorRecovery*/false);
1997
56
    } else {
1998
56
      Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
1999
56
    }
2000
61
  }
2001
2002
  // Check that super class name is valid class name
2003
4.81k
  ObjCInterfaceDecl *SDecl = nullptr;
2004
4.81k
  if (SuperClassname) {
2005
    // Check if a different kind of symbol declared in this scope.
2006
49
    PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
2007
49
                                LookupOrdinaryName);
2008
49
    if (PrevDecl && 
!isa<ObjCInterfaceDecl>(PrevDecl)48
) {
2009
1
      Diag(SuperClassLoc, diag::err_redefinition_different_kind)
2010
1
        << SuperClassname;
2011
1
      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2012
48
    } else {
2013
48
      SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
2014
48
      if (SDecl && 
!SDecl->hasDefinition()47
)
2015
1
        SDecl = nullptr;
2016
48
      if (!SDecl)
2017
2
        Diag(SuperClassLoc, diag::err_undef_superclass)
2018
2
          << SuperClassname << ClassName;
2019
46
      else if (IDecl && 
!declaresSameEntity(IDecl->getSuperClass(), SDecl)35
) {
2020
        // This implementation and its interface do not have the same
2021
        // super class.
2022
2
        Diag(SuperClassLoc, diag::err_conflicting_super_class)
2023
2
          << SDecl->getDeclName();
2024
2
        Diag(SDecl->getLocation(), diag::note_previous_definition);
2025
2
      }
2026
48
    }
2027
49
  }
2028
2029
4.81k
  if (!IDecl) {
2030
    // Legacy case of @implementation with no corresponding @interface.
2031
    // Build, chain & install the interface decl into the identifier.
2032
2033
    // FIXME: Do we support attributes on the @implementation? If so we should
2034
    // copy them over.
2035
62
    IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
2036
62
                                      ClassName, /*typeParamList=*/nullptr,
2037
62
                                      /*PrevDecl=*/nullptr, ClassLoc,
2038
62
                                      true);
2039
62
    AddPragmaAttributes(TUScope, IDecl);
2040
62
    IDecl->startDefinition();
2041
62
    if (SDecl) {
2042
11
      IDecl->setSuperClass(Context.getTrivialTypeSourceInfo(
2043
11
                             Context.getObjCInterfaceType(SDecl),
2044
11
                             SuperClassLoc));
2045
11
      IDecl->setEndOfDefinitionLoc(SuperClassLoc);
2046
51
    } else {
2047
51
      IDecl->setEndOfDefinitionLoc(ClassLoc);
2048
51
    }
2049
2050
62
    PushOnScopeChains(IDecl, TUScope);
2051
4.75k
  } else {
2052
    // Mark the interface as being completed, even if it was just as
2053
    //   @class ....;
2054
    // declaration; the user cannot reopen it.
2055
4.75k
    if (!IDecl->hasDefinition())
2056
4
      IDecl->startDefinition();
2057
4.75k
  }
2058
2059
4.81k
  ObjCImplementationDecl* IMPDecl =
2060
4.81k
    ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl,
2061
4.81k
                                   ClassLoc, AtClassImplLoc, SuperClassLoc);
2062
2063
4.81k
  ProcessDeclAttributeList(TUScope, IMPDecl, Attrs);
2064
4.81k
  AddPragmaAttributes(TUScope, IMPDecl);
2065
2066
4.81k
  if (CheckObjCDeclScope(IMPDecl))
2067
2
    return ActOnObjCContainerStartDefinition(IMPDecl);
2068
2069
  // Check that there is no duplicate implementation of this class.
2070
4.81k
  if (IDecl->getImplementation()) {
2071
    // FIXME: Don't leak everything!
2072
3
    Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
2073
3
    Diag(IDecl->getImplementation()->getLocation(),
2074
3
         diag::note_previous_definition);
2075
3
    IMPDecl->setInvalidDecl();
2076
4.80k
  } else { // add it to the list.
2077
4.80k
    IDecl->setImplementation(IMPDecl);
2078
4.80k
    PushOnScopeChains(IMPDecl, TUScope);
2079
    // Warn on implementating deprecated class under
2080
    // -Wdeprecated-implementations flag.
2081
4.80k
    DiagnoseObjCImplementedDeprecations(*this, IDecl, IMPDecl->getLocation());
2082
4.80k
  }
2083
2084
  // If the superclass has the objc_runtime_visible attribute, we
2085
  // cannot implement a subclass of it.
2086
4.81k
  if (IDecl->getSuperClass() &&
2087
4.81k
      
IDecl->getSuperClass()->hasAttr<ObjCRuntimeVisibleAttr>()2.18k
) {
2088
1
    Diag(ClassLoc, diag::err_objc_runtime_visible_subclass)
2089
1
      << IDecl->getDeclName()
2090
1
      << IDecl->getSuperClass()->getDeclName();
2091
1
  }
2092
2093
4.81k
  return ActOnObjCContainerStartDefinition(IMPDecl);
2094
4.81k
}
2095
2096
Sema::DeclGroupPtrTy
2097
5.33k
Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) {
2098
5.33k
  SmallVector<Decl *, 64> DeclsInGroup;
2099
5.33k
  DeclsInGroup.reserve(Decls.size() + 1);
2100
2101
13.3k
  for (unsigned i = 0, e = Decls.size(); i != e; 
++i8.04k
) {
2102
8.04k
    Decl *Dcl = Decls[i];
2103
8.04k
    if (!Dcl)
2104
0
      continue;
2105
8.04k
    if (Dcl->getDeclContext()->isFileContext())
2106
187
      Dcl->setTopLevelDeclInObjCContainer();
2107
8.04k
    DeclsInGroup.push_back(Dcl);
2108
8.04k
  }
2109
2110
5.33k
  DeclsInGroup.push_back(ObjCImpDecl);
2111
2112
5.33k
  return BuildDeclaratorGroup(DeclsInGroup);
2113
5.33k
}
2114
2115
void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
2116
                                    ObjCIvarDecl **ivars, unsigned numIvars,
2117
225
                                    SourceLocation RBrace) {
2118
225
  assert(ImpDecl && "missing implementation decl");
2119
0
  ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
2120
225
  if (!IDecl)
2121
0
    return;
2122
  /// Check case of non-existing \@interface decl.
2123
  /// (legacy objective-c \@implementation decl without an \@interface decl).
2124
  /// Add implementations's ivar to the synthesize class's ivar list.
2125
225
  if (IDecl->isImplicitInterfaceDecl()) {
2126
10
    IDecl->setEndOfDefinitionLoc(RBrace);
2127
    // Add ivar's to class's DeclContext.
2128
25
    for (unsigned i = 0, e = numIvars; i != e; 
++i15
) {
2129
15
      ivars[i]->setLexicalDeclContext(ImpDecl);
2130
      // In a 'fragile' runtime the ivar was added to the implicit
2131
      // ObjCInterfaceDecl while in a 'non-fragile' runtime the ivar is
2132
      // only in the ObjCImplementationDecl. In the non-fragile case the ivar
2133
      // therefore also needs to be propagated to the ObjCInterfaceDecl.
2134
15
      if (!LangOpts.ObjCRuntime.isFragile())
2135
10
        IDecl->makeDeclVisibleInContext(ivars[i]);
2136
15
      ImpDecl->addDecl(ivars[i]);
2137
15
    }
2138
2139
10
    return;
2140
10
  }
2141
  // If implementation has empty ivar list, just return.
2142
215
  if (numIvars == 0)
2143
10
    return;
2144
2145
205
  assert(ivars && "missing @implementation ivars");
2146
205
  if (LangOpts.ObjCRuntime.isNonFragile()) {
2147
196
    if (ImpDecl->getSuperClass())
2148
6
      Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
2149
462
    for (unsigned i = 0; i < numIvars; 
i++266
) {
2150
266
      ObjCIvarDecl* ImplIvar = ivars[i];
2151
266
      if (const ObjCIvarDecl *ClsIvar =
2152
266
            IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
2153
2
        Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
2154
2
        Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2155
2
        continue;
2156
2
      }
2157
      // Check class extensions (unnamed categories) for duplicate ivars.
2158
264
      for (const auto *CDecl : IDecl->visible_extensions()) {
2159
91
        if (const ObjCIvarDecl *ClsExtIvar =
2160
91
            CDecl->getIvarDecl(ImplIvar->getIdentifier())) {
2161
5
          Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
2162
5
          Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
2163
5
          continue;
2164
5
        }
2165
91
      }
2166
      // Instance ivar to Implementation's DeclContext.
2167
264
      ImplIvar->setLexicalDeclContext(ImpDecl);
2168
264
      IDecl->makeDeclVisibleInContext(ImplIvar);
2169
264
      ImpDecl->addDecl(ImplIvar);
2170
264
    }
2171
196
    return;
2172
196
  }
2173
  // Check interface's Ivar list against those in the implementation.
2174
  // names and types must match.
2175
  //
2176
9
  unsigned j = 0;
2177
9
  ObjCInterfaceDecl::ivar_iterator
2178
9
    IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
2179
21
  for (; numIvars > 0 && 
IVI != IVE13
;
++IVI12
) {
2180
12
    ObjCIvarDecl* ImplIvar = ivars[j++];
2181
12
    ObjCIvarDecl* ClsIvar = *IVI;
2182
12
    assert (ImplIvar && "missing implementation ivar");
2183
0
    assert (ClsIvar && "missing class ivar");
2184
2185
    // First, make sure the types match.
2186
12
    if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) {
2187
2
      Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
2188
2
        << ImplIvar->getIdentifier()
2189
2
        << ImplIvar->getType() << ClsIvar->getType();
2190
2
      Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2191
10
    } else if (ImplIvar->isBitField() && 
ClsIvar->isBitField()3
&&
2192
10
               ImplIvar->getBitWidthValue(Context) !=
2193
3
               ClsIvar->getBitWidthValue(Context)) {
2194
1
      Diag(ImplIvar->getBitWidth()->getBeginLoc(),
2195
1
           diag::err_conflicting_ivar_bitwidth)
2196
1
          << ImplIvar->getIdentifier();
2197
1
      Diag(ClsIvar->getBitWidth()->getBeginLoc(),
2198
1
           diag::note_previous_definition);
2199
1
    }
2200
    // Make sure the names are identical.
2201
12
    if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
2202
1
      Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
2203
1
        << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
2204
1
      Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2205
1
    }
2206
12
    --numIvars;
2207
12
  }
2208
2209
9
  if (numIvars > 0)
2210
1
    Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count);
2211
8
  else if (IVI != IVE)
2212
1
    Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count);
2213
9
}
2214
2215
static void WarnUndefinedMethod(Sema &S, SourceLocation ImpLoc,
2216
                                ObjCMethodDecl *method,
2217
                                bool &IncompleteImpl,
2218
                                unsigned DiagID,
2219
1.34k
                                NamedDecl *NeededFor = nullptr) {
2220
  // No point warning no definition of method which is 'unavailable'.
2221
1.34k
  if (method->getAvailability() == AR_Unavailable)
2222
23
    return;
2223
2224
  // FIXME: For now ignore 'IncompleteImpl'.
2225
  // Previously we grouped all unimplemented methods under a single
2226
  // warning, but some users strongly voiced that they would prefer
2227
  // separate warnings.  We will give that approach a try, as that
2228
  // matches what we do with protocols.
2229
1.32k
  {
2230
1.32k
    const Sema::SemaDiagnosticBuilder &B = S.Diag(ImpLoc, DiagID);
2231
1.32k
    B << method;
2232
1.32k
    if (NeededFor)
2233
132
      B << NeededFor;
2234
1.32k
  }
2235
2236
  // Issue a note to the original declaration.
2237
1.32k
  SourceLocation MethodLoc = method->getBeginLoc();
2238
1.32k
  if (MethodLoc.isValid())
2239
1.32k
    S.Diag(MethodLoc, diag::note_method_declared_at) << method;
2240
1.32k
}
2241
2242
/// Determines if type B can be substituted for type A.  Returns true if we can
2243
/// guarantee that anything that the user will do to an object of type A can
2244
/// also be done to an object of type B.  This is trivially true if the two
2245
/// types are the same, or if B is a subclass of A.  It becomes more complex
2246
/// in cases where protocols are involved.
2247
///
2248
/// Object types in Objective-C describe the minimum requirements for an
2249
/// object, rather than providing a complete description of a type.  For
2250
/// example, if A is a subclass of B, then B* may refer to an instance of A.
2251
/// The principle of substitutability means that we may use an instance of A
2252
/// anywhere that we may use an instance of B - it will implement all of the
2253
/// ivars of B and all of the methods of B.
2254
///
2255
/// This substitutability is important when type checking methods, because
2256
/// the implementation may have stricter type definitions than the interface.
2257
/// The interface specifies minimum requirements, but the implementation may
2258
/// have more accurate ones.  For example, a method may privately accept
2259
/// instances of B, but only publish that it accepts instances of A.  Any
2260
/// object passed to it will be type checked against B, and so will implicitly
2261
/// by a valid A*.  Similarly, a method may return a subclass of the class that
2262
/// it is declared as returning.
2263
///
2264
/// This is most important when considering subclassing.  A method in a
2265
/// subclass must accept any object as an argument that its superclass's
2266
/// implementation accepts.  It may, however, accept a more general type
2267
/// without breaking substitutability (i.e. you can still use the subclass
2268
/// anywhere that you can use the superclass, but not vice versa).  The
2269
/// converse requirement applies to return types: the return type for a
2270
/// subclass method must be a valid object of the kind that the superclass
2271
/// advertises, but it may be specified more accurately.  This avoids the need
2272
/// for explicit down-casting by callers.
2273
///
2274
/// Note: This is a stricter requirement than for assignment.
2275
static bool isObjCTypeSubstitutable(ASTContext &Context,
2276
                                    const ObjCObjectPointerType *A,
2277
                                    const ObjCObjectPointerType *B,
2278
6.64k
                                    bool rejectId) {
2279
  // Reject a protocol-unqualified id.
2280
6.64k
  if (rejectId && 
B->isObjCIdType()1.17k
)
return false880
;
2281
2282
  // If B is a qualified id, then A must also be a qualified id and it must
2283
  // implement all of the protocols in B.  It may not be a qualified class.
2284
  // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
2285
  // stricter definition so it is not substitutable for id<A>.
2286
5.76k
  if (B->isObjCQualifiedIdType()) {
2287
444
    return A->isObjCQualifiedIdType() &&
2288
444
           
Context.ObjCQualifiedIdTypesAreCompatible(A, B, false)440
;
2289
444
  }
2290
2291
  /*
2292
  // id is a special type that bypasses type checking completely.  We want a
2293
  // warning when it is used in one place but not another.
2294
  if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
2295
2296
2297
  // If B is a qualified id, then A must also be a qualified id (which it isn't
2298
  // if we've got this far)
2299
  if (B->isObjCQualifiedIdType()) return false;
2300
  */
2301
2302
  // Now we know that A and B are (potentially-qualified) class types.  The
2303
  // normal rules for assignment apply.
2304
5.31k
  return Context.canAssignObjCInterfaces(A, B);
2305
5.76k
}
2306
2307
2.62k
static SourceRange getTypeRange(TypeSourceInfo *TSI) {
2308
2.62k
  return (TSI ? 
TSI->getTypeLoc().getSourceRange()2.61k
:
SourceRange()10
);
2309
2.62k
}
2310
2311
/// Determine whether two set of Objective-C declaration qualifiers conflict.
2312
static bool objcModifiersConflict(Decl::ObjCDeclQualifier x,
2313
14.1k
                                  Decl::ObjCDeclQualifier y) {
2314
14.1k
  return (x & ~Decl::OBJC_TQ_CSNullability) !=
2315
14.1k
         (y & ~Decl::OBJC_TQ_CSNullability);
2316
14.1k
}
2317
2318
static bool CheckMethodOverrideReturn(Sema &S,
2319
                                      ObjCMethodDecl *MethodImpl,
2320
                                      ObjCMethodDecl *MethodDecl,
2321
                                      bool IsProtocolMethodDecl,
2322
                                      bool IsOverridingMode,
2323
52.8k
                                      bool Warn) {
2324
52.8k
  if (IsProtocolMethodDecl &&
2325
52.8k
      objcModifiersConflict(MethodDecl->getObjCDeclQualifier(),
2326
7.62k
                            MethodImpl->getObjCDeclQualifier())) {
2327
6
    if (Warn) {
2328
6
      S.Diag(MethodImpl->getLocation(),
2329
6
             (IsOverridingMode
2330
6
                  ? 
diag::warn_conflicting_overriding_ret_type_modifiers4
2331
6
                  : 
diag::warn_conflicting_ret_type_modifiers2
))
2332
6
          << MethodImpl->getDeclName()
2333
6
          << MethodImpl->getReturnTypeSourceRange();
2334
6
      S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
2335
6
          << MethodDecl->getReturnTypeSourceRange();
2336
6
    }
2337
0
    else
2338
0
      return false;
2339
6
  }
2340
52.8k
  if (Warn && 
IsOverridingMode52.8k
&&
2341
52.8k
      
!isa<ObjCImplementationDecl>(MethodImpl->getDeclContext())47.8k
&&
2342
52.8k
      !S.Context.hasSameNullabilityTypeQualifier(MethodImpl->getReturnType(),
2343
43.1k
                                                 MethodDecl->getReturnType(),
2344
43.1k
                                                 false)) {
2345
1
    auto nullabilityMethodImpl =
2346
1
      *MethodImpl->getReturnType()->getNullability(S.Context);
2347
1
    auto nullabilityMethodDecl =
2348
1
      *MethodDecl->getReturnType()->getNullability(S.Context);
2349
1
      S.Diag(MethodImpl->getLocation(),
2350
1
             diag::warn_conflicting_nullability_attr_overriding_ret_types)
2351
1
        << DiagNullabilityKind(
2352
1
             nullabilityMethodImpl,
2353
1
             ((MethodImpl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2354
1
              != 0))
2355
1
        << DiagNullabilityKind(
2356
1
             nullabilityMethodDecl,
2357
1
             ((MethodDecl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2358
1
                != 0));
2359
1
      S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
2360
1
  }
2361
2362
52.8k
  if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(),
2363
52.8k
                                       MethodDecl->getReturnType()))
2364
47.1k
    return true;
2365
5.72k
  if (!Warn)
2366
2
    return false;
2367
2368
5.72k
  unsigned DiagID =
2369
5.72k
    IsOverridingMode ? 
diag::warn_conflicting_overriding_ret_types5.52k
2370
5.72k
                     : 
diag::warn_conflicting_ret_types192
;
2371
2372
  // Mismatches between ObjC pointers go into a different warning
2373
  // category, and sometimes they're even completely explicitly allowed.
2374
5.72k
  if (const ObjCObjectPointerType *ImplPtrTy =
2375
5.72k
          MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) {
2376
5.51k
    if (const ObjCObjectPointerType *IfacePtrTy =
2377
5.51k
            MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) {
2378
      // Allow non-matching return types as long as they don't violate
2379
      // the principle of substitutability.  Specifically, we permit
2380
      // return types that are subclasses of the declared return type,
2381
      // or that are more-qualified versions of the declared type.
2382
5.46k
      if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
2383
5.17k
        return false;
2384
2385
293
      DiagID =
2386
293
        IsOverridingMode ? 
diag::warn_non_covariant_overriding_ret_types255
2387
293
                         : 
diag::warn_non_covariant_ret_types38
;
2388
293
    }
2389
5.51k
  }
2390
2391
551
  S.Diag(MethodImpl->getLocation(), DiagID)
2392
551
      << MethodImpl->getDeclName() << MethodDecl->getReturnType()
2393
551
      << MethodImpl->getReturnType()
2394
551
      << MethodImpl->getReturnTypeSourceRange();
2395
551
  S.Diag(MethodDecl->getLocation(), IsOverridingMode
2396
551
                                        ? 
diag::note_previous_declaration427
2397
551
                                        : 
diag::note_previous_definition124
)
2398
551
      << MethodDecl->getReturnTypeSourceRange();
2399
551
  return false;
2400
5.72k
}
2401
2402
static bool CheckMethodOverrideParam(Sema &S,
2403
                                     ObjCMethodDecl *MethodImpl,
2404
                                     ObjCMethodDecl *MethodDecl,
2405
                                     ParmVarDecl *ImplVar,
2406
                                     ParmVarDecl *IfaceVar,
2407
                                     bool IsProtocolMethodDecl,
2408
                                     bool IsOverridingMode,
2409
38.3k
                                     bool Warn) {
2410
38.3k
  if (IsProtocolMethodDecl &&
2411
38.3k
      objcModifiersConflict(ImplVar->getObjCDeclQualifier(),
2412
6.53k
                            IfaceVar->getObjCDeclQualifier())) {
2413
148
    if (Warn) {
2414
148
      if (IsOverridingMode)
2415
74
        S.Diag(ImplVar->getLocation(),
2416
74
               diag::warn_conflicting_overriding_param_modifiers)
2417
74
            << getTypeRange(ImplVar->getTypeSourceInfo())
2418
74
            << MethodImpl->getDeclName();
2419
74
      else S.Diag(ImplVar->getLocation(),
2420
74
             diag::warn_conflicting_param_modifiers)
2421
74
          << getTypeRange(ImplVar->getTypeSourceInfo())
2422
74
          << MethodImpl->getDeclName();
2423
148
      S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
2424
148
          << getTypeRange(IfaceVar->getTypeSourceInfo());
2425
148
    }
2426
0
    else
2427
0
      return false;
2428
148
  }
2429
2430
38.3k
  QualType ImplTy = ImplVar->getType();
2431
38.3k
  QualType IfaceTy = IfaceVar->getType();
2432
38.3k
  if (Warn && 
IsOverridingMode38.3k
&&
2433
38.3k
      
!isa<ObjCImplementationDecl>(MethodImpl->getDeclContext())35.2k
&&
2434
38.3k
      
!S.Context.hasSameNullabilityTypeQualifier(ImplTy, IfaceTy, true)32.2k
) {
2435
1
    S.Diag(ImplVar->getLocation(),
2436
1
           diag::warn_conflicting_nullability_attr_overriding_param_types)
2437
1
      << DiagNullabilityKind(
2438
1
           *ImplTy->getNullability(S.Context),
2439
1
           ((ImplVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2440
1
            != 0))
2441
1
      << DiagNullabilityKind(
2442
1
           *IfaceTy->getNullability(S.Context),
2443
1
           ((IfaceVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2444
1
            != 0));
2445
1
    S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration);
2446
1
  }
2447
38.3k
  if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
2448
37.1k
    return true;
2449
2450
1.22k
  if (!Warn)
2451
0
    return false;
2452
1.22k
  unsigned DiagID =
2453
1.22k
    IsOverridingMode ? 
diag::warn_conflicting_overriding_param_types1.18k
2454
1.22k
                     : 
diag::warn_conflicting_param_types35
;
2455
2456
  // Mismatches between ObjC pointers go into a different warning
2457
  // category, and sometimes they're even completely explicitly allowed..
2458
1.22k
  if (const ObjCObjectPointerType *ImplPtrTy =
2459
1.22k
        ImplTy->getAs<ObjCObjectPointerType>()) {
2460
1.19k
    if (const ObjCObjectPointerType *IfacePtrTy =
2461
1.19k
          IfaceTy->getAs<ObjCObjectPointerType>()) {
2462
      // Allow non-matching argument types as long as they don't
2463
      // violate the principle of substitutability.  Specifically, the
2464
      // implementation must accept any objects that the superclass
2465
      // accepts, however it may also accept others.
2466
1.17k
      if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
2467
57
        return false;
2468
2469
1.12k
      DiagID =
2470
1.12k
      IsOverridingMode ? 
diag::warn_non_contravariant_overriding_param_types1.10k
2471
1.12k
                       : 
diag::warn_non_contravariant_param_types16
;
2472
1.12k
    }
2473
1.19k
  }
2474
2475
1.16k
  S.Diag(ImplVar->getLocation(), DiagID)
2476
1.16k
    << getTypeRange(ImplVar->getTypeSourceInfo())
2477
1.16k
    << MethodImpl->getDeclName() << IfaceTy << ImplTy;
2478
1.16k
  S.Diag(IfaceVar->getLocation(),
2479
1.16k
         (IsOverridingMode ? 
diag::note_previous_declaration1.13k
2480
1.16k
                           : 
diag::note_previous_definition28
))
2481
1.16k
    << getTypeRange(IfaceVar->getTypeSourceInfo());
2482
1.16k
  return false;
2483
1.22k
}
2484
2485
/// In ARC, check whether the conventional meanings of the two methods
2486
/// match.  If they don't, it's a hard error.
2487
static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
2488
558
                                      ObjCMethodDecl *decl) {
2489
558
  ObjCMethodFamily implFamily = impl->getMethodFamily();
2490
558
  ObjCMethodFamily declFamily = decl->getMethodFamily();
2491
558
  if (implFamily == declFamily) 
return false528
;
2492
2493
  // Since conventions are sorted by selector, the only possibility is
2494
  // that the types differ enough to cause one selector or the other
2495
  // to fall out of the family.
2496
30
  assert(implFamily == OMF_None || declFamily == OMF_None);
2497
2498
  // No further diagnostics required on invalid declarations.
2499
30
  if (impl->isInvalidDecl() || 
decl->isInvalidDecl()24
)
return true9
;
2500
2501
21
  const ObjCMethodDecl *unmatched = impl;
2502
21
  ObjCMethodFamily family = declFamily;
2503
21
  unsigned errorID = diag::err_arc_lost_method_convention;
2504
21
  unsigned noteID = diag::note_arc_lost_method_convention;
2505
21
  if (declFamily == OMF_None) {
2506
9
    unmatched = decl;
2507
9
    family = implFamily;
2508
9
    errorID = diag::err_arc_gained_method_convention;
2509
9
    noteID = diag::note_arc_gained_method_convention;
2510
9
  }
2511
2512
  // Indexes into a %select clause in the diagnostic.
2513
21
  enum FamilySelector {
2514
21
    F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
2515
21
  };
2516
21
  FamilySelector familySelector = FamilySelector();
2517
2518
21
  switch (family) {
2519
0
  case OMF_None: llvm_unreachable("logic error, no method convention");
2520
0
  case OMF_retain:
2521
0
  case OMF_release:
2522
0
  case OMF_autorelease:
2523
0
  case OMF_dealloc:
2524
0
  case OMF_finalize:
2525
0
  case OMF_retainCount:
2526
0
  case OMF_self:
2527
0
  case OMF_initialize:
2528
0
  case OMF_performSelector:
2529
    // Mismatches for these methods don't change ownership
2530
    // conventions, so we don't care.
2531
0
    return false;
2532
2533
21
  case OMF_init: familySelector = F_init; break;
2534
0
  case OMF_alloc: familySelector = F_alloc; break;
2535
0
  case OMF_copy: familySelector = F_copy; break;
2536
0
  case OMF_mutableCopy: familySelector = F_mutableCopy; break;
2537
0
  case OMF_new: familySelector = F_new; break;
2538
21
  }
2539
2540
21
  enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
2541
21
  ReasonSelector reasonSelector;
2542
2543
  // The only reason these methods don't fall within their families is
2544
  // due to unusual result types.
2545
21
  if (unmatched->getReturnType()->isObjCObjectPointerType()) {
2546
0
    reasonSelector = R_UnrelatedReturn;
2547
21
  } else {
2548
21
    reasonSelector = R_NonObjectReturn;
2549
21
  }
2550
2551
21
  S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector);
2552
21
  S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector);
2553
2554
21
  return true;
2555
21
}
2556
2557
void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
2558
                                       ObjCMethodDecl *MethodDecl,
2559
4.98k
                                       bool IsProtocolMethodDecl) {
2560
4.98k
  if (getLangOpts().ObjCAutoRefCount &&
2561
4.98k
      
checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl)558
)
2562
30
    return;
2563
2564
4.95k
  CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
2565
4.95k
                            IsProtocolMethodDecl, false,
2566
4.95k
                            true);
2567
2568
4.95k
  for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
2569
4.95k
       IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2570
4.95k
       EF = MethodDecl->param_end();
2571
8.12k
       IM != EM && 
IF != EF3.17k
;
++IM, ++IF3.17k
) {
2572
3.17k
    CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
2573
3.17k
                             IsProtocolMethodDecl, false, true);
2574
3.17k
  }
2575
2576
4.95k
  if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
2577
2
    Diag(ImpMethodDecl->getLocation(),
2578
2
         diag::warn_conflicting_variadic);
2579
2
    Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
2580
2
  }
2581
4.95k
}
2582
2583
void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
2584
                                       ObjCMethodDecl *Overridden,
2585
47.8k
                                       bool IsProtocolMethodDecl) {
2586
2587
47.8k
  CheckMethodOverrideReturn(*this, Method, Overridden,
2588
47.8k
                            IsProtocolMethodDecl, true,
2589
47.8k
                            true);
2590
2591
47.8k
  for (ObjCMethodDecl::param_iterator IM = Method->param_begin(),
2592
47.8k
       IF = Overridden->param_begin(), EM = Method->param_end(),
2593
47.8k
       EF = Overridden->param_end();
2594
83.0k
       IM != EM && 
IF != EF35.2k
;
++IM, ++IF35.2k
) {
2595
35.2k
    CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF,
2596
35.2k
                             IsProtocolMethodDecl, true, true);
2597
35.2k
  }
2598
2599
47.8k
  if (Method->isVariadic() != Overridden->isVariadic()) {
2600
3
    Diag(Method->getLocation(),
2601
3
         diag::warn_conflicting_overriding_variadic);
2602
3
    Diag(Overridden->getLocation(), diag::note_previous_declaration);
2603
3
  }
2604
47.8k
}
2605
2606
/// WarnExactTypedMethods - This routine issues a warning if method
2607
/// implementation declaration matches exactly that of its declaration.
2608
void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
2609
                                 ObjCMethodDecl *MethodDecl,
2610
24
                                 bool IsProtocolMethodDecl) {
2611
  // don't issue warning when protocol method is optional because primary
2612
  // class is not required to implement it and it is safe for protocol
2613
  // to implement it.
2614
24
  if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional)
2615
1
    return;
2616
  // don't issue warning when primary class's method is
2617
  // depecated/unavailable.
2618
23
  if (MethodDecl->hasAttr<UnavailableAttr>() ||
2619
23
      MethodDecl->hasAttr<DeprecatedAttr>())
2620
0
    return;
2621
2622
23
  bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
2623
23
                                      IsProtocolMethodDecl, false, false);
2624
23
  if (match)
2625
21
    for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
2626
21
         IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2627
21
         EF = MethodDecl->param_end();
2628
24
         IM != EM && 
IF != EF3
;
++IM, ++IF3
) {
2629
3
      match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl,
2630
3
                                       *IM, *IF,
2631
3
                                       IsProtocolMethodDecl, false, false);
2632
3
      if (!match)
2633
0
        break;
2634
3
    }
2635
23
  if (match)
2636
21
    match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
2637
23
  if (match)
2638
21
    match = !(MethodDecl->isClassMethod() &&
2639
21
              
MethodDecl->getSelector() == GetNullarySelector("load", Context)0
);
2640
2641
23
  if (match) {
2642
21
    Diag(ImpMethodDecl->getLocation(),
2643
21
         diag::warn_category_method_impl_match);
2644
21
    Diag(MethodDecl->getLocation(), diag::note_method_declared_at)
2645
21
      << MethodDecl->getDeclName();
2646
21
  }
2647
23
}
2648
2649
/// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
2650
/// improve the efficiency of selector lookups and type checking by associating
2651
/// with each protocol / interface / category the flattened instance tables. If
2652
/// we used an immutable set to keep the table then it wouldn't add significant
2653
/// memory cost and it would be handy for lookups.
2654
2655
typedef llvm::DenseSet<IdentifierInfo*> ProtocolNameSet;
2656
typedef std::unique_ptr<ProtocolNameSet> LazyProtocolNameSet;
2657
2658
static void findProtocolsWithExplicitImpls(const ObjCProtocolDecl *PDecl,
2659
9
                                           ProtocolNameSet &PNS) {
2660
9
  if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>())
2661
7
    PNS.insert(PDecl->getIdentifier());
2662
9
  for (const auto *PI : PDecl->protocols())
2663
1
    findProtocolsWithExplicitImpls(PI, PNS);
2664
9
}
2665
2666
/// Recursively populates a set with all conformed protocols in a class
2667
/// hierarchy that have the 'objc_protocol_requires_explicit_implementation'
2668
/// attribute.
2669
static void findProtocolsWithExplicitImpls(const ObjCInterfaceDecl *Super,
2670
22
                                           ProtocolNameSet &PNS) {
2671
22
  if (!Super)
2672
12
    return;
2673
2674
10
  for (const auto *I : Super->all_referenced_protocols())
2675
8
    findProtocolsWithExplicitImpls(I, PNS);
2676
2677
10
  findProtocolsWithExplicitImpls(Super->getSuperClass(), PNS);
2678
10
}
2679
2680
/// CheckProtocolMethodDefs - This routine checks unimplemented methods
2681
/// Declared in protocol, and those referenced by it.
2682
static void CheckProtocolMethodDefs(Sema &S,
2683
                                    SourceLocation ImpLoc,
2684
                                    ObjCProtocolDecl *PDecl,
2685
                                    bool& IncompleteImpl,
2686
                                    const Sema::SelectorSet &InsMap,
2687
                                    const Sema::SelectorSet &ClsMap,
2688
                                    ObjCContainerDecl *CDecl,
2689
756
                                    LazyProtocolNameSet &ProtocolsExplictImpl) {
2690
756
  ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
2691
756
  ObjCInterfaceDecl *IDecl = C ? 
C->getClassInterface()25
2692
756
                               : 
dyn_cast<ObjCInterfaceDecl>(CDecl)731
;
2693
756
  assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
2694
2695
0
  ObjCInterfaceDecl *Super = IDecl->getSuperClass();
2696
756
  ObjCInterfaceDecl *NSIDecl = nullptr;
2697
2698
  // If this protocol is marked 'objc_protocol_requires_explicit_implementation'
2699
  // then we should check if any class in the super class hierarchy also
2700
  // conforms to this protocol, either directly or via protocol inheritance.
2701
  // If so, we can skip checking this protocol completely because we
2702
  // know that a parent class already satisfies this protocol.
2703
  //
2704
  // Note: we could generalize this logic for all protocols, and merely
2705
  // add the limit on looking at the super class chain for just
2706
  // specially marked protocols.  This may be a good optimization.  This
2707
  // change is restricted to 'objc_protocol_requires_explicit_implementation'
2708
  // protocols for now for controlled evaluation.
2709
756
  if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) {
2710
16
    if (!ProtocolsExplictImpl) {
2711
12
      ProtocolsExplictImpl.reset(new ProtocolNameSet);
2712
12
      findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl);
2713
12
    }
2714
16
    if (ProtocolsExplictImpl->find(PDecl->getIdentifier()) !=
2715
16
        ProtocolsExplictImpl->end())
2716
6
      return;
2717
2718
    // If no super class conforms to the protocol, we should not search
2719
    // for methods in the super class to implicitly satisfy the protocol.
2720
10
    Super = nullptr;
2721
10
  }
2722
2723
750
  if (S.getLangOpts().ObjCRuntime.isNeXTFamily()) {
2724
    // check to see if class implements forwardInvocation method and objects
2725
    // of this class are derived from 'NSProxy' so that to forward requests
2726
    // from one object to another.
2727
    // Under such conditions, which means that every method possible is
2728
    // implemented in the class, we should not issue "Method definition not
2729
    // found" warnings.
2730
    // FIXME: Use a general GetUnarySelector method for this.
2731
727
    IdentifierInfo* II = &S.Context.Idents.get("forwardInvocation");
2732
727
    Selector fISelector = S.Context.Selectors.getSelector(1, &II);
2733
727
    if (InsMap.count(fISelector))
2734
      // Is IDecl derived from 'NSProxy'? If so, no instance methods
2735
      // need be implemented in the implementation.
2736
1
      NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy"));
2737
727
  }
2738
2739
  // If this is a forward protocol declaration, get its definition.
2740
750
  if (!PDecl->isThisDeclarationADefinition() &&
2741
750
      
PDecl->getDefinition()6
)
2742
1
    PDecl = PDecl->getDefinition();
2743
2744
  // If a method lookup fails locally we still need to look and see if
2745
  // the method was implemented by a base class or an inherited
2746
  // protocol. This lookup is slow, but occurs rarely in correct code
2747
  // and otherwise would terminate in a warning.
2748
2749
  // check unimplemented instance methods.
2750
750
  if (!NSIDecl)
2751
1.04k
    
for (auto *method : PDecl->instance_methods())749
{
2752
1.04k
      if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
2753
1.04k
          
!method->isPropertyAccessor()997
&&
2754
1.04k
          
!InsMap.count(method->getSelector())677
&&
2755
1.04k
          
(389
!Super389
|| !Super->lookupMethod(method->getSelector(),
2756
284
                                          true /* instance */,
2757
284
                                          false /* shallowCategory */,
2758
284
                                          true /* followsSuper */,
2759
284
                                          nullptr /* category */))) {
2760
            // If a method is not implemented in the category implementation but
2761
            // has been declared in its primary class, superclass,
2762
            // or in one of their protocols, no need to issue the warning.
2763
            // This is because method will be implemented in the primary class
2764
            // or one of its super class implementation.
2765
2766
            // Ugly, but necessary. Method declared in protocol might have
2767
            // have been synthesized due to a property declared in the class which
2768
            // uses the protocol.
2769
119
            if (ObjCMethodDecl *MethodInClass =
2770
119
                  IDecl->lookupMethod(method->getSelector(),
2771
119
                                      true /* instance */,
2772
119
                                      true /* shallowCategoryLookup */,
2773
119
                                      false /* followSuper */))
2774
34
              if (C || 
MethodInClass->isPropertyAccessor()31
)
2775
5
                continue;
2776
114
            unsigned DIAG = diag::warn_unimplemented_protocol_method;
2777
114
            if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
2778
105
              WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG,
2779
105
                                  PDecl);
2780
105
            }
2781
114
          }
2782
1.04k
    }
2783
  // check unimplemented class methods
2784
750
  for (auto *method : PDecl->class_methods()) {
2785
139
    if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
2786
139
        
!ClsMap.count(method->getSelector())136
&&
2787
139
        
(34
!Super34
|| !Super->lookupMethod(method->getSelector(),
2788
28
                                        false /* class method */,
2789
28
                                        false /* shallowCategoryLookup */,
2790
28
                                        true  /* followSuper */,
2791
34
                                        nullptr /* category */))) {
2792
      // See above comment for instance method lookups.
2793
34
      if (C && IDecl->lookupMethod(method->getSelector(),
2794
1
                                   false /* class */,
2795
1
                                   true /* shallowCategoryLookup */,
2796
1
                                   false /* followSuper */))
2797
1
        continue;
2798
2799
33
      unsigned DIAG = diag::warn_unimplemented_protocol_method;
2800
33
      if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
2801
27
        WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, PDecl);
2802
27
      }
2803
33
    }
2804
139
  }
2805
  // Check on this protocols's referenced protocols, recursively.
2806
750
  for (auto *PI : PDecl->protocols())
2807
186
    CheckProtocolMethodDefs(S, ImpLoc, PI, IncompleteImpl, InsMap, ClsMap,
2808
186
                            CDecl, ProtocolsExplictImpl);
2809
750
}
2810
2811
/// MatchAllMethodDeclarations - Check methods declared in interface
2812
/// or protocol against those declared in their implementations.
2813
///
2814
void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap,
2815
                                      const SelectorSet &ClsMap,
2816
                                      SelectorSet &InsMapSeen,
2817
                                      SelectorSet &ClsMapSeen,
2818
                                      ObjCImplDecl* IMPDecl,
2819
                                      ObjCContainerDecl* CDecl,
2820
                                      bool &IncompleteImpl,
2821
                                      bool ImmediateClass,
2822
20.4k
                                      bool WarnCategoryMethodImpl) {
2823
  // Check and see if instance methods in class interface have been
2824
  // implemented in the implementation class. If so, their types match.
2825
68.8k
  for (auto *I : CDecl->instance_methods()) {
2826
68.8k
    if (!InsMapSeen.insert(I->getSelector()).second)
2827
1.56k
      continue;
2828
67.3k
    if (!I->isPropertyAccessor() &&
2829
67.3k
        
!InsMap.count(I->getSelector())52.7k
) {
2830
48.8k
      if (ImmediateClass)
2831
1.03k
        WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
2832
1.03k
                            diag::warn_undef_method_impl);
2833
48.8k
      continue;
2834
48.8k
    } else {
2835
18.4k
      ObjCMethodDecl *ImpMethodDecl =
2836
18.4k
        IMPDecl->getInstanceMethod(I->getSelector());
2837
18.4k
      assert(CDecl->getInstanceMethod(I->getSelector(), true/*AllowHidden*/) &&
2838
18.4k
             "Expected to find the method through lookup as well");
2839
      // ImpMethodDecl may be null as in a @dynamic property.
2840
18.4k
      if (ImpMethodDecl) {
2841
        // Skip property accessor function stubs.
2842
9.25k
        if (ImpMethodDecl->isSynthesizedAccessorStub())
2843
5.00k
          continue;
2844
4.25k
        if (!WarnCategoryMethodImpl)
2845
4.21k
          WarnConflictingTypedMethods(ImpMethodDecl, I,
2846
4.21k
                                      isa<ObjCProtocolDecl>(CDecl));
2847
33
        else if (!I->isPropertyAccessor())
2848
24
          WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
2849
4.25k
      }
2850
18.4k
    }
2851
67.3k
  }
2852
2853
  // Check and see if class methods in class interface have been
2854
  // implemented in the implementation class. If so, their types match.
2855
20.4k
  for (auto *I : CDecl->class_methods()) {
2856
15.7k
    if (!ClsMapSeen.insert(I->getSelector()).second)
2857
92
      continue;
2858
15.6k
    if (!I->isPropertyAccessor() &&
2859
15.6k
        
!ClsMap.count(I->getSelector())15.0k
) {
2860
14.3k
      if (ImmediateClass)
2861
175
        WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
2862
175
                            diag::warn_undef_method_impl);
2863
14.3k
    } else {
2864
1.31k
      ObjCMethodDecl *ImpMethodDecl =
2865
1.31k
        IMPDecl->getClassMethod(I->getSelector());
2866
1.31k
      assert(CDecl->getClassMethod(I->getSelector(), true/*AllowHidden*/) &&
2867
1.31k
             "Expected to find the method through lookup as well");
2868
      // ImpMethodDecl may be null as in a @dynamic property.
2869
1.31k
      if (ImpMethodDecl) {
2870
        // Skip property accessor function stubs.
2871
771
        if (ImpMethodDecl->isSynthesizedAccessorStub())
2872
0
          continue;
2873
771
        if (!WarnCategoryMethodImpl)
2874
771
          WarnConflictingTypedMethods(ImpMethodDecl, I,
2875
771
                                      isa<ObjCProtocolDecl>(CDecl));
2876
0
        else if (!I->isPropertyAccessor())
2877
0
          WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
2878
771
      }
2879
1.31k
    }
2880
15.6k
  }
2881
2882
20.4k
  if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) {
2883
    // Also, check for methods declared in protocols inherited by
2884
    // this protocol.
2885
2.15k
    for (auto *PI : PD->protocols())
2886
306
      MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2887
306
                                 IMPDecl, PI, IncompleteImpl, false,
2888
306
                                 WarnCategoryMethodImpl);
2889
2.15k
  }
2890
2891
20.4k
  if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
2892
    // when checking that methods in implementation match their declaration,
2893
    // i.e. when WarnCategoryMethodImpl is false, check declarations in class
2894
    // extension; as well as those in categories.
2895
7.73k
    if (!WarnCategoryMethodImpl) {
2896
7.37k
      for (auto *Cat : I->visible_categories())
2897
10.0k
        MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2898
10.0k
                                   IMPDecl, Cat, IncompleteImpl,
2899
10.0k
                                   ImmediateClass && 
Cat->IsClassExtension()699
,
2900
10.0k
                                   WarnCategoryMethodImpl);
2901
7.37k
    } else {
2902
      // Also methods in class extensions need be looked at next.
2903
355
      for (auto *Ext : I->visible_extensions())
2904
18
        MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2905
18
                                   IMPDecl, Ext, IncompleteImpl, false,
2906
18
                                   WarnCategoryMethodImpl);
2907
355
    }
2908
2909
    // Check for any implementation of a methods declared in protocol.
2910
7.73k
    for (auto *PI : I->all_referenced_protocols())
2911
1.84k
      MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2912
1.84k
                                 IMPDecl, PI, IncompleteImpl, false,
2913
1.84k
                                 WarnCategoryMethodImpl);
2914
2915
    // FIXME. For now, we are not checking for exact match of methods
2916
    // in category implementation and its primary class's super class.
2917
7.73k
    if (!WarnCategoryMethodImpl && 
I->getSuperClass()7.37k
)
2918
2.56k
      MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2919
2.56k
                                 IMPDecl,
2920
2.56k
                                 I->getSuperClass(), IncompleteImpl, false);
2921
7.73k
  }
2922
20.4k
}
2923
2924
/// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
2925
/// category matches with those implemented in its primary class and
2926
/// warns each time an exact match is found.
2927
void Sema::CheckCategoryVsClassMethodMatches(
2928
503
                                  ObjCCategoryImplDecl *CatIMPDecl) {
2929
  // Get category's primary class.
2930
503
  ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
2931
503
  if (!CatDecl)
2932
0
    return;
2933
503
  ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
2934
503
  if (!IDecl)
2935
0
    return;
2936
503
  ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass();
2937
503
  SelectorSet InsMap, ClsMap;
2938
2939
503
  for (const auto *I : CatIMPDecl->instance_methods()) {
2940
438
    Selector Sel = I->getSelector();
2941
    // When checking for methods implemented in the category, skip over
2942
    // those declared in category class's super class. This is because
2943
    // the super class must implement the method.
2944
438
    if (SuperIDecl && 
SuperIDecl->lookupMethod(Sel, true)307
)
2945
25
      continue;
2946
413
    InsMap.insert(Sel);
2947
413
  }
2948
2949
503
  for (const auto *I : CatIMPDecl->class_methods()) {
2950
64
    Selector Sel = I->getSelector();
2951
64
    if (SuperIDecl && 
SuperIDecl->lookupMethod(Sel, false)47
)
2952
5
      continue;
2953
59
    ClsMap.insert(Sel);
2954
59
  }
2955
503
  if (InsMap.empty() && 
ClsMap.empty()180
)
2956
148
    return;
2957
2958
355
  SelectorSet InsMapSeen, ClsMapSeen;
2959
355
  bool IncompleteImpl = false;
2960
355
  MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2961
355
                             CatIMPDecl, IDecl,
2962
355
                             IncompleteImpl, false,
2963
355
                             true /*WarnCategoryMethodImpl*/);
2964
355
}
2965
2966
void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
2967
                                     ObjCContainerDecl* CDecl,
2968
5.31k
                                     bool IncompleteImpl) {
2969
5.31k
  SelectorSet InsMap;
2970
  // Check and see if instance methods in class interface have been
2971
  // implemented in the implementation class.
2972
5.31k
  for (const auto *I : IMPDecl->instance_methods())
2973
11.5k
    InsMap.insert(I->getSelector());
2974
2975
  // Add the selectors for getters/setters of @dynamic properties.
2976
5.31k
  for (const auto *PImpl : IMPDecl->property_impls()) {
2977
    // We only care about @dynamic implementations.
2978
2.99k
    if (PImpl->getPropertyImplementation() != ObjCPropertyImplDecl::Dynamic)
2979
2.77k
      continue;
2980
2981
219
    const auto *P = PImpl->getPropertyDecl();
2982
219
    if (!P) 
continue0
;
2983
2984
219
    InsMap.insert(P->getGetterName());
2985
219
    if (!P->getSetterName().isNull())
2986
219
      InsMap.insert(P->getSetterName());
2987
219
  }
2988
2989
  // Check and see if properties declared in the interface have either 1)
2990
  // an implementation or 2) there is a @synthesize/@dynamic implementation
2991
  // of the property in the @implementation.
2992
5.31k
  if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2993
4.81k
    bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties &&
2994
4.81k
                                
LangOpts.ObjCRuntime.isNonFragile()4.79k
&&
2995
4.81k
                                
!IDecl->isObjCRequiresPropertyDefs()4.57k
;
2996
4.81k
    DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties);
2997
4.81k
  }
2998
2999
  // Diagnose null-resettable synthesized setters.
3000
5.31k
  diagnoseNullResettableSynthesizedSetters(IMPDecl);
3001
3002
5.31k
  SelectorSet ClsMap;
3003
5.31k
  for (const auto *I : IMPDecl->class_methods())
3004
1.21k
    ClsMap.insert(I->getSelector());
3005
3006
  // Check for type conflict of methods declared in a class/protocol and
3007
  // its implementation; if any.
3008
5.31k
  SelectorSet InsMapSeen, ClsMapSeen;
3009
5.31k
  MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
3010
5.31k
                             IMPDecl, CDecl,
3011
5.31k
                             IncompleteImpl, true);
3012
3013
  // check all methods implemented in category against those declared
3014
  // in its primary class.
3015
5.31k
  if (ObjCCategoryImplDecl *CatDecl =
3016
5.31k
        dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
3017
503
    CheckCategoryVsClassMethodMatches(CatDecl);
3018
3019
  // Check the protocol list for unimplemented methods in the @implementation
3020
  // class.
3021
  // Check and see if class methods in class interface have been
3022
  // implemented in the implementation class.
3023
3024
5.31k
  LazyProtocolNameSet ExplicitImplProtocols;
3025
3026
5.31k
  if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
3027
4.81k
    for (auto *PI : I->all_referenced_protocols())
3028
545
      CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), PI, IncompleteImpl,
3029
545
                              InsMap, ClsMap, I, ExplicitImplProtocols);
3030
4.81k
  } else 
if (ObjCCategoryDecl *503
C503
= dyn_cast<ObjCCategoryDecl>(CDecl)) {
3031
    // For extended class, unimplemented methods in its protocols will
3032
    // be reported in the primary class.
3033
503
    if (!C->IsClassExtension()) {
3034
503
      for (auto *P : C->protocols())
3035
25
        CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), P,
3036
25
                                IncompleteImpl, InsMap, ClsMap, CDecl,
3037
25
                                ExplicitImplProtocols);
3038
503
      DiagnoseUnimplementedProperties(S, IMPDecl, CDecl,
3039
503
                                      /*SynthesizeProperties=*/false);
3040
503
    }
3041
503
  } else
3042
0
    llvm_unreachable("invalid ObjCContainerDecl type.");
3043
5.31k
}
3044
3045
Sema::DeclGroupPtrTy
3046
Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
3047
                                   IdentifierInfo **IdentList,
3048
                                   SourceLocation *IdentLocs,
3049
                                   ArrayRef<ObjCTypeParamList *> TypeParamLists,
3050
63.4k
                                   unsigned NumElts) {
3051
63.4k
  SmallVector<Decl *, 8> DeclsInGroup;
3052
194k
  for (unsigned i = 0; i != NumElts; 
++i131k
) {
3053
    // Check for another declaration kind with the same name.
3054
131k
    NamedDecl *PrevDecl
3055
131k
      = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
3056
131k
                         LookupOrdinaryName, forRedeclarationInCurContext());
3057
131k
    if (PrevDecl && 
!isa<ObjCInterfaceDecl>(PrevDecl)105k
) {
3058
      // GCC apparently allows the following idiom:
3059
      //
3060
      // typedef NSObject < XCElementTogglerP > XCElementToggler;
3061
      // @class XCElementToggler;
3062
      //
3063
      // Here we have chosen to ignore the forward class declaration
3064
      // with a warning. Since this is the implied behavior.
3065
4
      TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
3066
4
      if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
3067
1
        Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
3068
1
        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3069
3
      } else {
3070
        // a forward class declaration matching a typedef name of a class refers
3071
        // to the underlying class. Just ignore the forward class with a warning
3072
        // as this will force the intended behavior which is to lookup the
3073
        // typedef name.
3074
3
        if (isa<ObjCObjectType>(TDD->getUnderlyingType())) {
3075
3
          Diag(AtClassLoc, diag::warn_forward_class_redefinition)
3076
3
              << IdentList[i];
3077
3
          Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3078
3
          continue;
3079
3
        }
3080
3
      }
3081
4
    }
3082
3083
    // Create a declaration to describe this forward declaration.
3084
131k
    ObjCInterfaceDecl *PrevIDecl
3085
131k
      = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
3086
3087
131k
    IdentifierInfo *ClassName = IdentList[i];
3088
131k
    if (PrevIDecl && 
PrevIDecl->getIdentifier() != ClassName105k
) {
3089
      // A previous decl with a different name is because of
3090
      // @compatibility_alias, for example:
3091
      // \code
3092
      //   @class NewImage;
3093
      //   @compatibility_alias OldImage NewImage;
3094
      // \endcode
3095
      // A lookup for 'OldImage' will return the 'NewImage' decl.
3096
      //
3097
      // In such a case use the real declaration name, instead of the alias one,
3098
      // otherwise we will break IdentifierResolver and redecls-chain invariants.
3099
      // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
3100
      // has been aliased.
3101
6
      ClassName = PrevIDecl->getIdentifier();
3102
6
    }
3103
3104
    // If this forward declaration has type parameters, compare them with the
3105
    // type parameters of the previous declaration.
3106
131k
    ObjCTypeParamList *TypeParams = TypeParamLists[i];
3107
131k
    if (PrevIDecl && 
TypeParams105k
) {
3108
20.9k
      if (ObjCTypeParamList *PrevTypeParams = PrevIDecl->getTypeParamList()) {
3109
        // Check for consistency with the previous declaration.
3110
20.3k
        if (checkTypeParamListConsistency(
3111
20.3k
              *this, PrevTypeParams, TypeParams,
3112
20.3k
              TypeParamListContext::ForwardDeclaration)) {
3113
0
          TypeParams = nullptr;
3114
0
        }
3115
20.3k
      } else 
if (ObjCInterfaceDecl *650
Def650
= PrevIDecl->getDefinition()) {
3116
        // The @interface does not have type parameters. Complain.
3117
1
        Diag(IdentLocs[i], diag::err_objc_parameterized_forward_class)
3118
1
          << ClassName
3119
1
          << TypeParams->getSourceRange();
3120
1
        Diag(Def->getLocation(), diag::note_defined_here)
3121
1
          << ClassName;
3122
3123
1
        TypeParams = nullptr;
3124
1
      }
3125
20.9k
    }
3126
3127
131k
    ObjCInterfaceDecl *IDecl
3128
131k
      = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
3129
131k
                                  ClassName, TypeParams, PrevIDecl,
3130
131k
                                  IdentLocs[i]);
3131
131k
    IDecl->setAtEndRange(IdentLocs[i]);
3132
3133
131k
    if (PrevIDecl)
3134
105k
      mergeDeclAttributes(IDecl, PrevIDecl);
3135
3136
131k
    PushOnScopeChains(IDecl, TUScope);
3137
131k
    CheckObjCDeclScope(IDecl);
3138
131k
    DeclsInGroup.push_back(IDecl);
3139
131k
  }
3140
3141
63.4k
  return BuildDeclaratorGroup(DeclsInGroup);
3142
63.4k
}
3143
3144
static bool tryMatchRecordTypes(ASTContext &Context,
3145
                                Sema::MethodMatchStrategy strategy,
3146
                                const Type *left, const Type *right);
3147
3148
static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
3149
1.32M
                       QualType leftQT, QualType rightQT) {
3150
1.32M
  const Type *left =
3151
1.32M
    Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
3152
1.32M
  const Type *right =
3153
1.32M
    Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
3154
3155
1.32M
  if (left == right) 
return true1.20M
;
3156
3157
  // If we're doing a strict match, the types have to match exactly.
3158
126k
  if (strategy == Sema::MMS_strict) 
return false123k
;
3159
3160
2.57k
  if (left->isIncompleteType() || right->isIncompleteType()) 
return false6
;
3161
3162
  // Otherwise, use this absurdly complicated algorithm to try to
3163
  // validate the basic, low-level compatibility of the two types.
3164
3165
  // As a minimum, require the sizes and alignments to match.
3166
2.57k
  TypeInfo LeftTI = Context.getTypeInfo(left);
3167
2.57k
  TypeInfo RightTI = Context.getTypeInfo(right);
3168
2.57k
  if (LeftTI.Width != RightTI.Width)
3169
20
    return false;
3170
3171
2.55k
  if (LeftTI.Align != RightTI.Align)
3172
0
    return false;
3173
3174
  // Consider all the kinds of non-dependent canonical types:
3175
  // - functions and arrays aren't possible as return and parameter types
3176
3177
  // - vector types of equal size can be arbitrarily mixed
3178
2.55k
  if (isa<VectorType>(left)) 
return isa<VectorType>(right)0
;
3179
2.55k
  if (isa<VectorType>(right)) 
return false0
;
3180
3181
  // - references should only match references of identical type
3182
  // - structs, unions, and Objective-C objects must match more-or-less
3183
  //   exactly
3184
  // - everything else should be a scalar
3185
2.55k
  if (!left->isScalarType() || 
!right->isScalarType()2.55k
)
3186
2
    return tryMatchRecordTypes(Context, strategy, left, right);
3187
3188
  // Make scalars agree in kind, except count bools as chars, and group
3189
  // all non-member pointers together.
3190
2.55k
  Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
3191
2.55k
  Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
3192
2.55k
  if (leftSK == Type::STK_Bool) 
leftSK = Type::STK_Integral0
;
3193
2.55k
  if (rightSK == Type::STK_Bool) 
rightSK = Type::STK_Integral0
;
3194
2.55k
  if (leftSK == Type::STK_CPointer || 
leftSK == Type::STK_BlockPointer2.54k
)
3195
10
    leftSK = Type::STK_ObjCObjectPointer;
3196
2.55k
  if (rightSK == Type::STK_CPointer || 
rightSK == Type::STK_BlockPointer2.53k
)
3197
15
    rightSK = Type::STK_ObjCObjectPointer;
3198
3199
  // Note that data member pointers and function member pointers don't
3200
  // intermix because of the size differences.
3201
3202
2.55k
  return (leftSK == rightSK);
3203
2.55k
}
3204
3205
static bool tryMatchRecordTypes(ASTContext &Context,
3206
                                Sema::MethodMatchStrategy strategy,
3207
2
                                const Type *lt, const Type *rt) {
3208
2
  assert(lt && rt && lt != rt);
3209
3210
2
  if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) 
return false0
;
3211
2
  RecordDecl *left = cast<RecordType>(lt)->getDecl();
3212
2
  RecordDecl *right = cast<RecordType>(rt)->getDecl();
3213
3214
  // Require union-hood to match.
3215
2
  if (left->isUnion() != right->isUnion()) 
return false0
;
3216
3217
  // Require an exact match if either is non-POD.
3218
2
  if ((isa<CXXRecordDecl>(left) && 
!cast<CXXRecordDecl>(left)->isPOD()0
) ||
3219
2
      (isa<CXXRecordDecl>(right) && 
!cast<CXXRecordDecl>(right)->isPOD()0
))
3220
0
    return false;
3221
3222
  // Require size and alignment to match.
3223
2
  TypeInfo LeftTI = Context.getTypeInfo(lt);
3224
2
  TypeInfo RightTI = Context.getTypeInfo(rt);
3225
2
  if (LeftTI.Width != RightTI.Width)
3226
0
    return false;
3227
3228
2
  if (LeftTI.Align != RightTI.Align)
3229
0
    return false;
3230
3231
  // Require fields to match.
3232
2
  RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
3233
2
  RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
3234
4
  for (; li != le && 
ri != re3
;
++li, ++ri2
) {
3235
3
    if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
3236
1
      return false;
3237
3
  }
3238
1
  return (li == le && ri == re);
3239
2
}
3240
3241
/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
3242
/// returns true, or false, accordingly.
3243
/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
3244
bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
3245
                                      const ObjCMethodDecl *right,
3246
940k
                                      MethodMatchStrategy strategy) {
3247
940k
  if (!matchTypes(Context, strategy, left->getReturnType(),
3248
940k
                  right->getReturnType()))
3249
74.8k
    return false;
3250
3251
  // If either is hidden, it is not considered to match.
3252
866k
  if (!left->isUnconditionallyVisible() || 
!right->isUnconditionallyVisible()866k
)
3253
7
    return false;
3254
3255
866k
  if (left->isDirectMethod() != right->isDirectMethod())
3256
266
    return false;
3257
3258
865k
  if (getLangOpts().ObjCAutoRefCount &&
3259
865k
      
(6.45k
left->hasAttr<NSReturnsRetainedAttr>()
3260
6.45k
         != right->hasAttr<NSReturnsRetainedAttr>() ||
3261
6.45k
       left->hasAttr<NSConsumesSelfAttr>()
3262
6.44k
         != right->hasAttr<NSConsumesSelfAttr>()))
3263
11
    return false;
3264
3265
865k
  ObjCMethodDecl::param_const_iterator
3266
865k
    li = left->param_begin(), le = left->param_end(), ri = right->param_begin(),
3267
865k
    re = right->param_end();
3268
3269
1.20M
  for (; li != le && 
ri != re387k
;
++li, ++ri339k
) {
3270
387k
    assert(ri != right->param_end() && "Param mismatch");
3271
0
    const ParmVarDecl *lparm = *li, *rparm = *ri;
3272
3273
387k
    if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
3274
48.6k
      return false;
3275
3276
339k
    if (getLangOpts().ObjCAutoRefCount &&
3277
339k
        
lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>()2.15k
)
3278
6
      return false;
3279
339k
  }
3280
817k
  return true;
3281
865k
}
3282
3283
static bool isMethodContextSameForKindofLookup(ObjCMethodDecl *Method,
3284
806k
                                               ObjCMethodDecl *MethodInList) {
3285
806k
  auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
3286
806k
  auto *MethodInListProtocol =
3287
806k
      dyn_cast<ObjCProtocolDecl>(MethodInList->getDeclContext());
3288
  // If this method belongs to a protocol but the method in list does not, or
3289
  // vice versa, we say the context is not the same.
3290
806k
  if ((MethodProtocol && 
!MethodInListProtocol771
) ||
3291
806k
      
(806k
!MethodProtocol806k
&&
MethodInListProtocol806k
))
3292
14.6k
    return false;
3293
3294
792k
  if (MethodProtocol && 
MethodInListProtocol286
)
3295
286
    return true;
3296
3297
791k
  ObjCInterfaceDecl *MethodInterface = Method->getClassInterface();
3298
791k
  ObjCInterfaceDecl *MethodInListInterface =
3299
791k
      MethodInList->getClassInterface();
3300
791k
  return MethodInterface == MethodInListInterface;
3301
792k
}
3302
3303
void Sema::addMethodToGlobalList(ObjCMethodList *List,
3304
1.12M
                                 ObjCMethodDecl *Method) {
3305
  // Record at the head of the list whether there were 0, 1, or >= 2 methods
3306
  // inside categories.
3307
1.12M
  if (ObjCCategoryDecl *CD =
3308
1.12M
          dyn_cast<ObjCCategoryDecl>(Method->getDeclContext()))
3309
255k
    if (!CD->IsClassExtension() && 
List->getBits() < 2252k
)
3310
241k
      List->setBits(List->getBits() + 1);
3311
3312
  // If the list is empty, make it a singleton list.
3313
1.12M
  if (List->getMethod() == nullptr) {
3314
914k
    List->setMethod(Method);
3315
914k
    List->setNext(nullptr);
3316
914k
    return;
3317
914k
  }
3318
3319
  // We've seen a method with this name, see if we have already seen this type
3320
  // signature.
3321
214k
  ObjCMethodList *Previous = List;
3322
214k
  ObjCMethodList *ListWithSameDeclaration = nullptr;
3323
1.36M
  for (; List; 
Previous = List, List = List->getNext()1.15M
) {
3324
    // If we are building a module, keep all of the methods.
3325
1.15M
    if (getLangOpts().isCompilingModule())
3326
227k
      continue;
3327
3328
930k
    bool SameDeclaration = MatchTwoMethodDeclarations(Method,
3329
930k
                                                      List->getMethod());
3330
    // Looking for method with a type bound requires the correct context exists.
3331
    // We need to insert a method into the list if the context is different.
3332
    // If the method's declaration matches the list
3333
    // a> the method belongs to a different context: we need to insert it, in
3334
    //    order to emit the availability message, we need to prioritize over
3335
    //    availability among the methods with the same declaration.
3336
    // b> the method belongs to the same context: there is no need to insert a
3337
    //    new entry.
3338
    // If the method's declaration does not match the list, we insert it to the
3339
    // end.
3340
930k
    if (!SameDeclaration ||
3341
930k
        
!isMethodContextSameForKindofLookup(Method, List->getMethod())806k
) {
3342
      // Even if two method types do not match, we would like to say
3343
      // there is more than one declaration so unavailability/deprecated
3344
      // warning is not too noisy.
3345
925k
      if (!Method->isDefined())
3346
914k
        List->setHasMoreThanOneDecl(true);
3347
3348
      // For methods with the same declaration, the one that is deprecated
3349
      // should be put in the front for better diagnostics.
3350
925k
      if (Method->isDeprecated() && 
SameDeclaration113k
&&
3351
925k
          
!ListWithSameDeclaration111k
&&
!List->getMethod()->isDeprecated()31.0k
)
3352
7.14k
        ListWithSameDeclaration = List;
3353
3354
925k
      if (Method->isUnavailable() && 
SameDeclaration83.4k
&&
3355
925k
          
!ListWithSameDeclaration83.4k
&&
3356
925k
          
List->getMethod()->getAvailability() < AR_Deprecated38.5k
)
3357
3.69k
        ListWithSameDeclaration = List;
3358
925k
      continue;
3359
925k
    }
3360
3361
5.00k
    ObjCMethodDecl *PrevObjCMethod = List->getMethod();
3362
3363
    // Propagate the 'defined' bit.
3364
5.00k
    if (Method->isDefined())
3365
3.80k
      PrevObjCMethod->setDefined(true);
3366
1.19k
    else {
3367
      // Objective-C doesn't allow an @interface for a class after its
3368
      // @implementation. So if Method is not defined and there already is
3369
      // an entry for this type signature, Method has to be for a different
3370
      // class than PrevObjCMethod.
3371
1.19k
      List->setHasMoreThanOneDecl(true);
3372
1.19k
    }
3373
3374
    // If a method is deprecated, push it in the global pool.
3375
    // This is used for better diagnostics.
3376
5.00k
    if (Method->isDeprecated()) {
3377
58
      if (!PrevObjCMethod->isDeprecated())
3378
22
        List->setMethod(Method);
3379
58
    }
3380
    // If the new method is unavailable, push it into global pool
3381
    // unless previous one is deprecated.
3382
5.00k
    if (Method->isUnavailable()) {
3383
22
      if (PrevObjCMethod->getAvailability() < AR_Deprecated)
3384
0
        List->setMethod(Method);
3385
22
    }
3386
3387
5.00k
    return;
3388
930k
  }
3389
3390
  // We have a new signature for an existing method - add it.
3391
  // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
3392
209k
  ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
3393
3394
  // We insert it right before ListWithSameDeclaration.
3395
209k
  if (ListWithSameDeclaration) {
3396
10.8k
    auto *List = new (Mem) ObjCMethodList(*ListWithSameDeclaration);
3397
    // FIXME: should we clear the other bits in ListWithSameDeclaration?
3398
10.8k
    ListWithSameDeclaration->setMethod(Method);
3399
10.8k
    ListWithSameDeclaration->setNext(List);
3400
10.8k
    return;
3401
10.8k
  }
3402
3403
198k
  Previous->setNext(new (Mem) ObjCMethodList(Method));
3404
198k
}
3405
3406
/// Read the contents of the method pool for a given selector from
3407
/// external storage.
3408
66.4k
void Sema::ReadMethodPool(Selector Sel) {
3409
66.4k
  assert(ExternalSource && "We need an external AST source");
3410
0
  ExternalSource->ReadMethodPool(Sel);
3411
66.4k
}
3412
3413
1.73k
void Sema::updateOutOfDateSelector(Selector Sel) {
3414
1.73k
  if (!ExternalSource)
3415
0
    return;
3416
1.73k
  ExternalSource->updateOutOfDateSelector(Sel);
3417
1.73k
}
3418
3419
void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
3420
1.12M
                                 bool instance) {
3421
  // Ignore methods of invalid containers.
3422
1.12M
  if (cast<Decl>(Method->getDeclContext())->isInvalidDecl())
3423
36
    return;
3424
3425
1.12M
  if (ExternalSource)
3426
46.2k
    ReadMethodPool(Method->getSelector());
3427
3428
1.12M
  GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
3429
1.12M
  if (Pos == MethodPool.end())
3430
903k
    Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
3431
903k
                                           GlobalMethods())).first;
3432
3433
1.12M
  Method->setDefined(impl);
3434
3435
1.12M
  ObjCMethodList &Entry = instance ? 
Pos->second.first925k
:
Pos->second.second195k
;
3436
1.12M
  addMethodToGlobalList(&Entry, Method);
3437
1.12M
}
3438
3439
/// Determines if this is an "acceptable" loose mismatch in the global
3440
/// method pool.  This exists mostly as a hack to get around certain
3441
/// global mismatches which we can't afford to make warnings / errors.
3442
/// Really, what we want is a way to take a method out of the global
3443
/// method pool.
3444
static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
3445
28
                                       ObjCMethodDecl *other) {
3446
28
  if (!chosen->isInstanceMethod())
3447
0
    return false;
3448
3449
28
  if (chosen->isDirectMethod() != other->isDirectMethod())
3450
1
    return false;
3451
3452
27
  Selector sel = chosen->getSelector();
3453
27
  if (!sel.isUnarySelector() || 
sel.getNameForSlot(0) != "length"11
)
3454
27
    return false;
3455
3456
  // Don't complain about mismatches for -length if the method we
3457
  // chose has an integral result type.
3458
0
  return (chosen->getReturnType()->isIntegerType());
3459
27
}
3460
3461
/// Return true if the given method is wthin the type bound.
3462
static bool FilterMethodsByTypeBound(ObjCMethodDecl *Method,
3463
13.9k
                                     const ObjCObjectType *TypeBound) {
3464
13.9k
  if (!TypeBound)
3465
13.9k
    return true;
3466
3467
23
  if (TypeBound->isObjCId())
3468
    // FIXME: should we handle the case of bounding to id<A, B> differently?
3469
3
    return true;
3470
3471
20
  auto *BoundInterface = TypeBound->getInterface();
3472
20
  assert(BoundInterface && "unexpected object type!");
3473
3474
  // Check if the Method belongs to a protocol. We should allow any method
3475
  // defined in any protocol, because any subclass could adopt the protocol.
3476
0
  auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
3477
20
  if (MethodProtocol) {
3478
1
    return true;
3479
1
  }
3480
3481
  // If the Method belongs to a class, check if it belongs to the class
3482
  // hierarchy of the class bound.
3483
19
  if (ObjCInterfaceDecl *MethodInterface = Method->getClassInterface()) {
3484
    // We allow methods declared within classes that are part of the hierarchy
3485
    // of the class bound (superclass of, subclass of, or the same as the class
3486
    // bound).
3487
19
    return MethodInterface == BoundInterface ||
3488
19
           
MethodInterface->isSuperClassOf(BoundInterface)15
||
3489
19
           
BoundInterface->isSuperClassOf(MethodInterface)14
;
3490
19
  }
3491
0
  llvm_unreachable("unknown method context");
3492
0
}
3493
3494
/// We first select the type of the method: Instance or Factory, then collect
3495
/// all methods with that type.
3496
bool Sema::CollectMultipleMethodsInGlobalPool(
3497
    Selector Sel, SmallVectorImpl<ObjCMethodDecl *> &Methods,
3498
    bool InstanceFirst, bool CheckTheOther,
3499
4.60k
    const ObjCObjectType *TypeBound) {
3500
4.60k
  if (ExternalSource)
3501
796
    ReadMethodPool(Sel);
3502
3503
4.60k
  GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3504
4.60k
  if (Pos == MethodPool.end())
3505
963
    return false;
3506
3507
  // Gather the non-hidden methods.
3508
3.64k
  ObjCMethodList &MethList = InstanceFirst ? 
Pos->second.first3.60k
:
3509
3.64k
                             
Pos->second.second43
;
3510
17.6k
  for (ObjCMethodList *M = &MethList; M; 
M = M->getNext()13.9k
)
3511
13.9k
    if (M->getMethod() && 
M->getMethod()->isUnconditionallyVisible()13.9k
) {
3512
13.9k
      if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
3513
13.9k
        Methods.push_back(M->getMethod());
3514
13.9k
    }
3515
3516
  // Return if we find any method with the desired kind.
3517
3.64k
  if (!Methods.empty())
3518
3.57k
    return Methods.size() > 1;
3519
3520
73
  if (!CheckTheOther)
3521
41
    return false;
3522
3523
  // Gather the other kind.
3524
32
  ObjCMethodList &MethList2 = InstanceFirst ? 
Pos->second.second29
:
3525
32
                              
Pos->second.first3
;
3526
64
  for (ObjCMethodList *M = &MethList2; M; 
M = M->getNext()32
)
3527
32
    if (M->getMethod() && 
M->getMethod()->isUnconditionallyVisible()29
) {
3528
29
      if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
3529
29
        Methods.push_back(M->getMethod());
3530
29
    }
3531
3532
32
  return Methods.size() > 1;
3533
73
}
3534
3535
bool Sema::AreMultipleMethodsInGlobalPool(
3536
    Selector Sel, ObjCMethodDecl *BestMethod, SourceRange R,
3537
3.55k
    bool receiverIdOrClass, SmallVectorImpl<ObjCMethodDecl *> &Methods) {
3538
  // Diagnose finding more than one method in global pool.
3539
3.55k
  SmallVector<ObjCMethodDecl *, 4> FilteredMethods;
3540
3.55k
  FilteredMethods.push_back(BestMethod);
3541
3542
3.55k
  for (auto *M : Methods)
3543
13.8k
    if (M != BestMethod && 
!M->hasAttr<UnavailableAttr>()10.3k
)
3544
10.3k
      FilteredMethods.push_back(M);
3545
3546
3.55k
  if (FilteredMethods.size() > 1)
3547
2.30k
    DiagnoseMultipleMethodInGlobalPool(FilteredMethods, Sel, R,
3548
2.30k
                                       receiverIdOrClass);
3549
3550
3.55k
  GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3551
  // Test for no method in the pool which should not trigger any warning by
3552
  // caller.
3553
3.55k
  if (Pos == MethodPool.end())
3554
0
    return true;
3555
3.55k
  ObjCMethodList &MethList =
3556
3.55k
    BestMethod->isInstanceMethod() ? 
Pos->second.first3.53k
:
Pos->second.second26
;
3557
3.55k
  return MethList.hasMoreThanOneDecl();
3558
3.55k
}
3559
3560
ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3561
                                               bool receiverIdOrClass,
3562
691
                                               bool instance) {
3563
691
  if (ExternalSource)
3564
36
    ReadMethodPool(Sel);
3565
3566
691
  GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3567
691
  if (Pos == MethodPool.end())
3568
264
    return nullptr;
3569
3570
  // Gather the non-hidden methods.
3571
427
  ObjCMethodList &MethList = instance ? 
Pos->second.first341
:
Pos->second.second86
;
3572
427
  SmallVector<ObjCMethodDecl *, 4> Methods;
3573
478
  for (ObjCMethodList *M = &MethList; M; 
M = M->getNext()51
) {
3574
427
    if (M->getMethod() && 
M->getMethod()->isUnconditionallyVisible()376
)
3575
376
      return M->getMethod();
3576
427
  }
3577
51
  return nullptr;
3578
427
}
3579
3580
void Sema::DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3581
                                              Selector Sel, SourceRange R,
3582
2.30k
                                              bool receiverIdOrClass) {
3583
  // We found multiple methods, so we may have to complain.
3584
2.30k
  bool issueDiagnostic = false, issueError = false;
3585
3586
  // We support a warning which complains about *any* difference in
3587
  // method signature.
3588
2.30k
  bool strictSelectorMatch =
3589
2.30k
  receiverIdOrClass &&
3590
2.30k
  !Diags.isIgnored(diag::warn_strict_multiple_method_decl, R.getBegin());
3591
2.30k
  if (strictSelectorMatch) {
3592
7
    for (unsigned I = 1, N = Methods.size(); I != N; 
++I0
) {
3593
7
      if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) {
3594
7
        issueDiagnostic = true;
3595
7
        break;
3596
7
      }
3597
7
    }
3598
7
  }
3599
3600
  // If we didn't see any strict differences, we won't see any loose
3601
  // differences.  In ARC, however, we also need to check for loose
3602
  // mismatches, because most of them are errors.
3603
2.30k
  if (!strictSelectorMatch ||
3604
2.30k
      
(7
issueDiagnostic7
&&
getLangOpts().ObjCAutoRefCount7
))
3605
12.5k
    
for (unsigned I = 1, N = Methods.size(); 2.29k
I != N;
++I10.2k
) {
3606
      // This checks if the methods differ in type mismatch.
3607
10.3k
      if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) &&
3608
10.3k
          
!isAcceptableMethodMismatch(Methods[0], Methods[I])28
) {
3609
28
        issueDiagnostic = true;
3610
28
        if (getLangOpts().ObjCAutoRefCount)
3611
10
          issueError = true;
3612
28
        break;
3613
28
      }
3614
10.3k
    }
3615
3616
2.30k
  if (issueDiagnostic) {
3617
35
    if (issueError)
3618
10
      Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
3619
25
    else if (strictSelectorMatch)
3620
7
      Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
3621
18
    else
3622
18
      Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
3623
3624
35
    Diag(Methods[0]->getBeginLoc(),
3625
35
         issueError ? 
diag::note_possibility10
:
diag::note_using25
)
3626
35
        << Methods[0]->getSourceRange();
3627
76
    for (unsigned I = 1, N = Methods.size(); I != N; 
++I41
) {
3628
41
      Diag(Methods[I]->getBeginLoc(), diag::note_also_found)
3629
41
          << Methods[I]->getSourceRange();
3630
41
    }
3631
35
  }
3632
2.30k
}
3633
3634
106
ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
3635
106
  GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3636
106
  if (Pos == MethodPool.end())
3637
1
    return nullptr;
3638
3639
105
  GlobalMethods &Methods = Pos->second;
3640
175
  for (const ObjCMethodList *Method = &Methods.first; Method;
3641
105
       
Method = Method->getNext()70
)
3642
121
    if (Method->getMethod() &&
3643
121
        
(99
Method->getMethod()->isDefined()99
||
3644
99
         
Method->getMethod()->isPropertyAccessor()54
))
3645
51
      return Method->getMethod();
3646
3647
98
  
for (const ObjCMethodList *Method = &Methods.second; 54
Method;
3648
54
       
Method = Method->getNext()44
)
3649
54
    if (Method->getMethod() &&
3650
54
        
(23
Method->getMethod()->isDefined()23
||
3651
23
         
Method->getMethod()->isPropertyAccessor()13
))
3652
10
      return Method->getMethod();
3653
44
  return nullptr;
3654
54
}
3655
3656
static void
3657
HelperSelectorsForTypoCorrection(
3658
                      SmallVectorImpl<const ObjCMethodDecl *> &BestMethod,
3659
43.8k
                      StringRef Typo, const ObjCMethodDecl * Method) {
3660
43.8k
  const unsigned MaxEditDistance = 1;
3661
43.8k
  unsigned BestEditDistance = MaxEditDistance + 1;
3662
43.8k
  std::string MethodName = Method->getSelector().getAsString();
3663
3664
43.8k
  unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size());
3665
43.8k
  if (MinPossibleEditDistance > 0 &&
3666
43.8k
      
Typo.size() / MinPossibleEditDistance < 142.0k
)
3667
2.48k
    return;
3668
41.3k
  unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance);
3669
41.3k
  if (EditDistance > MaxEditDistance)
3670
41.3k
    return;
3671
61
  if (EditDistance == BestEditDistance)
3672
0
    BestMethod.push_back(Method);
3673
61
  else if (EditDistance < BestEditDistance) {
3674
61
    BestMethod.clear();
3675
61
    BestMethod.push_back(Method);
3676
61
  }
3677
61
}
3678
3679
static bool HelperIsMethodInObjCType(Sema &S, Selector Sel,
3680
45.9k
                                     QualType ObjectType) {
3681
45.9k
  if (ObjectType.isNull())
3682
41.7k
    return true;
3683
4.25k
  if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/))
3684
728
    return true;
3685
3.53k
  return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) !=
3686
3.53k
         nullptr;
3687
4.25k
}
3688
3689
const ObjCMethodDecl *
3690
Sema::SelectorsForTypoCorrection(Selector Sel,
3691
760
                                 QualType ObjectType) {
3692
760
  unsigned NumArgs = Sel.getNumArgs();
3693
760
  SmallVector<const ObjCMethodDecl *, 8> Methods;
3694
760
  bool ObjectIsId = true, ObjectIsClass = true;
3695
760
  if (ObjectType.isNull())
3696
128
    ObjectIsId = ObjectIsClass = false;
3697
632
  else if (!ObjectType->isObjCObjectPointerType())
3698
102
    return nullptr;
3699
530
  else if (const ObjCObjectPointerType *ObjCPtr =
3700
530
           ObjectType->getAsObjCInterfacePointerType()) {
3701
343
    ObjectType = QualType(ObjCPtr->getInterfaceType(), 0);
3702
343
    ObjectIsId = ObjectIsClass = false;
3703
343
  }
3704
187
  else if (ObjectType->isObjCIdType() || 
ObjectType->isObjCQualifiedIdType()38
)
3705
179
    ObjectIsClass = false;
3706
8
  else if (ObjectType->isObjCClassType() || 
ObjectType->isObjCQualifiedClassType()2
)
3707
8
    ObjectIsId = false;
3708
0
  else
3709
0
    return nullptr;
3710
3711
658
  for (GlobalMethodPool::iterator b = MethodPool.begin(),
3712
99.5k
       e = MethodPool.end(); b != e; 
b++98.8k
) {
3713
    // instance methods
3714
218k
    for (ObjCMethodList *M = &b->second.first; M; 
M=M->getNext()119k
)
3715
119k
      if (M->getMethod() &&
3716
119k
          
(M->getMethod()->getSelector().getNumArgs() == NumArgs)98.6k
&&
3717
119k
          
(M->getMethod()->getSelector() != Sel)36.9k
) {
3718
36.8k
        if (ObjectIsId)
3719
824
          Methods.push_back(M->getMethod());
3720
36.0k
        else if (!ObjectIsClass &&
3721
36.0k
                 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3722
36.0k
                                          ObjectType))
3723
33.9k
          Methods.push_back(M->getMethod());
3724
36.8k
      }
3725
    // class methods
3726
199k
    for (ObjCMethodList *M = &b->second.second; M; 
M=M->getNext()100k
)
3727
100k
      if (M->getMethod() &&
3728
100k
          
(M->getMethod()->getSelector().getNumArgs() == NumArgs)24.1k
&&
3729
100k
          
(M->getMethod()->getSelector() != Sel)10.9k
) {
3730
10.8k
        if (ObjectIsClass)
3731
15
          Methods.push_back(M->getMethod());
3732
10.8k
        else if (!ObjectIsId &&
3733
10.8k
                 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3734
9.96k
                                          ObjectType))
3735
9.07k
          Methods.push_back(M->getMethod());
3736
10.8k
      }
3737
98.8k
  }
3738
3739
658
  SmallVector<const ObjCMethodDecl *, 8> SelectedMethods;
3740
44.5k
  for (unsigned i = 0, e = Methods.size(); i < e; 
i++43.8k
) {
3741
43.8k
    HelperSelectorsForTypoCorrection(SelectedMethods,
3742
43.8k
                                     Sel.getAsString(), Methods[i]);
3743
43.8k
  }
3744
658
  return (SelectedMethods.size() == 1) ? 
SelectedMethods[0]42
:
nullptr616
;
3745
760
}
3746
3747
/// DiagnoseDuplicateIvars -
3748
/// Check for duplicate ivars in the entire class at the start of
3749
/// \@implementation. This becomes necesssary because class extension can
3750
/// add ivars to a class in random order which will not be known until
3751
/// class's \@implementation is seen.
3752
void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
3753
35.8k
                                  ObjCInterfaceDecl *SID) {
3754
132k
  for (auto *Ivar : ID->ivars()) {
3755
132k
    if (Ivar->isInvalidDecl())
3756
2
      continue;
3757
132k
    if (IdentifierInfo *II = Ivar->getIdentifier()) {
3758
132k
      ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
3759
132k
      if (prevIvar) {
3760
4
        Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
3761
4
        Diag(prevIvar->getLocation(), diag::note_previous_declaration);
3762
4
        Ivar->setInvalidDecl();
3763
4
      }
3764
132k
    }
3765
132k
  }
3766
35.8k
}
3767
3768
/// Diagnose attempts to define ARC-__weak ivars when __weak is disabled.
3769
4.81k
static void DiagnoseWeakIvars(Sema &S, ObjCImplementationDecl *ID) {
3770
4.81k
  if (S.getLangOpts().ObjCWeak) 
return371
;
3771
3772
4.44k
  for (auto ivar = ID->getClassInterface()->all_declared_ivar_begin();
3773
8.35k
         ivar; 
ivar = ivar->getNextIvar()3.91k
) {
3774
3.91k
    if (ivar->isInvalidDecl()) 
continue16
;
3775
3.90k
    if (ivar->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
3776
4
      if (S.getLangOpts().ObjCWeakRuntime) {
3777
1
        S.Diag(ivar->getLocation(), diag::err_arc_weak_disabled);
3778
3
      } else {
3779
3
        S.Diag(ivar->getLocation(), diag::err_arc_weak_no_runtime);
3780
3
      }
3781
4
    }
3782
3.90k
  }
3783
4.44k
}
3784
3785
/// Diagnose attempts to use flexible array member with retainable object type.
3786
static void DiagnoseRetainableFlexibleArrayMember(Sema &S,
3787
4.81k
                                                  ObjCInterfaceDecl *ID) {
3788
4.81k
  if (!S.getLangOpts().ObjCAutoRefCount)
3789
4.20k
    return;
3790
3791
1.47k
  
for (auto ivar = ID->all_declared_ivar_begin(); 604
ivar;
3792
867
       ivar = ivar->getNextIvar()) {
3793
867
    if (ivar->isInvalidDecl())
3794
1
      continue;
3795
866
    QualType IvarTy = ivar->getType();
3796
866
    if (IvarTy->isIncompleteArrayType() &&
3797
866
        
(IvarTy.getObjCLifetime() != Qualifiers::OCL_ExplicitNone)4
&&
3798
866
        
IvarTy->isObjCLifetimeType()3
) {
3799
1
      S.Diag(ivar->getLocation(), diag::err_flexible_array_arc_retainable);
3800
1
      ivar->setInvalidDecl();
3801
1
    }
3802
866
  }
3803
604
}
3804
3805
270k
Sema::ObjCContainerKind Sema::getObjCContainerKind() const {
3806
270k
  switch (CurContext->getDeclKind()) {
3807
71.0k
    case Decl::ObjCInterface:
3808
71.0k
      return Sema::OCK_Interface;
3809
17.5k
    case Decl::ObjCProtocol:
3810
17.5k
      return Sema::OCK_Protocol;
3811
40.7k
    case Decl::ObjCCategory:
3812
40.7k
      if (cast<ObjCCategoryDecl>(CurContext)->IsClassExtension())
3813
847
        return Sema::OCK_ClassExtension;
3814
39.8k
      return Sema::OCK_Category;
3815
4.82k
    case Decl::ObjCImplementation:
3816
4.82k
      return Sema::OCK_Implementation;
3817
518
    case Decl::ObjCCategoryImpl:
3818
518
      return Sema::OCK_CategoryImplementation;
3819
3820
135k
    default:
3821
135k
      return Sema::OCK_None;
3822
270k
  }
3823
270k
}
3824
3825
32.4k
static bool IsVariableSizedType(QualType T) {
3826
32.4k
  if (T->isIncompleteArrayType())
3827
13
    return true;
3828
32.4k
  const auto *RecordTy = T->getAs<RecordType>();
3829
32.4k
  return (RecordTy && 
RecordTy->getDecl()->hasFlexibleArrayMember()292
);
3830
32.4k
}
3831
3832
134k
static void DiagnoseVariableSizedIvars(Sema &S, ObjCContainerDecl *OCD) {
3833
134k
  ObjCInterfaceDecl *IntfDecl = nullptr;
3834
134k
  ObjCInterfaceDecl::ivar_range Ivars = llvm::make_range(
3835
134k
      ObjCInterfaceDecl::ivar_iterator(), ObjCInterfaceDecl::ivar_iterator());
3836
134k
  if ((IntfDecl = dyn_cast<ObjCInterfaceDecl>(OCD))) {
3837
70.9k
    Ivars = IntfDecl->ivars();
3838
70.9k
  } else 
if (auto *63.6k
ImplDecl63.6k
= dyn_cast<ObjCImplementationDecl>(OCD)) {
3839
4.81k
    IntfDecl = ImplDecl->getClassInterface();
3840
4.81k
    Ivars = ImplDecl->ivars();
3841
58.8k
  } else if (auto *CategoryDecl = dyn_cast<ObjCCategoryDecl>(OCD)) {
3842
40.7k
    if (CategoryDecl->IsClassExtension()) {
3843
846
      IntfDecl = CategoryDecl->getClassInterface();
3844
846
      Ivars = CategoryDecl->ivars();
3845
846
    }
3846
40.7k
  }
3847
3848
  // Check if variable sized ivar is in interface and visible to subclasses.
3849
134k
  if (!isa<ObjCInterfaceDecl>(OCD)) {
3850
63.6k
    for (auto ivar : Ivars) {
3851
2.45k
      if (!ivar->isInvalidDecl() && 
IsVariableSizedType(ivar->getType())2.44k
) {
3852
9
        S.Diag(ivar->getLocation(), diag::warn_variable_sized_ivar_visibility)
3853
9
            << ivar->getDeclName() << ivar->getType();
3854
9
      }
3855
2.45k
    }
3856
63.6k
  }
3857
3858
  // Subsequent checks require interface decl.
3859
134k
  if (!IntfDecl)
3860
58.0k
    return;
3861
3862
  // Check if variable sized ivar is followed by another ivar.
3863
215k
  
for (ObjCIvarDecl *ivar = IntfDecl->all_declared_ivar_begin(); 76.6k
ivar;
3864
138k
       ivar = ivar->getNextIvar()) {
3865
138k
    if (ivar->isInvalidDecl() || 
!ivar->getNextIvar()138k
)
3866
34.4k
      continue;
3867
103k
    QualType IvarTy = ivar->getType();
3868
103k
    bool IsInvalidIvar = false;
3869
103k
    if (IvarTy->isIncompleteArrayType()) {
3870
11
      S.Diag(ivar->getLocation(), diag::err_flexible_array_not_at_end)
3871
11
          << ivar->getDeclName() << IvarTy
3872
11
          << TTK_Class; // Use "class" for Obj-C.
3873
11
      IsInvalidIvar = true;
3874
103k
    } else if (const RecordType *RecordTy = IvarTy->getAs<RecordType>()) {
3875
1.67k
      if (RecordTy->getDecl()->hasFlexibleArrayMember()) {
3876
5
        S.Diag(ivar->getLocation(),
3877
5
               diag::err_objc_variable_sized_type_not_at_end)
3878
5
            << ivar->getDeclName() << IvarTy;
3879
5
        IsInvalidIvar = true;
3880
5
      }
3881
1.67k
    }
3882
103k
    if (IsInvalidIvar) {
3883
16
      S.Diag(ivar->getNextIvar()->getLocation(),
3884
16
             diag::note_next_ivar_declaration)
3885
16
          << ivar->getNextIvar()->getSynthesize();
3886
16
      ivar->setInvalidDecl();
3887
16
    }
3888
103k
  }
3889
3890
  // Check if ObjC container adds ivars after variable sized ivar in superclass.
3891
  // Perform the check only if OCD is the first container to declare ivars to
3892
  // avoid multiple warnings for the same ivar.
3893
76.6k
  ObjCIvarDecl *FirstIvar =
3894
76.6k
      (Ivars.begin() == Ivars.end()) ? 
nullptr43.3k
:
*Ivars.begin()33.3k
;
3895
76.6k
  if (FirstIvar && 
(FirstIvar == IntfDecl->all_declared_ivar_begin())33.3k
) {
3896
32.9k
    const ObjCInterfaceDecl *SuperClass = IntfDecl->getSuperClass();
3897
40.5k
    while (SuperClass && 
SuperClass->ivar_empty()37.5k
)
3898
7.53k
      SuperClass = SuperClass->getSuperClass();
3899
32.9k
    if (SuperClass) {
3900
30.0k
      auto IvarIter = SuperClass->ivar_begin();
3901
30.0k
      std::advance(IvarIter, SuperClass->ivar_size() - 1);
3902
30.0k
      const ObjCIvarDecl *LastIvar = *IvarIter;
3903
30.0k
      if (IsVariableSizedType(LastIvar->getType())) {
3904
6
        S.Diag(FirstIvar->getLocation(),
3905
6
               diag::warn_superclass_variable_sized_type_not_at_end)
3906
6
            << FirstIvar->getDeclName() << LastIvar->getDeclName()
3907
6
            << LastIvar->getType() << SuperClass->getDeclName();
3908
6
        S.Diag(LastIvar->getLocation(), diag::note_entity_declared_at)
3909
6
            << LastIvar->getDeclName();
3910
6
      }
3911
30.0k
    }
3912
32.9k
  }
3913
76.6k
}
3914
3915
static void DiagnoseCategoryDirectMembersProtocolConformance(
3916
    Sema &S, ObjCProtocolDecl *PDecl, ObjCCategoryDecl *CDecl);
3917
3918
static void DiagnoseCategoryDirectMembersProtocolConformance(
3919
    Sema &S, ObjCCategoryDecl *CDecl,
3920
43.2k
    const llvm::iterator_range<ObjCProtocolList::iterator> &Protocols) {
3921
43.2k
  for (auto *PI : Protocols)
3922
2.56k
    DiagnoseCategoryDirectMembersProtocolConformance(S, PI, CDecl);
3923
43.2k
}
3924
3925
static void DiagnoseCategoryDirectMembersProtocolConformance(
3926
2.56k
    Sema &S, ObjCProtocolDecl *PDecl, ObjCCategoryDecl *CDecl) {
3927
2.56k
  if (!PDecl->isThisDeclarationADefinition() && 
PDecl->getDefinition()2
)
3928
0
    PDecl = PDecl->getDefinition();
3929
3930
2.56k
  llvm::SmallVector<const Decl *, 4> DirectMembers;
3931
2.56k
  const auto *IDecl = CDecl->getClassInterface();
3932
26.1k
  for (auto *MD : PDecl->methods()) {
3933
26.1k
    if (!MD->isPropertyAccessor()) {
3934
19.4k
      if (const auto *CMD =
3935
19.4k
              IDecl->getMethod(MD->getSelector(), MD->isInstanceMethod())) {
3936
44
        if (CMD->isDirectMethod())
3937
3
          DirectMembers.push_back(CMD);
3938
44
      }
3939
19.4k
    }
3940
26.1k
  }
3941
6.07k
  for (auto *PD : PDecl->properties()) {
3942
6.07k
    if (const auto *CPD = IDecl->FindPropertyVisibleInPrimaryClass(
3943
6.07k
            PD->getIdentifier(),
3944
6.07k
            PD->isClassProperty()
3945
6.07k
                ? ObjCPropertyQueryKind::OBJC_PR_query_class
3946
6.07k
                : ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
3947
863
      if (CPD->isDirectProperty())
3948
2
        DirectMembers.push_back(CPD);
3949
863
    }
3950
6.07k
  }
3951
2.56k
  if (!DirectMembers.empty()) {
3952
5
    S.Diag(CDecl->getLocation(), diag::err_objc_direct_protocol_conformance)
3953
5
        << CDecl->IsClassExtension() << CDecl << PDecl << IDecl;
3954
5
    for (const auto *MD : DirectMembers)
3955
5
      S.Diag(MD->getLocation(), diag::note_direct_member_here);
3956
5
    return;
3957
5
  }
3958
3959
  // Check on this protocols's referenced protocols, recursively.
3960
2.55k
  DiagnoseCategoryDirectMembersProtocolConformance(S, CDecl,
3961
2.55k
                                                   PDecl->protocols());
3962
2.55k
}
3963
3964
// Note: For class/category implementations, allMethods is always null.
3965
Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods,
3966
134k
                       ArrayRef<DeclGroupPtrTy> allTUVars) {
3967
134k
  if (getObjCContainerKind() == Sema::OCK_None)
3968
0
    return nullptr;
3969
3970
134k
  assert(AtEnd.isValid() && "Invalid location for '@end'");
3971
3972
0
  auto *OCD = cast<ObjCContainerDecl>(CurContext);
3973
134k
  Decl *ClassDecl = OCD;
3974
3975
134k
  bool isInterfaceDeclKind =
3976
134k
        isa<ObjCInterfaceDecl>(ClassDecl) || 
isa<ObjCCategoryDecl>(ClassDecl)63.6k
3977
134k
         || 
isa<ObjCProtocolDecl>(ClassDecl)22.9k
;
3978
134k
  bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
3979
3980
  // Make synthesized accessor stub functions visible.
3981
  // ActOnPropertyImplDecl() creates them as not visible in case
3982
  // they are overridden by an explicit method that is encountered
3983
  // later.
3984
134k
  if (auto *OID = dyn_cast<ObjCImplementationDecl>(CurContext)) {
3985
4.81k
    for (auto PropImpl : OID->property_impls()) {
3986
2.99k
      if (auto *Getter = PropImpl->getGetterMethodDecl())
3987
2.77k
        if (Getter->isSynthesizedAccessorStub())
3988
2.67k
          OID->addDecl(Getter);
3989
2.99k
      if (auto *Setter = PropImpl->getSetterMethodDecl())
3990
2.41k
        if (Setter->isSynthesizedAccessorStub())
3991
2.34k
          OID->addDecl(Setter);
3992
2.99k
    }
3993
4.81k
  }
3994
3995
  // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
3996
134k
  llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
3997
134k
  llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
3998
3999
780k
  for (unsigned i = 0, e = allMethods.size(); i != e; 
i++645k
) {
4000
645k
    ObjCMethodDecl *Method =
4001
645k
      cast_or_null<ObjCMethodDecl>(allMethods[i]);
4002
4003
645k
    if (!Method) 
continue0
; // Already issued a diagnostic.
4004
645k
    if (Method->isInstanceMethod()) {
4005
      /// Check for instance method of the same name with incompatible types
4006
516k
      const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
4007
516k
      bool match = PrevMethod ? 
MatchTwoMethodDeclarations(Method, PrevMethod)19
4008
516k
                              : 
false516k
;
4009
516k
      if ((isInterfaceDeclKind && PrevMethod && 
!match19
)
4010
516k
          || 
(516k
checkIdenticalMethods516k
&&
match0
)) {
4011
5
          Diag(Method->getLocation(), diag::err_duplicate_method_decl)
4012
5
            << Method->getDeclName();
4013
5
          Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
4014
5
        Method->setInvalidDecl();
4015
516k
      } else {
4016
516k
        if (PrevMethod) {
4017
14
          Method->setAsRedeclaration(PrevMethod);
4018
14
          if (!Context.getSourceManager().isInSystemHeader(
4019
14
                 Method->getLocation()))
4020
13
            Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
4021
13
              << Method->getDeclName();
4022
14
          Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
4023
14
        }
4024
516k
        InsMap[Method->getSelector()] = Method;
4025
        /// The following allows us to typecheck messages to "id".
4026
516k
        AddInstanceMethodToGlobalPool(Method);
4027
516k
      }
4028
516k
    } else {
4029
      /// Check for class method of the same name with incompatible types
4030
128k
      const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
4031
128k
      bool match = PrevMethod ? 
MatchTwoMethodDeclarations(Method, PrevMethod)2
4032
128k
                              : 
false128k
;
4033
128k
      if ((isInterfaceDeclKind && PrevMethod && 
!match2
)
4034
128k
          || 
(128k
checkIdenticalMethods128k
&&
match0
)) {
4035
2
        Diag(Method->getLocation(), diag::err_duplicate_method_decl)
4036
2
          << Method->getDeclName();
4037
2
        Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
4038
2
        Method->setInvalidDecl();
4039
128k
      } else {
4040
128k
        if (PrevMethod) {
4041
0
          Method->setAsRedeclaration(PrevMethod);
4042
0
          if (!Context.getSourceManager().isInSystemHeader(
4043
0
                 Method->getLocation()))
4044
0
            Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
4045
0
              << Method->getDeclName();
4046
0
          Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
4047
0
        }
4048
128k
        ClsMap[Method->getSelector()] = Method;
4049
128k
        AddFactoryMethodToGlobalPool(Method);
4050
128k
      }
4051
128k
    }
4052
645k
  }
4053
134k
  if (isa<ObjCInterfaceDecl>(ClassDecl)) {
4054
    // Nothing to do here.
4055
70.9k
  } else 
if (ObjCCategoryDecl *63.6k
C63.6k
= dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
4056
    // Categories are used to extend the class by declaring new methods.
4057
    // By the same token, they are also used to add new properties. No
4058
    // need to compare the added property to those in the class.
4059
4060
40.7k
    if (C->IsClassExtension()) {
4061
846
      ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
4062
846
      DiagnoseClassExtensionDupMethods(C, CCPrimary);
4063
846
    }
4064
4065
40.7k
    DiagnoseCategoryDirectMembersProtocolConformance(*this, C, C->protocols());
4066
40.7k
  }
4067
134k
  if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
4068
134k
    if (CDecl->getIdentifier())
4069
      // ProcessPropertyDecl is responsible for diagnosing conflicts with any
4070
      // user-defined setter/getter. It also synthesizes setter/getter methods
4071
      // and adds them to the DeclContext and global method pools.
4072
133k
      for (auto *I : CDecl->properties())
4073
349k
        ProcessPropertyDecl(I);
4074
134k
    CDecl->setAtEndRange(AtEnd);
4075
134k
  }
4076
134k
  if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
4077
4.81k
    IC->setAtEndRange(AtEnd);
4078
4.81k
    if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
4079
      // Any property declared in a class extension might have user
4080
      // declared setter or getter in current class extension or one
4081
      // of the other class extensions. Mark them as synthesized as
4082
      // property will be synthesized when property with same name is
4083
      // seen in the @implementation.
4084
4.81k
      for (const auto *Ext : IDecl->visible_extensions()) {
4085
450
        for (const auto *Property : Ext->instance_properties()) {
4086
          // Skip over properties declared @dynamic
4087
232
          if (const ObjCPropertyImplDecl *PIDecl
4088
232
              = IC->FindPropertyImplDecl(Property->getIdentifier(),
4089
232
                                         Property->getQueryKind()))
4090
219
            if (PIDecl->getPropertyImplementation()
4091
219
                  == ObjCPropertyImplDecl::Dynamic)
4092
12
              continue;
4093
4094
300
          
for (const auto *Ext : IDecl->visible_extensions())220
{
4095
300
            if (ObjCMethodDecl *GetterMethod =
4096
300
                    Ext->getInstanceMethod(Property->getGetterName()))
4097
174
              GetterMethod->setPropertyAccessor(true);
4098
300
            if (!Property->isReadOnly())
4099
280
              if (ObjCMethodDecl *SetterMethod
4100
280
                    = Ext->getInstanceMethod(Property->getSetterName()))
4101
184
                SetterMethod->setPropertyAccessor(true);
4102
300
          }
4103
220
        }
4104
450
      }
4105
4.81k
      ImplMethodsVsClassMethods(S, IC, IDecl);
4106
4.81k
      AtomicPropertySetterGetterRules(IC, IDecl);
4107
4.81k
      DiagnoseOwningPropertyGetterSynthesis(IC);
4108
4.81k
      DiagnoseUnusedBackingIvarInAccessor(S, IC);
4109
4.81k
      if (IDecl->hasDesignatedInitializers())
4110
14
        DiagnoseMissingDesignatedInitOverrides(IC, IDecl);
4111
4.81k
      DiagnoseWeakIvars(*this, IC);
4112
4.81k
      DiagnoseRetainableFlexibleArrayMember(*this, IDecl);
4113
4114
4.81k
      bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>();
4115
4.81k
      if (IDecl->getSuperClass() == nullptr) {
4116
        // This class has no superclass, so check that it has been marked with
4117
        // __attribute((objc_root_class)).
4118
2.62k
        if (!HasRootClassAttr) {
4119
2.50k
          SourceLocation DeclLoc(IDecl->getLocation());
4120
2.50k
          SourceLocation SuperClassLoc(getLocForEndOfToken(DeclLoc));
4121
2.50k
          Diag(DeclLoc, diag::warn_objc_root_class_missing)
4122
2.50k
            << IDecl->getIdentifier();
4123
          // See if NSObject is in the current scope, and if it is, suggest
4124
          // adding " : NSObject " to the class declaration.
4125
2.50k
          NamedDecl *IF = LookupSingleName(TUScope,
4126
2.50k
                                           NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject),
4127
2.50k
                                           DeclLoc, LookupOrdinaryName);
4128
2.50k
          ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
4129
2.50k
          if (NSObjectDecl && 
NSObjectDecl->getDefinition()292
) {
4130
280
            Diag(SuperClassLoc, diag::note_objc_needs_superclass)
4131
280
              << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject ");
4132
2.22k
          } else {
4133
2.22k
            Diag(SuperClassLoc, diag::note_objc_needs_superclass);
4134
2.22k
          }
4135
2.50k
        }
4136
2.62k
      } else 
if (2.18k
HasRootClassAttr2.18k
) {
4137
        // Complain that only root classes may have this attribute.
4138
1
        Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass);
4139
1
      }
4140
4141
4.81k
      if (const ObjCInterfaceDecl *Super = IDecl->getSuperClass()) {
4142
        // An interface can subclass another interface with a
4143
        // objc_subclassing_restricted attribute when it has that attribute as
4144
        // well (because of interfaces imported from Swift). Therefore we have
4145
        // to check if we can subclass in the implementation as well.
4146
2.18k
        if (IDecl->hasAttr<ObjCSubclassingRestrictedAttr>() &&
4147
2.18k
            
Super->hasAttr<ObjCSubclassingRestrictedAttr>()4
) {
4148
2
          Diag(IC->getLocation(), diag::err_restricted_superclass_mismatch);
4149
2
          Diag(Super->getLocation(), diag::note_class_declared);
4150
2
        }
4151
2.18k
      }
4152
4153
4.81k
      if (IDecl->hasAttr<ObjCClassStubAttr>())
4154
2
        Diag(IC->getLocation(), diag::err_implementation_of_class_stub);
4155
4156
4.81k
      if (LangOpts.ObjCRuntime.isNonFragile()) {
4157
7.08k
        while (IDecl->getSuperClass()) {
4158
2.49k
          DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
4159
2.49k
          IDecl = IDecl->getSuperClass();
4160
2.49k
        }
4161
4.59k
      }
4162
4.81k
    }
4163
4.81k
    SetIvarInitializers(IC);
4164
129k
  } else if (ObjCCategoryImplDecl* CatImplClass =
4165
129k
                                   dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
4166
518
    CatImplClass->setAtEndRange(AtEnd);
4167
4168
    // Find category interface decl and then check that all methods declared
4169
    // in this interface are implemented in the category @implementation.
4170
518
    if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
4171
505
      if (ObjCCategoryDecl *Cat
4172
505
            = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) {
4173
503
        ImplMethodsVsClassMethods(S, CatImplClass, Cat);
4174
503
      }
4175
505
    }
4176
129k
  } else if (const auto *IntfDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
4177
70.9k
    if (const ObjCInterfaceDecl *Super = IntfDecl->getSuperClass()) {
4178
62.8k
      if (!IntfDecl->hasAttr<ObjCSubclassingRestrictedAttr>() &&
4179
62.8k
          
Super->hasAttr<ObjCSubclassingRestrictedAttr>()62.8k
) {
4180
2
        Diag(IntfDecl->getLocation(), diag::err_restricted_superclass_mismatch);
4181
2
        Diag(Super->getLocation(), diag::note_class_declared);
4182
2
      }
4183
62.8k
    }
4184
4185
70.9k
    if (IntfDecl->hasAttr<ObjCClassStubAttr>() &&
4186
70.9k
        
!IntfDecl->hasAttr<ObjCSubclassingRestrictedAttr>()6
)
4187
2
      Diag(IntfDecl->getLocation(), diag::err_class_stub_subclassing_mismatch);
4188
70.9k
  }
4189
134k
  DiagnoseVariableSizedIvars(*this, OCD);
4190
134k
  if (isInterfaceDeclKind) {
4191
    // Reject invalid vardecls.
4192
173k
    for (unsigned i = 0, e = allTUVars.size(); i != e; 
i++44.3k
) {
4193
44.3k
      DeclGroupRef DG = allTUVars[i].get();
4194
91.6k
      for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; 
++I47.2k
)
4195
47.2k
        if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
4196
30.8k
          if (!VDecl->hasExternalStorage())
4197
24
            Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
4198
30.8k
        }
4199
44.3k
    }
4200
129k
  }
4201
134k
  ActOnObjCContainerFinishDefinition();
4202
4203
179k
  for (unsigned i = 0, e = allTUVars.size(); i != e; 
i++44.3k
) {
4204
44.3k
    DeclGroupRef DG = allTUVars[i].get();
4205
91.6k
    for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; 
++I47.2k
)
4206
47.2k
      (*I)->setTopLevelDeclInObjCContainer();
4207
44.3k
    Consumer.HandleTopLevelDeclInObjCContainer(DG);
4208
44.3k
  }
4209
4210
134k
  ActOnDocumentableDecl(ClassDecl);
4211
134k
  return ClassDecl;
4212
134k
}
4213
4214
/// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
4215
/// objective-c's type qualifier from the parser version of the same info.
4216
static Decl::ObjCDeclQualifier
4217
1.61M
CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
4218
1.61M
  return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
4219
1.61M
}
4220
4221
/// Check whether the declared result type of the given Objective-C
4222
/// method declaration is compatible with the method's class.
4223
///
4224
static Sema::ResultTypeCompatibilityKind
4225
CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
4226
653k
                                    ObjCInterfaceDecl *CurrentClass) {
4227
653k
  QualType ResultType = Method->getReturnType();
4228
4229
  // If an Objective-C method inherits its related result type, then its
4230
  // declared result type must be compatible with its own class type. The
4231
  // declared result type is compatible if:
4232
653k
  if (const ObjCObjectPointerType *ResultObjectType
4233
653k
                                = ResultType->getAs<ObjCObjectPointerType>()) {
4234
    //   - it is id or qualified id, or
4235
322k
    if (ResultObjectType->isObjCIdType() ||
4236
322k
        
ResultObjectType->isObjCQualifiedIdType()166k
)
4237
156k
      return Sema::RTC_Compatible;
4238
4239
165k
    if (CurrentClass) {
4240
161k
      if (ObjCInterfaceDecl *ResultClass
4241
161k
                                      = ResultObjectType->getInterfaceDecl()) {
4242
        //   - it is the same as the method's class type, or
4243
159k
        if (declaresSameEntity(CurrentClass, ResultClass))
4244
71.3k
          return Sema::RTC_Compatible;
4245
4246
        //   - it is a superclass of the method's class type
4247
87.9k
        if (ResultClass->isSuperClassOf(CurrentClass))
4248
1.63k
          return Sema::RTC_Compatible;
4249
87.9k
      }
4250
161k
    } else {
4251
      // Any Objective-C pointer type might be acceptable for a protocol
4252
      // method; we just don't know.
4253
3.94k
      return Sema::RTC_Unknown;
4254
3.94k
    }
4255
165k
  }
4256
4257
419k
  return Sema::RTC_Incompatible;
4258
653k
}
4259
4260
namespace {
4261
/// A helper class for searching for methods which a particular method
4262
/// overrides.
4263
class OverrideSearch {
4264
public:
4265
  const ObjCMethodDecl *Method;
4266
  llvm::SmallSetVector<ObjCMethodDecl*, 4> Overridden;
4267
  bool Recursive;
4268
4269
public:
4270
1.12M
  OverrideSearch(Sema &S, const ObjCMethodDecl *method) : Method(method) {
4271
1.12M
    Selector selector = method->getSelector();
4272
4273
    // Bypass this search if we've never seen an instance/class method
4274
    // with this selector before.
4275
1.12M
    Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
4276
1.12M
    if (it == S.MethodPool.end()) {
4277
535k
      if (!S.getExternalSource()) 
return516k
;
4278
19.2k
      S.ReadMethodPool(selector);
4279
4280
19.2k
      it = S.MethodPool.find(selector);
4281
19.2k
      if (it == S.MethodPool.end())
4282
18.8k
        return;
4283
19.2k
    }
4284
587k
    const ObjCMethodList &list =
4285
587k
      method->isInstanceMethod() ? 
it->second.first505k
:
it->second.second81.6k
;
4286
587k
    if (!list.getMethod()) 
return4.21k
;
4287
4288
582k
    const ObjCContainerDecl *container
4289
582k
      = cast<ObjCContainerDecl>(method->getDeclContext());
4290
4291
    // Prevent the search from reaching this container again.  This is
4292
    // important with categories, which override methods from the
4293
    // interface and each other.
4294
582k
    if (const ObjCCategoryDecl *Category =
4295
582k
            dyn_cast<ObjCCategoryDecl>(container)) {
4296
81.3k
      searchFromContainer(container);
4297
81.3k
      if (const ObjCInterfaceDecl *Interface = Category->getClassInterface())
4298
81.3k
        searchFromContainer(Interface);
4299
501k
    } else {
4300
501k
      searchFromContainer(container);
4301
501k
    }
4302
582k
  }
4303
4304
  typedef decltype(Overridden)::iterator iterator;
4305
1.12M
  iterator begin() const { return Overridden.begin(); }
4306
1.12M
  iterator end() const { return Overridden.end(); }
4307
4308
private:
4309
10.2M
  void searchFromContainer(const ObjCContainerDecl *container) {
4310
10.2M
    if (container->isInvalidDecl()) 
return11
;
4311
4312
10.2M
    switch (container->getDeclKind()) {
4313
0
#define OBJCCONTAINER(type, base) \
4314
10.2M
    case Decl::type: \
4315
10.2M
      searchFrom(cast<type##Decl>(container)); \
4316
10.2M
      break;
4317
0
#define ABSTRACT_DECL(expansion)
4318
0
#define DECL(type, base) \
4319
0
    case Decl::type:
4320
0
#include "clang/AST/DeclNodes.inc"
4321
0
      llvm_unreachable("not an ObjC container!");
4322
10.2M
    }
4323
10.2M
  }
4324
4325
1.89M
  void searchFrom(const ObjCProtocolDecl *protocol) {
4326
1.89M
    if (!protocol->hasDefinition())
4327
0
      return;
4328
4329
    // A method in a protocol declaration overrides declarations from
4330
    // referenced ("parent") protocols.
4331
1.89M
    search(protocol->getReferencedProtocols());
4332
1.89M
  }
4333
4334
6.97M
  void searchFrom(const ObjCCategoryDecl *category) {
4335
    // A method in a category declaration overrides declarations from
4336
    // the main class and from protocols the category references.
4337
    // The main class is handled in the constructor.
4338
6.97M
    search(category->getReferencedProtocols());
4339
6.97M
  }
4340
4341
372
  void searchFrom(const ObjCCategoryImplDecl *impl) {
4342
    // A method in a category definition that has a category
4343
    // declaration overrides declarations from the category
4344
    // declaration.
4345
372
    if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
4346
372
      search(category);
4347
372
      if (ObjCInterfaceDecl *Interface = category->getClassInterface())
4348
372
        search(Interface);
4349
4350
    // Otherwise it overrides declarations from the class.
4351
372
    } else 
if (const auto *0
Interface0
= impl->getClassInterface()) {
4352
0
      search(Interface);
4353
0
    }
4354
372
  }
4355
4356
1.34M
  void searchFrom(const ObjCInterfaceDecl *iface) {
4357
    // A method in a class declaration overrides declarations from
4358
1.34M
    if (!iface->hasDefinition())
4359
0
      return;
4360
4361
    //   - categories,
4362
1.34M
    for (auto *Cat : iface->known_categories())
4363
6.98M
      search(Cat);
4364
4365
    //   - the super class, and
4366
1.34M
    if (ObjCInterfaceDecl *super = iface->getSuperClass())
4367
809k
      search(super);
4368
4369
    //   - any referenced protocols.
4370
1.34M
    search(iface->getReferencedProtocols());
4371
1.34M
  }
4372
4373
4.99k
  void searchFrom(const ObjCImplementationDecl *impl) {
4374
    // A method in a class implementation overrides declarations from
4375
    // the class interface.
4376
4.99k
    if (const auto *Interface = impl->getClassInterface())
4377
4.99k
      search(Interface);
4378
4.99k
  }
4379
4380
10.2M
  void search(const ObjCProtocolList &protocols) {
4381
10.2M
    for (const auto *Proto : protocols)
4382
1.90M
      search(Proto);
4383
10.2M
  }
4384
4385
9.70M
  void search(const ObjCContainerDecl *container) {
4386
    // Check for a method in this container which matches this selector.
4387
9.70M
    ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
4388
9.70M
                                                Method->isInstanceMethod(),
4389
9.70M
                                                /*AllowHidden=*/true);
4390
4391
    // If we find one, record it and bail out.
4392
9.70M
    if (meth) {
4393
145k
      Overridden.insert(meth);
4394
145k
      return;
4395
145k
    }
4396
4397
    // Otherwise, search for methods that a hypothetical method here
4398
    // would have overridden.
4399
4400
    // Note that we're now in a recursive case.
4401
9.55M
    Recursive = true;
4402
4403
9.55M
    searchFromContainer(container);
4404
9.55M
  }
4405
};
4406
} // end anonymous namespace
4407
4408
void Sema::CheckObjCMethodDirectOverrides(ObjCMethodDecl *method,
4409
60.0k
                                          ObjCMethodDecl *overridden) {
4410
60.0k
  if (overridden->isDirectMethod()) {
4411
23
    const auto *attr = overridden->getAttr<ObjCDirectAttr>();
4412
23
    Diag(method->getLocation(), diag::err_objc_override_direct_method);
4413
23
    Diag(attr->getLocation(), diag::note_previous_declaration);
4414
60.0k
  } else if (method->isDirectMethod()) {
4415
8
    const auto *attr = method->getAttr<ObjCDirectAttr>();
4416
8
    Diag(attr->getLocation(), diag::err_objc_direct_on_override)
4417
8
        << isa<ObjCProtocolDecl>(overridden->getDeclContext());
4418
8
    Diag(overridden->getLocation(), diag::note_previous_declaration);
4419
8
  }
4420
60.0k
}
4421
4422
void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
4423
                                    ObjCInterfaceDecl *CurrentClass,
4424
1.12M
                                    ResultTypeCompatibilityKind RTC) {
4425
1.12M
  if (!ObjCMethod)
4426
0
    return;
4427
  // Search for overridden methods and merge information down from them.
4428
1.12M
  OverrideSearch overrides(*this, ObjCMethod);
4429
  // Keep track if the method overrides any method in the class's base classes,
4430
  // its protocols, or its categories' protocols; we will keep that info
4431
  // in the ObjCMethodDecl.
4432
  // For this info, a method in an implementation is not considered as
4433
  // overriding the same method in the interface or its categories.
4434
1.12M
  bool hasOverriddenMethodsInBaseOrProtocol = false;
4435
1.12M
  for (ObjCMethodDecl *overridden : overrides) {
4436
144k
    if (!hasOverriddenMethodsInBaseOrProtocol) {
4437
144k
      if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) ||
4438
144k
          
CurrentClass != overridden->getClassInterface()133k
||
4439
144k
          
overridden->isOverriding()84.9k
) {
4440
60.0k
        CheckObjCMethodDirectOverrides(ObjCMethod, overridden);
4441
60.0k
        hasOverriddenMethodsInBaseOrProtocol = true;
4442
84.3k
      } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) {
4443
        // OverrideSearch will return as "overridden" the same method in the
4444
        // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to
4445
        // check whether a category of a base class introduced a method with the
4446
        // same selector, after the interface method declaration.
4447
        // To avoid unnecessary lookups in the majority of cases, we use the
4448
        // extra info bits in GlobalMethodPool to check whether there were any
4449
        // category methods with this selector.
4450
3.49k
        GlobalMethodPool::iterator It =
4451
3.49k
            MethodPool.find(ObjCMethod->getSelector());
4452
3.49k
        if (It != MethodPool.end()) {
4453
3.49k
          ObjCMethodList &List =
4454
3.49k
            ObjCMethod->isInstanceMethod()? 
It->second.first2.91k
:
It->second.second580
;
4455
3.49k
          unsigned CategCount = List.getBits();
4456
3.49k
          if (CategCount > 0) {
4457
            // If the method is in a category we'll do lookup if there were at
4458
            // least 2 category methods recorded, otherwise only one will do.
4459
331
            if (CategCount > 1 ||
4460
331
                
!isa<ObjCCategoryImplDecl>(overridden->getDeclContext())302
) {
4461
331
              OverrideSearch overrides(*this, overridden);
4462
331
              for (ObjCMethodDecl *SuperOverridden : overrides) {
4463
313
                if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) ||
4464
313
                    
CurrentClass != SuperOverridden->getClassInterface()312
) {
4465
3
                  CheckObjCMethodDirectOverrides(ObjCMethod, SuperOverridden);
4466
3
                  hasOverriddenMethodsInBaseOrProtocol = true;
4467
3
                  overridden->setOverriding(true);
4468
3
                  break;
4469
3
                }
4470
313
              }
4471
331
            }
4472
331
          }
4473
3.49k
        }
4474
3.49k
      }
4475
144k
    }
4476
4477
    // Propagate down the 'related result type' bit from overridden methods.
4478
144k
    if (RTC != Sema::RTC_Incompatible && 
overridden->hasRelatedResultType()106k
)
4479
28.4k
      ObjCMethod->setRelatedResultType();
4480
4481
    // Then merge the declarations.
4482
144k
    mergeObjCMethodDecls(ObjCMethod, overridden);
4483
4484
144k
    if (ObjCMethod->isImplicit() && 
overridden->isImplicit()63.9k
)
4485
63.3k
      continue; // Conflicting properties are detected elsewhere.
4486
4487
    // Check for overriding methods
4488
81.4k
    if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) ||
4489
81.4k
        
isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext())38.3k
)
4490
47.8k
      CheckConflictingOverridingMethod(ObjCMethod, overridden,
4491
47.8k
              isa<ObjCProtocolDecl>(overridden->getDeclContext()));
4492
4493
81.4k
    if (CurrentClass && 
overridden->getDeclContext() != CurrentClass81.4k
&&
4494
81.4k
        
isa<ObjCInterfaceDecl>(overridden->getDeclContext())77.7k
&&
4495
81.4k
        
!overridden->isImplicit()31.3k
/* not meant for properties */) {
4496
26.9k
      ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(),
4497
26.9k
                                          E = ObjCMethod->param_end();
4498
26.9k
      ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(),
4499
26.9k
                                     PrevE = overridden->param_end();
4500
44.4k
      for (; ParamI != E && 
PrevI != PrevE17.7k
;
++ParamI, ++PrevI17.4k
) {
4501
17.7k
        assert(PrevI != overridden->param_end() && "Param mismatch");
4502
0
        QualType T1 = Context.getCanonicalType((*ParamI)->getType());
4503
17.7k
        QualType T2 = Context.getCanonicalType((*PrevI)->getType());
4504
        // If type of argument of method in this class does not match its
4505
        // respective argument type in the super class method, issue warning;
4506
17.7k
        if (!Context.typesAreCompatible(T1, T2)) {
4507
336
          Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
4508
336
            << T1 << T2;
4509
336
          Diag(overridden->getLocation(), diag::note_previous_declaration);
4510
336
          break;
4511
336
        }
4512
17.7k
      }
4513
26.9k
    }
4514
81.4k
  }
4515
4516
1.12M
  ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol);
4517
1.12M
}
4518
4519
/// Merge type nullability from for a redeclaration of the same entity,
4520
/// producing the updated type of the redeclared entity.
4521
static QualType mergeTypeNullabilityForRedecl(Sema &S, SourceLocation loc,
4522
                                              QualType type,
4523
                                              bool usesCSKeyword,
4524
                                              SourceLocation prevLoc,
4525
                                              QualType prevType,
4526
8.23k
                                              bool prevUsesCSKeyword) {
4527
  // Determine the nullability of both types.
4528
8.23k
  auto nullability = type->getNullability(S.Context);
4529
8.23k
  auto prevNullability = prevType->getNullability(S.Context);
4530
4531
  // Easy case: both have nullability.
4532
8.23k
  if (nullability.hasValue() == prevNullability.hasValue()) {
4533
    // Neither has nullability; continue.
4534
8.20k
    if (!nullability)
4535
8.18k
      return type;
4536
4537
    // The nullabilities are equivalent; do nothing.
4538
18
    if (*nullability == *prevNullability)
4539
16
      return type;
4540
4541
    // Complain about mismatched nullability.
4542
2
    S.Diag(loc, diag::err_nullability_conflicting)
4543
2
      << DiagNullabilityKind(*nullability, usesCSKeyword)
4544
2
      << DiagNullabilityKind(*prevNullability, prevUsesCSKeyword);
4545
2
    return type;
4546
18
  }
4547
4548
  // If it's the redeclaration that has nullability, don't change anything.
4549
28
  if (nullability)
4550
2
    return type;
4551
4552
  // Otherwise, provide the result with the same nullability.
4553
26
  return S.Context.getAttributedType(
4554
26
           AttributedType::getNullabilityAttrKind(*prevNullability),
4555
26
           type, type);
4556
28
}
4557
4558
/// Merge information from the declaration of a method in the \@interface
4559
/// (or a category/extension) into the corresponding method in the
4560
/// @implementation (for a class or category).
4561
static void mergeInterfaceMethodToImpl(Sema &S,
4562
                                       ObjCMethodDecl *method,
4563
5.05k
                                       ObjCMethodDecl *prevMethod) {
4564
  // Merge the objc_requires_super attribute.
4565
5.05k
  if (prevMethod->hasAttr<ObjCRequiresSuperAttr>() &&
4566
5.05k
      
!method->hasAttr<ObjCRequiresSuperAttr>()80
) {
4567
    // merge the attribute into implementation.
4568
80
    method->addAttr(
4569
80
      ObjCRequiresSuperAttr::CreateImplicit(S.Context,
4570
80
                                            method->getLocation()));
4571
80
  }
4572
4573
  // Merge nullability of the result type.
4574
5.05k
  QualType newReturnType
4575
5.05k
    = mergeTypeNullabilityForRedecl(
4576
5.05k
        S, method->getReturnTypeSourceRange().getBegin(),
4577
5.05k
        method->getReturnType(),
4578
5.05k
        method->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4579
5.05k
        prevMethod->getReturnTypeSourceRange().getBegin(),
4580
5.05k
        prevMethod->getReturnType(),
4581
5.05k
        prevMethod->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4582
5.05k
  method->setReturnType(newReturnType);
4583
4584
  // Handle each of the parameters.
4585
5.05k
  unsigned numParams = method->param_size();
4586
5.05k
  unsigned numPrevParams = prevMethod->param_size();
4587
8.23k
  for (unsigned i = 0, n = std::min(numParams, numPrevParams); i != n; 
++i3.17k
) {
4588
3.17k
    ParmVarDecl *param = method->param_begin()[i];
4589
3.17k
    ParmVarDecl *prevParam = prevMethod->param_begin()[i];
4590
4591
    // Merge nullability.
4592
3.17k
    QualType newParamType
4593
3.17k
      = mergeTypeNullabilityForRedecl(
4594
3.17k
          S, param->getLocation(), param->getType(),
4595
3.17k
          param->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4596
3.17k
          prevParam->getLocation(), prevParam->getType(),
4597
3.17k
          prevParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4598
3.17k
    param->setType(newParamType);
4599
3.17k
  }
4600
5.05k
}
4601
4602
/// Verify that the method parameters/return value have types that are supported
4603
/// by the x86 target.
4604
static void checkObjCMethodX86VectorTypes(Sema &SemaRef,
4605
387
                                          const ObjCMethodDecl *Method) {
4606
387
  assert(SemaRef.getASTContext().getTargetInfo().getTriple().getArch() ==
4607
387
             llvm::Triple::x86 &&
4608
387
         "x86-specific check invoked for a different target");
4609
0
  SourceLocation Loc;
4610
387
  QualType T;
4611
387
  for (const ParmVarDecl *P : Method->parameters()) {
4612
149
    if (P->getType()->isVectorType()) {
4613
54
      Loc = P->getBeginLoc();
4614
54
      T = P->getType();
4615
54
      break;
4616
54
    }
4617
149
  }
4618
387
  if (Loc.isInvalid()) {
4619
333
    if (Method->getReturnType()->isVectorType()) {
4620
23
      Loc = Method->getReturnTypeSourceRange().getBegin();
4621
23
      T = Method->getReturnType();
4622
23
    } else
4623
310
      return;
4624
333
  }
4625
4626
  // Vector parameters/return values are not supported by objc_msgSend on x86 in
4627
  // iOS < 9 and macOS < 10.11.
4628
77
  const auto &Triple = SemaRef.getASTContext().getTargetInfo().getTriple();
4629
77
  VersionTuple AcceptedInVersion;
4630
77
  if (Triple.getOS() == llvm::Triple::IOS)
4631
17
    AcceptedInVersion = VersionTuple(/*Major=*/9);
4632
60
  else if (Triple.isMacOSX())
4633
42
    AcceptedInVersion = VersionTuple(/*Major=*/10, /*Minor=*/11);
4634
18
  else
4635
18
    return;
4636
59
  if (SemaRef.getASTContext().getTargetInfo().getPlatformMinVersion() >=
4637
59
      AcceptedInVersion)
4638
27
    return;
4639
32
  SemaRef.Diag(Loc, diag::err_objc_method_unsupported_param_ret_type)
4640
32
      << T << (Method->getReturnType()->isVectorType() ? /*return value*/ 
18
4641
32
                                                       : /*parameter*/ 
024
)
4642
32
      << (Triple.isMacOSX() ? 
"macOS 10.11"24
:
"iOS 9"8
);
4643
32
}
4644
4645
591k
static void mergeObjCDirectMembers(Sema &S, Decl *CD, ObjCMethodDecl *Method) {
4646
591k
  if (!Method->isDirectMethod() && 
!Method->hasAttr<UnavailableAttr>()591k
&&
4647
591k
      
CD->hasAttr<ObjCDirectMembersAttr>()589k
) {
4648
10
    Method->addAttr(
4649
10
        ObjCDirectAttr::CreateImplicit(S.Context, Method->getLocation()));
4650
10
  }
4651
591k
}
4652
4653
static void checkObjCDirectMethodClashes(Sema &S, ObjCInterfaceDecl *IDecl,
4654
                                         ObjCMethodDecl *Method,
4655
591k
                                         ObjCImplDecl *ImpDecl = nullptr) {
4656
591k
  auto Sel = Method->getSelector();
4657
591k
  bool isInstance = Method->isInstanceMethod();
4658
591k
  bool diagnosed = false;
4659
4660
591k
  auto diagClash = [&](const ObjCMethodDecl *IMD) {
4661
201
    if (diagnosed || IMD->isImplicit())
4662
33
      return;
4663
168
    if (Method->isDirectMethod() || 
IMD->isDirectMethod()166
) {
4664
3
      S.Diag(Method->getLocation(), diag::err_objc_direct_duplicate_decl)
4665
3
          << Method->isDirectMethod() << /* method */ 0 << IMD->isDirectMethod()
4666
3
          << Method->getDeclName();
4667
3
      S.Diag(IMD->getLocation(), diag::note_previous_declaration);
4668
3
      diagnosed = true;
4669
3
    }
4670
168
  };
4671
4672
  // Look for any other declaration of this method anywhere we can see in this
4673
  // compilation unit.
4674
  //
4675
  // We do not use IDecl->lookupMethod() because we have specific needs:
4676
  //
4677
  // - we absolutely do not need to walk protocols, because
4678
  //   diag::err_objc_direct_on_protocol has already been emitted
4679
  //   during parsing if there's a conflict,
4680
  //
4681
  // - when we do not find a match in a given @interface container,
4682
  //   we need to attempt looking it up in the @implementation block if the
4683
  //   translation unit sees it to find more clashes.
4684
4685
591k
  if (auto *IMD = IDecl->getMethod(Sel, isInstance))
4686
176
    diagClash(IMD);
4687
591k
  else if (auto *Impl = IDecl->getImplementation())
4688
2.66k
    if (Impl != ImpDecl)
4689
99
      if (auto *IMD = IDecl->getImplementation()->getMethod(Sel, isInstance))
4690
5
        diagClash(IMD);
4691
4692
591k
  for (const auto *Cat : IDecl->visible_categories())
4693
661k
    if (auto *IMD = Cat->getMethod(Sel, isInstance))
4694
20
      diagClash(IMD);
4695
661k
    else if (auto CatImpl = Cat->getImplementation())
4696
157
      if (CatImpl != ImpDecl)
4697
13
        if (auto *IMD = Cat->getMethod(Sel, isInstance))
4698
0
          diagClash(IMD);
4699
591k
}
4700
4701
Decl *Sema::ActOnMethodDeclaration(
4702
    Scope *S, SourceLocation MethodLoc, SourceLocation EndLoc,
4703
    tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
4704
    ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
4705
    // optional arguments. The number of types/arguments is obtained
4706
    // from the Sel.getNumArgs().
4707
    ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo,
4708
    unsigned CNumArgs, // c-style args
4709
    const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodDeclKind,
4710
653k
    bool isVariadic, bool MethodDefinition) {
4711
  // Make sure we can establish a context for the method.
4712
653k
  if (!CurContext->isObjCContainer()) {
4713
25
    Diag(MethodLoc, diag::err_missing_method_context);
4714
25
    return nullptr;
4715
25
  }
4716
4717
653k
  Decl *ClassDecl = cast<ObjCContainerDecl>(CurContext);
4718
653k
  QualType resultDeclType;
4719
4720
653k
  bool HasRelatedResultType = false;
4721
653k
  TypeSourceInfo *ReturnTInfo = nullptr;
4722
653k
  if (ReturnType) {
4723
651k
    resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo);
4724
4725
651k
    if (CheckFunctionReturnType(resultDeclType, MethodLoc))
4726
4
      return nullptr;
4727
4728
651k
    QualType bareResultType = resultDeclType;
4729
651k
    (void)AttributedType::stripOuterNullability(bareResultType);
4730
651k
    HasRelatedResultType = (bareResultType == Context.getObjCInstanceType());
4731
651k
  } else { // get the type for "id".
4732
1.63k
    resultDeclType = Context.getObjCIdType();
4733
1.63k
    Diag(MethodLoc, diag::warn_missing_method_return_type)
4734
1.63k
      << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
4735
1.63k
  }
4736
4737
653k
  ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create(
4738
653k
      Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext,
4739
653k
      MethodType == tok::minus, isVariadic,
4740
653k
      /*isPropertyAccessor=*/false, /*isSynthesizedAccessorStub=*/false,
4741
653k
      /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
4742
653k
      MethodDeclKind == tok::objc_optional ? 
ObjCMethodDecl::Optional38.8k
4743
653k
                                           : 
ObjCMethodDecl::Required614k
,
4744
653k
      HasRelatedResultType);
4745
4746
653k
  SmallVector<ParmVarDecl*, 16> Params;
4747
4748
1.61M
  for (unsigned i = 0, e = Sel.getNumArgs(); i != e; 
++i963k
) {
4749
963k
    QualType ArgType;
4750
963k
    TypeSourceInfo *DI;
4751
4752
963k
    if (!ArgInfo[i].Type) {
4753
135
      ArgType = Context.getObjCIdType();
4754
135
      DI = nullptr;
4755
963k
    } else {
4756
963k
      ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
4757
963k
    }
4758
4759
963k
    LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
4760
963k
                   LookupOrdinaryName, forRedeclarationInCurContext());
4761
963k
    LookupName(R, S);
4762
963k
    if (R.isSingleResult()) {
4763
11.2k
      NamedDecl *PrevDecl = R.getFoundDecl();
4764
11.2k
      if (S->isDeclScope(PrevDecl)) {
4765
9
        Diag(ArgInfo[i].NameLoc,
4766
9
             (MethodDefinition ? 
diag::warn_method_param_redefinition1
4767
9
                               : 
diag::warn_method_param_declaration8
))
4768
9
          << ArgInfo[i].Name;
4769
9
        Diag(PrevDecl->getLocation(),
4770
9
             diag::note_previous_declaration);
4771
9
      }
4772
11.2k
    }
4773
4774
963k
    SourceLocation StartLoc = DI
4775
963k
      ? 
DI->getTypeLoc().getBeginLoc()963k
4776
963k
      : 
ArgInfo[i].NameLoc135
;
4777
4778
963k
    ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
4779
963k
                                        ArgInfo[i].NameLoc, ArgInfo[i].Name,
4780
963k
                                        ArgType, DI, SC_None);
4781
4782
963k
    Param->setObjCMethodScopeInfo(i);
4783
4784
963k
    Param->setObjCDeclQualifier(
4785
963k
      CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
4786
4787
    // Apply the attributes to the parameter.
4788
963k
    ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
4789
963k
    AddPragmaAttributes(TUScope, Param);
4790
4791
963k
    if (Param->hasAttr<BlocksAttr>()) {
4792
4
      Diag(Param->getLocation(), diag::err_block_on_nonlocal);
4793
4
      Param->setInvalidDecl();
4794
4
    }
4795
963k
    S->AddDecl(Param);
4796
963k
    IdResolver.AddDecl(Param);
4797
4798
963k
    Params.push_back(Param);
4799
963k
  }
4800
4801
653k
  for (unsigned i = 0, e = CNumArgs; i != e; 
++i15
) {
4802
15
    ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
4803
15
    QualType ArgType = Param->getType();
4804
15
    if (ArgType.isNull())
4805
0
      ArgType = Context.getObjCIdType();
4806
15
    else
4807
      // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
4808
15
      ArgType = Context.getAdjustedParameterType(ArgType);
4809
4810
15
    Param->setDeclContext(ObjCMethod);
4811
15
    Params.push_back(Param);
4812
15
  }
4813
4814
653k
  ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
4815
653k
  ObjCMethod->setObjCDeclQualifier(
4816
653k
    CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
4817
4818
653k
  ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
4819
653k
  AddPragmaAttributes(TUScope, ObjCMethod);
4820
4821
  // Add the method now.
4822
653k
  const ObjCMethodDecl *PrevMethod = nullptr;
4823
653k
  if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
4824
7.77k
    if (MethodType == tok::minus) {
4825
6.56k
      PrevMethod = ImpDecl->getInstanceMethod(Sel);
4826
6.56k
      ImpDecl->addInstanceMethod(ObjCMethod);
4827
6.56k
    } else {
4828
1.21k
      PrevMethod = ImpDecl->getClassMethod(Sel);
4829
1.21k
      ImpDecl->addClassMethod(ObjCMethod);
4830
1.21k
    }
4831
4832
    // If this method overrides a previous @synthesize declaration,
4833
    // register it with the property.  Linear search through all
4834
    // properties here, because the autosynthesized stub hasn't been
4835
    // made visible yet, so it can be overriden by a later
4836
    // user-specified implementation.
4837
7.77k
    for (ObjCPropertyImplDecl *PropertyImpl : ImpDecl->property_impls()) {
4838
3.13k
      if (auto *Setter = PropertyImpl->getSetterMethodDecl())
4839
2.32k
        if (Setter->getSelector() == Sel &&
4840
2.32k
            
Setter->isInstanceMethod() == ObjCMethod->isInstanceMethod()47
) {
4841
47
          assert(Setter->isSynthesizedAccessorStub() && "autosynth stub expected");
4842
0
          PropertyImpl->setSetterMethodDecl(ObjCMethod);
4843
47
        }
4844
3.13k
      if (auto *Getter = PropertyImpl->getGetterMethodDecl())
4845
2.94k
        if (Getter->getSelector() == Sel &&
4846
2.94k
            
Getter->isInstanceMethod() == ObjCMethod->isInstanceMethod()48
) {
4847
47
          assert(Getter->isSynthesizedAccessorStub() && "autosynth stub expected");
4848
0
          PropertyImpl->setGetterMethodDecl(ObjCMethod);
4849
47
          break;
4850
47
        }
4851
3.13k
    }
4852
4853
    // A method is either tagged direct explicitly, or inherits it from its
4854
    // canonical declaration.
4855
    //
4856
    // We have to do the merge upfront and not in mergeInterfaceMethodToImpl()
4857
    // because IDecl->lookupMethod() returns more possible matches than just
4858
    // the canonical declaration.
4859
7.77k
    if (!ObjCMethod->isDirectMethod()) {
4860
7.72k
      const ObjCMethodDecl *CanonicalMD = ObjCMethod->getCanonicalDecl();
4861
7.72k
      if (CanonicalMD->isDirectMethod()) {
4862
37
        const auto *attr = CanonicalMD->getAttr<ObjCDirectAttr>();
4863
37
        ObjCMethod->addAttr(
4864
37
            ObjCDirectAttr::CreateImplicit(Context, attr->getLocation()));
4865
37
      }
4866
7.72k
    }
4867
4868
    // Merge information from the @interface declaration into the
4869
    // @implementation.
4870
7.77k
    if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface()) {
4871
7.76k
      if (auto *IMD = IDecl->lookupMethod(ObjCMethod->getSelector(),
4872
7.76k
                                          ObjCMethod->isInstanceMethod())) {
4873
5.05k
        mergeInterfaceMethodToImpl(*this, ObjCMethod, IMD);
4874
4875
        // The Idecl->lookupMethod() above will find declarations for ObjCMethod
4876
        // in one of these places:
4877
        //
4878
        // (1) the canonical declaration in an @interface container paired
4879
        //     with the ImplDecl,
4880
        // (2) non canonical declarations in @interface not paired with the
4881
        //     ImplDecl for the same Class,
4882
        // (3) any superclass container.
4883
        //
4884
        // Direct methods only allow for canonical declarations in the matching
4885
        // container (case 1).
4886
        //
4887
        // Direct methods overriding a superclass declaration (case 3) is
4888
        // handled during overrides checks in CheckObjCMethodOverrides().
4889
        //
4890
        // We deal with same-class container mismatches (Case 2) here.
4891
5.05k
        if (IDecl == IMD->getClassInterface()) {
4892
4.05k
          auto diagContainerMismatch = [&] {
4893
16
            int decl = 0, impl = 0;
4894
4895
16
            if (auto *Cat = dyn_cast<ObjCCategoryDecl>(IMD->getDeclContext()))
4896
12
              decl = Cat->IsClassExtension() ? 
14
:
28
;
4897
4898
16
            if (isa<ObjCCategoryImplDecl>(ImpDecl))
4899
12
              impl = 1 + (decl != 0);
4900
4901
16
            Diag(ObjCMethod->getLocation(),
4902
16
                 diag::err_objc_direct_impl_decl_mismatch)
4903
16
                << decl << impl;
4904
16
            Diag(IMD->getLocation(), diag::note_previous_declaration);
4905
16
          };
4906
4907
4.05k
          if (ObjCMethod->isDirectMethod()) {
4908
54
            const auto *attr = ObjCMethod->getAttr<ObjCDirectAttr>();
4909
54
            if (ObjCMethod->getCanonicalDecl() != IMD) {
4910
8
              diagContainerMismatch();
4911
46
            } else if (!IMD->isDirectMethod()) {
4912
5
              Diag(attr->getLocation(), diag::err_objc_direct_missing_on_decl);
4913
5
              Diag(IMD->getLocation(), diag::note_previous_declaration);
4914
5
            }
4915
3.99k
          } else if (IMD->isDirectMethod()) {
4916
8
            const auto *attr = IMD->getAttr<ObjCDirectAttr>();
4917
8
            if (ObjCMethod->getCanonicalDecl() != IMD) {
4918
8
              diagContainerMismatch();
4919
8
            } else {
4920
0
              ObjCMethod->addAttr(
4921
0
                  ObjCDirectAttr::CreateImplicit(Context, attr->getLocation()));
4922
0
            }
4923
8
          }
4924
4.05k
        }
4925
4926
        // Warn about defining -dealloc in a category.
4927
5.05k
        if (isa<ObjCCategoryImplDecl>(ImpDecl) && 
IMD->isOverriding()358
&&
4928
5.05k
            
ObjCMethod->getSelector().getMethodFamily() == OMF_dealloc20
) {
4929
2
          Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category)
4930
2
            << ObjCMethod->getDeclName();
4931
2
        }
4932
5.05k
      } else {
4933
2.71k
        mergeObjCDirectMembers(*this, ClassDecl, ObjCMethod);
4934
2.71k
        checkObjCDirectMethodClashes(*this, IDecl, ObjCMethod, ImpDecl);
4935
2.71k
      }
4936
4937
      // Warn if a method declared in a protocol to which a category or
4938
      // extension conforms is non-escaping and the implementation's method is
4939
      // escaping.
4940
7.76k
      for (auto *C : IDecl->visible_categories())
4941
1.83k
        for (auto &P : C->protocols())
4942
108
          if (auto *IMD = P->lookupMethod(ObjCMethod->getSelector(),
4943
108
                                          ObjCMethod->isInstanceMethod())) {
4944
15
            assert(ObjCMethod->parameters().size() ==
4945
15
                       IMD->parameters().size() &&
4946
15
                   "Methods have different number of parameters");
4947
0
            auto OI = IMD->param_begin(), OE = IMD->param_end();
4948
15
            auto NI = ObjCMethod->param_begin();
4949
21
            for (; OI != OE; 
++OI, ++NI6
)
4950
6
              diagnoseNoescape(*NI, *OI, C, P, *this);
4951
15
          }
4952
7.76k
    }
4953
645k
  } else {
4954
645k
    if (!isa<ObjCProtocolDecl>(ClassDecl)) {
4955
588k
      mergeObjCDirectMembers(*this, ClassDecl, ObjCMethod);
4956
4957
588k
      ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
4958
588k
      if (!IDecl)
4959
200k
        IDecl = cast<ObjCCategoryDecl>(ClassDecl)->getClassInterface();
4960
      // For valid code, we should always know the primary interface
4961
      // declaration by now, however for invalid code we'll keep parsing
4962
      // but we won't find the primary interface and IDecl will be nil.
4963
588k
      if (IDecl)
4964
588k
        checkObjCDirectMethodClashes(*this, IDecl, ObjCMethod);
4965
588k
    }
4966
4967
645k
    cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
4968
645k
  }
4969
4970
653k
  if (PrevMethod) {
4971
    // You can never have two method definitions with the same name.
4972
3
    Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
4973
3
      << ObjCMethod->getDeclName();
4974
3
    Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
4975
3
    ObjCMethod->setInvalidDecl();
4976
3
    return ObjCMethod;
4977
3
  }
4978
4979
  // If this Objective-C method does not have a related result type, but we
4980
  // are allowed to infer related result types, try to do so based on the
4981
  // method family.
4982
653k
  ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
4983
653k
  if (!CurrentClass) {
4984
264k
    if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
4985
200k
      CurrentClass = Cat->getClassInterface();
4986
64.4k
    else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
4987
7.77k
      CurrentClass = Impl->getClassInterface();
4988
56.6k
    else if (ObjCCategoryImplDecl *CatImpl
4989
56.6k
                                   = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
4990
0
      CurrentClass = CatImpl->getClassInterface();
4991
264k
  }
4992
4993
653k
  ResultTypeCompatibilityKind RTC
4994
653k
    = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass);
4995
4996
653k
  CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC);
4997
4998
653k
  bool ARCError = false;
4999
653k
  if (getLangOpts().ObjCAutoRefCount)
5000
15.9k
    ARCError = CheckARCMethodDecl(ObjCMethod);
5001
5002
  // Infer the related result type when possible.
5003
653k
  if (!ARCError && 
RTC == Sema::RTC_Compatible653k
&&
5004
653k
      
!ObjCMethod->hasRelatedResultType()229k
&&
5005
653k
      
LangOpts.ObjCInferRelatedResultType117k
) {
5006
117k
    bool InferRelatedResultType = false;
5007
117k
    switch (ObjCMethod->getMethodFamily()) {
5008
101k
    case OMF_None:
5009
103k
    case OMF_copy:
5010
103k
    case OMF_dealloc:
5011
103k
    case OMF_finalize:
5012
104k
    case OMF_mutableCopy:
5013
104k
    case OMF_release:
5014
104k
    case OMF_retainCount:
5015
104k
    case OMF_initialize:
5016
104k
    case OMF_performSelector:
5017
104k
      break;
5018
5019
969
    case OMF_alloc:
5020
1.60k
    case OMF_new:
5021
1.60k
        InferRelatedResultType = ObjCMethod->isClassMethod();
5022
1.60k
      break;
5023
5024
10.3k
    case OMF_init:
5025
10.5k
    case OMF_autorelease:
5026
10.7k
    case OMF_retain:
5027
10.7k
    case OMF_self:
5028
10.7k
      InferRelatedResultType = ObjCMethod->isInstanceMethod();
5029
10.7k
      break;
5030
117k
    }
5031
5032
117k
    if (InferRelatedResultType &&
5033
117k
        
!ObjCMethod->getReturnType()->isObjCIndependentClassType()11.9k
)
5034
11.9k
      ObjCMethod->setRelatedResultType();
5035
117k
  }
5036
5037
653k
  if (MethodDefinition &&
5038
653k
      
Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x867.77k
)
5039
387
    checkObjCMethodX86VectorTypes(*this, ObjCMethod);
5040
5041
  // + load method cannot have availability attributes. It get called on
5042
  // startup, so it has to have the availability of the deployment target.
5043
653k
  if (const auto *attr = ObjCMethod->getAttr<AvailabilityAttr>()) {
5044
196k
    if (ObjCMethod->isClassMethod() &&
5045
196k
        
ObjCMethod->getSelector().getAsString() == "load"42.4k
) {
5046
2
      Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
5047
2
          << 0;
5048
2
      ObjCMethod->dropAttr<AvailabilityAttr>();
5049
2
    }
5050
196k
  }
5051
5052
  // Insert the invisible arguments, self and _cmd!
5053
653k
  ObjCMethod->createImplicitParams(Context, ObjCMethod->getClassInterface());
5054
5055
653k
  ActOnDocumentableDecl(ObjCMethod);
5056
5057
653k
  return ObjCMethod;
5058
653k
}
5059
5060
271k
bool Sema::CheckObjCDeclScope(Decl *D) {
5061
  // Following is also an error. But it is caused by a missing @end
5062
  // and diagnostic is issued elsewhere.
5063
271k
  if (isa<ObjCContainerDecl>(CurContext->getRedeclContext()))
5064
4
    return false;
5065
5066
  // If we switched context to translation unit while we are still lexically in
5067
  // an objc container, it means the parser missed emitting an error.
5068
271k
  if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext()))
5069
271k
    return false;
5070
5071
13
  Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
5072
13
  D->setInvalidDecl();
5073
5074
13
  return true;
5075
271k
}
5076
5077
/// Called whe