Coverage Report

Created: 2019-07-24 05:18

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