1 //===--- SemaDeclObjC.cpp - Semantic Analysis for ObjC Declarations -------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for Objective C declarations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/Sema/Lookup.h"
16 #include "clang/Sema/ExternalSemaSource.h"
17 #include "clang/Sema/Scope.h"
18 #include "clang/Sema/ScopeInfo.h"
19 #include "clang/AST/ASTConsumer.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/AST/ASTContext.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/ASTMutationListener.h"
25 #include "clang/Basic/SourceManager.h"
26 #include "clang/Sema/DeclSpec.h"
27 #include "llvm/ADT/DenseSet.h"
28 
29 using namespace clang;
30 
31 /// Check whether the given method, which must be in the 'init'
32 /// family, is a valid member of that family.
33 ///
34 /// \param receiverTypeIfCall - if null, check this as if declaring it;
35 ///   if non-null, check this as if making a call to it with the given
36 ///   receiver type
37 ///
38 /// \return true to indicate that there was an error and appropriate
39 ///   actions were taken
40 bool Sema::checkInitMethod(ObjCMethodDecl *method,
41                            QualType receiverTypeIfCall) {
42   if (method->isInvalidDecl()) return true;
43 
44   // This castAs is safe: methods that don't return an object
45   // pointer won't be inferred as inits and will reject an explicit
46   // objc_method_family(init).
47 
48   // We ignore protocols here.  Should we?  What about Class?
49 
50   const ObjCObjectType *result = method->getResultType()
51     ->castAs<ObjCObjectPointerType>()->getObjectType();
52 
53   if (result->isObjCId()) {
54     return false;
55   } else if (result->isObjCClass()) {
56     // fall through: always an error
57   } else {
58     ObjCInterfaceDecl *resultClass = result->getInterface();
59     assert(resultClass && "unexpected object type!");
60 
61     // It's okay for the result type to still be a forward declaration
62     // if we're checking an interface declaration.
63     if (resultClass->isForwardDecl()) {
64       if (receiverTypeIfCall.isNull() &&
65           !isa<ObjCImplementationDecl>(method->getDeclContext()))
66         return false;
67 
68     // Otherwise, we try to compare class types.
69     } else {
70       // If this method was declared in a protocol, we can't check
71       // anything unless we have a receiver type that's an interface.
72       const ObjCInterfaceDecl *receiverClass = 0;
73       if (isa<ObjCProtocolDecl>(method->getDeclContext())) {
74         if (receiverTypeIfCall.isNull())
75           return false;
76 
77         receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>()
78           ->getInterfaceDecl();
79 
80         // This can be null for calls to e.g. id<Foo>.
81         if (!receiverClass) return false;
82       } else {
83         receiverClass = method->getClassInterface();
84         assert(receiverClass && "method not associated with a class!");
85       }
86 
87       // If either class is a subclass of the other, it's fine.
88       if (receiverClass->isSuperClassOf(resultClass) ||
89           resultClass->isSuperClassOf(receiverClass))
90         return false;
91     }
92   }
93 
94   SourceLocation loc = method->getLocation();
95 
96   // If we're in a system header, and this is not a call, just make
97   // the method unusable.
98   if (receiverTypeIfCall.isNull() && getSourceManager().isInSystemHeader(loc)) {
99     method->addAttr(new (Context) UnavailableAttr(loc, Context,
100                 "init method returns a type unrelated to its receiver type"));
101     return true;
102   }
103 
104   // Otherwise, it's an error.
105   Diag(loc, diag::err_arc_init_method_unrelated_result_type);
106   method->setInvalidDecl();
107   return true;
108 }
109 
110 void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
111                                    const ObjCMethodDecl *Overridden,
112                                    bool IsImplementation) {
113   if (Overridden->hasRelatedResultType() &&
114       !NewMethod->hasRelatedResultType()) {
115     // This can only happen when the method follows a naming convention that
116     // implies a related result type, and the original (overridden) method has
117     // a suitable return type, but the new (overriding) method does not have
118     // a suitable return type.
119     QualType ResultType = NewMethod->getResultType();
120     SourceRange ResultTypeRange;
121     if (const TypeSourceInfo *ResultTypeInfo
122                                         = NewMethod->getResultTypeSourceInfo())
123       ResultTypeRange = ResultTypeInfo->getTypeLoc().getSourceRange();
124 
125     // Figure out which class this method is part of, if any.
126     ObjCInterfaceDecl *CurrentClass
127       = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext());
128     if (!CurrentClass) {
129       DeclContext *DC = NewMethod->getDeclContext();
130       if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC))
131         CurrentClass = Cat->getClassInterface();
132       else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC))
133         CurrentClass = Impl->getClassInterface();
134       else if (ObjCCategoryImplDecl *CatImpl
135                = dyn_cast<ObjCCategoryImplDecl>(DC))
136         CurrentClass = CatImpl->getClassInterface();
137     }
138 
139     if (CurrentClass) {
140       Diag(NewMethod->getLocation(),
141            diag::warn_related_result_type_compatibility_class)
142         << Context.getObjCInterfaceType(CurrentClass)
143         << ResultType
144         << ResultTypeRange;
145     } else {
146       Diag(NewMethod->getLocation(),
147            diag::warn_related_result_type_compatibility_protocol)
148         << ResultType
149         << ResultTypeRange;
150     }
151 
152     if (ObjCMethodFamily Family = Overridden->getMethodFamily())
153       Diag(Overridden->getLocation(),
154            diag::note_related_result_type_overridden_family)
155         << Family;
156     else
157       Diag(Overridden->getLocation(),
158            diag::note_related_result_type_overridden);
159   }
160   if (getLangOptions().ObjCAutoRefCount) {
161     if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() !=
162          Overridden->hasAttr<NSReturnsRetainedAttr>())) {
163         Diag(NewMethod->getLocation(),
164              diag::err_nsreturns_retained_attribute_mismatch) << 1;
165         Diag(Overridden->getLocation(), diag::note_previous_decl)
166         << "method";
167     }
168     if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() !=
169               Overridden->hasAttr<NSReturnsNotRetainedAttr>())) {
170         Diag(NewMethod->getLocation(),
171              diag::err_nsreturns_retained_attribute_mismatch) << 0;
172         Diag(Overridden->getLocation(), diag::note_previous_decl)
173         << "method";
174     }
175     ObjCMethodDecl::param_const_iterator oi = Overridden->param_begin();
176     for (ObjCMethodDecl::param_iterator
177            ni = NewMethod->param_begin(), ne = NewMethod->param_end();
178          ni != ne; ++ni, ++oi) {
179       const ParmVarDecl *oldDecl = (*oi);
180       ParmVarDecl *newDecl = (*ni);
181       if (newDecl->hasAttr<NSConsumedAttr>() !=
182           oldDecl->hasAttr<NSConsumedAttr>()) {
183         Diag(newDecl->getLocation(),
184              diag::err_nsconsumed_attribute_mismatch);
185         Diag(oldDecl->getLocation(), diag::note_previous_decl)
186           << "parameter";
187       }
188     }
189   }
190 }
191 
192 /// \brief Check a method declaration for compatibility with the Objective-C
193 /// ARC conventions.
194 static bool CheckARCMethodDecl(Sema &S, ObjCMethodDecl *method) {
195   ObjCMethodFamily family = method->getMethodFamily();
196   switch (family) {
197   case OMF_None:
198   case OMF_dealloc:
199   case OMF_finalize:
200   case OMF_retain:
201   case OMF_release:
202   case OMF_autorelease:
203   case OMF_retainCount:
204   case OMF_self:
205   case OMF_performSelector:
206     return false;
207 
208   case OMF_init:
209     // If the method doesn't obey the init rules, don't bother annotating it.
210     if (S.checkInitMethod(method, QualType()))
211       return true;
212 
213     method->addAttr(new (S.Context) NSConsumesSelfAttr(SourceLocation(),
214                                                        S.Context));
215 
216     // Don't add a second copy of this attribute, but otherwise don't
217     // let it be suppressed.
218     if (method->hasAttr<NSReturnsRetainedAttr>())
219       return false;
220     break;
221 
222   case OMF_alloc:
223   case OMF_copy:
224   case OMF_mutableCopy:
225   case OMF_new:
226     if (method->hasAttr<NSReturnsRetainedAttr>() ||
227         method->hasAttr<NSReturnsNotRetainedAttr>() ||
228         method->hasAttr<NSReturnsAutoreleasedAttr>())
229       return false;
230     break;
231   }
232 
233   method->addAttr(new (S.Context) NSReturnsRetainedAttr(SourceLocation(),
234                                                         S.Context));
235   return false;
236 }
237 
238 static void DiagnoseObjCImplementedDeprecations(Sema &S,
239                                                 NamedDecl *ND,
240                                                 SourceLocation ImplLoc,
241                                                 int select) {
242   if (ND && ND->isDeprecated()) {
243     S.Diag(ImplLoc, diag::warn_deprecated_def) << select;
244     if (select == 0)
245       S.Diag(ND->getLocation(), diag::note_method_declared_at);
246     else
247       S.Diag(ND->getLocation(), diag::note_previous_decl) << "class";
248   }
249 }
250 
251 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
252 /// pool.
253 void Sema::AddAnyMethodToGlobalPool(Decl *D) {
254   ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
255 
256   // If we don't have a valid method decl, simply return.
257   if (!MDecl)
258     return;
259   if (MDecl->isInstanceMethod())
260     AddInstanceMethodToGlobalPool(MDecl, true);
261   else
262     AddFactoryMethodToGlobalPool(MDecl, true);
263 }
264 
265 /// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
266 /// and user declared, in the method definition's AST.
267 void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
268   assert(getCurMethodDecl() == 0 && "Method parsing confused");
269   ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
270 
271   // If we don't have a valid method decl, simply return.
272   if (!MDecl)
273     return;
274 
275   // Allow all of Sema to see that we are entering a method definition.
276   PushDeclContext(FnBodyScope, MDecl);
277   PushFunctionScope();
278 
279   // Create Decl objects for each parameter, entrring them in the scope for
280   // binding to their use.
281 
282   // Insert the invisible arguments, self and _cmd!
283   MDecl->createImplicitParams(Context, MDecl->getClassInterface());
284 
285   PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
286   PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
287 
288   // Introduce all of the other parameters into this scope.
289   for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(),
290        E = MDecl->param_end(); PI != E; ++PI) {
291     ParmVarDecl *Param = (*PI);
292     if (!Param->isInvalidDecl() &&
293         RequireCompleteType(Param->getLocation(), Param->getType(),
294                             diag::err_typecheck_decl_incomplete_type))
295           Param->setInvalidDecl();
296     if ((*PI)->getIdentifier())
297       PushOnScopeChains(*PI, FnBodyScope);
298   }
299 
300   // In ARC, disallow definition of retain/release/autorelease/retainCount
301   if (getLangOptions().ObjCAutoRefCount) {
302     switch (MDecl->getMethodFamily()) {
303     case OMF_retain:
304     case OMF_retainCount:
305     case OMF_release:
306     case OMF_autorelease:
307       Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def)
308         << MDecl->getSelector();
309       break;
310 
311     case OMF_None:
312     case OMF_dealloc:
313     case OMF_finalize:
314     case OMF_alloc:
315     case OMF_init:
316     case OMF_mutableCopy:
317     case OMF_copy:
318     case OMF_new:
319     case OMF_self:
320     case OMF_performSelector:
321       break;
322     }
323   }
324 
325   // Warn on deprecated methods under -Wdeprecated-implementations,
326   // and prepare for warning on missing super calls.
327   if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) {
328     if (ObjCMethodDecl *IMD =
329           IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod()))
330       DiagnoseObjCImplementedDeprecations(*this,
331                                           dyn_cast<NamedDecl>(IMD),
332                                           MDecl->getLocation(), 0);
333 
334     // If this is "dealloc" or "finalize", set some bit here.
335     // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false.
336     // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set.
337     // Only do this if the current class actually has a superclass.
338     if (IC->getSuperClass()) {
339       ObjCShouldCallSuperDealloc =
340         !(Context.getLangOptions().ObjCAutoRefCount ||
341           Context.getLangOptions().getGC() == LangOptions::GCOnly) &&
342         MDecl->getMethodFamily() == OMF_dealloc;
343       ObjCShouldCallSuperFinalize =
344         Context.getLangOptions().getGC() != LangOptions::NonGC &&
345         MDecl->getMethodFamily() == OMF_finalize;
346     }
347   }
348 }
349 
350 Decl *Sema::
351 ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
352                          IdentifierInfo *ClassName, SourceLocation ClassLoc,
353                          IdentifierInfo *SuperName, SourceLocation SuperLoc,
354                          Decl * const *ProtoRefs, unsigned NumProtoRefs,
355                          const SourceLocation *ProtoLocs,
356                          SourceLocation EndProtoLoc, AttributeList *AttrList) {
357   assert(ClassName && "Missing class identifier");
358 
359   // Check for another declaration kind with the same name.
360   NamedDecl *PrevDecl = LookupSingleName(TUScope, ClassName, ClassLoc,
361                                          LookupOrdinaryName, ForRedeclaration);
362 
363   if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
364     Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
365     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
366   }
367 
368   ObjCInterfaceDecl* IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
369   if (IDecl) {
370     // Class already seen. Is it a forward declaration?
371     if (!IDecl->isForwardDecl()) {
372       IDecl->setInvalidDecl();
373       Diag(AtInterfaceLoc, diag::err_duplicate_class_def)<<IDecl->getDeclName();
374       Diag(IDecl->getLocation(), diag::note_previous_definition);
375 
376       // Create a new one; the other may be in a different DeclContex, (e.g.
377       // this one may be in a LinkageSpecDecl while the other is not) which
378       // will break invariants.
379       IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc,
380                                         ClassName, ClassLoc);
381       if (AttrList)
382         ProcessDeclAttributeList(TUScope, IDecl, AttrList);
383       PushOnScopeChains(IDecl, TUScope);
384 
385     } else {
386       IDecl->setLocation(ClassLoc);
387       IDecl->setAtStartLoc(AtInterfaceLoc);
388 
389       // Since this ObjCInterfaceDecl was created by a forward declaration,
390       // we now add it to the DeclContext since it wasn't added before
391       // (see ActOnForwardClassDeclaration).
392       IDecl->setLexicalDeclContext(CurContext);
393       CurContext->addDecl(IDecl);
394 
395       IDecl->completedForwardDecl();
396 
397       if (AttrList)
398         ProcessDeclAttributeList(TUScope, IDecl, AttrList);
399     }
400   } else {
401     IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc,
402                                       ClassName, ClassLoc);
403     if (AttrList)
404       ProcessDeclAttributeList(TUScope, IDecl, AttrList);
405 
406     PushOnScopeChains(IDecl, TUScope);
407   }
408 
409   if (SuperName) {
410     // Check if a different kind of symbol declared in this scope.
411     PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
412                                 LookupOrdinaryName);
413 
414     if (!PrevDecl) {
415       // Try to correct for a typo in the superclass name.
416       TypoCorrection Corrected = CorrectTypo(
417           DeclarationNameInfo(SuperName, SuperLoc), LookupOrdinaryName, TUScope,
418           NULL, NULL, false, CTC_NoKeywords);
419       if ((PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>())) {
420         Diag(SuperLoc, diag::err_undef_superclass_suggest)
421           << SuperName << ClassName << PrevDecl->getDeclName();
422         Diag(PrevDecl->getLocation(), diag::note_previous_decl)
423           << PrevDecl->getDeclName();
424       }
425     }
426 
427     if (PrevDecl == IDecl) {
428       Diag(SuperLoc, diag::err_recursive_superclass)
429         << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
430       IDecl->setLocEnd(ClassLoc);
431     } else {
432       ObjCInterfaceDecl *SuperClassDecl =
433                                 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
434 
435       // Diagnose classes that inherit from deprecated classes.
436       if (SuperClassDecl)
437         (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
438 
439       if (PrevDecl && SuperClassDecl == 0) {
440         // The previous declaration was not a class decl. Check if we have a
441         // typedef. If we do, get the underlying class type.
442         if (const TypedefNameDecl *TDecl =
443               dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
444           QualType T = TDecl->getUnderlyingType();
445           if (T->isObjCObjectType()) {
446             if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface())
447               SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
448           }
449         }
450 
451         // This handles the following case:
452         //
453         // typedef int SuperClass;
454         // @interface MyClass : SuperClass {} @end
455         //
456         if (!SuperClassDecl) {
457           Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
458           Diag(PrevDecl->getLocation(), diag::note_previous_definition);
459         }
460       }
461 
462       if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
463         if (!SuperClassDecl)
464           Diag(SuperLoc, diag::err_undef_superclass)
465             << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
466         else if (RequireCompleteType(SuperLoc,
467                    Context.getObjCInterfaceType(SuperClassDecl),
468                    PDiag(diag::err_forward_superclass)
469                      << SuperClassDecl->getDeclName()
470                      << ClassName
471                    << SourceRange(AtInterfaceLoc, ClassLoc))) {
472           SuperClassDecl = 0;
473         }
474       }
475       IDecl->setSuperClass(SuperClassDecl);
476       IDecl->setSuperClassLoc(SuperLoc);
477       IDecl->setLocEnd(SuperLoc);
478     }
479   } else { // we have a root class.
480     IDecl->setLocEnd(ClassLoc);
481   }
482 
483   // Check then save referenced protocols.
484   if (NumProtoRefs) {
485     IDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
486                            ProtoLocs, Context);
487     IDecl->setLocEnd(EndProtoLoc);
488   }
489 
490   CheckObjCDeclScope(IDecl);
491   return ActOnObjCContainerStartDefinition(IDecl);
492 }
493 
494 /// ActOnCompatiblityAlias - this action is called after complete parsing of
495 /// @compatibility_alias declaration. It sets up the alias relationships.
496 Decl *Sema::ActOnCompatiblityAlias(SourceLocation AtLoc,
497                                         IdentifierInfo *AliasName,
498                                         SourceLocation AliasLocation,
499                                         IdentifierInfo *ClassName,
500                                         SourceLocation ClassLocation) {
501   // Look for previous declaration of alias name
502   NamedDecl *ADecl = LookupSingleName(TUScope, AliasName, AliasLocation,
503                                       LookupOrdinaryName, ForRedeclaration);
504   if (ADecl) {
505     if (isa<ObjCCompatibleAliasDecl>(ADecl))
506       Diag(AliasLocation, diag::warn_previous_alias_decl);
507     else
508       Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
509     Diag(ADecl->getLocation(), diag::note_previous_declaration);
510     return 0;
511   }
512   // Check for class declaration
513   NamedDecl *CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
514                                        LookupOrdinaryName, ForRedeclaration);
515   if (const TypedefNameDecl *TDecl =
516         dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
517     QualType T = TDecl->getUnderlyingType();
518     if (T->isObjCObjectType()) {
519       if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
520         ClassName = IDecl->getIdentifier();
521         CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
522                                   LookupOrdinaryName, ForRedeclaration);
523       }
524     }
525   }
526   ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
527   if (CDecl == 0) {
528     Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
529     if (CDeclU)
530       Diag(CDeclU->getLocation(), diag::note_previous_declaration);
531     return 0;
532   }
533 
534   // Everything checked out, instantiate a new alias declaration AST.
535   ObjCCompatibleAliasDecl *AliasDecl =
536     ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
537 
538   if (!CheckObjCDeclScope(AliasDecl))
539     PushOnScopeChains(AliasDecl, TUScope);
540 
541   return AliasDecl;
542 }
543 
544 bool Sema::CheckForwardProtocolDeclarationForCircularDependency(
545   IdentifierInfo *PName,
546   SourceLocation &Ploc, SourceLocation PrevLoc,
547   const ObjCList<ObjCProtocolDecl> &PList) {
548 
549   bool res = false;
550   for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
551        E = PList.end(); I != E; ++I) {
552     if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
553                                                  Ploc)) {
554       if (PDecl->getIdentifier() == PName) {
555         Diag(Ploc, diag::err_protocol_has_circular_dependency);
556         Diag(PrevLoc, diag::note_previous_definition);
557         res = true;
558       }
559       if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
560             PDecl->getLocation(), PDecl->getReferencedProtocols()))
561         res = true;
562     }
563   }
564   return res;
565 }
566 
567 Decl *
568 Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
569                                   IdentifierInfo *ProtocolName,
570                                   SourceLocation ProtocolLoc,
571                                   Decl * const *ProtoRefs,
572                                   unsigned NumProtoRefs,
573                                   const SourceLocation *ProtoLocs,
574                                   SourceLocation EndProtoLoc,
575                                   AttributeList *AttrList) {
576   bool err = false;
577   // FIXME: Deal with AttrList.
578   assert(ProtocolName && "Missing protocol identifier");
579   ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolName, ProtocolLoc);
580   if (PDecl) {
581     // Protocol already seen. Better be a forward protocol declaration
582     if (!PDecl->isForwardDecl()) {
583       Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
584       Diag(PDecl->getLocation(), diag::note_previous_definition);
585 
586       // Create a new one; the other may be in a different DeclContex, (e.g.
587       // this one may be in a LinkageSpecDecl while the other is not) which
588       // will break invariants.
589       // We will not add it to scope chains to ignore it as the warning says.
590       PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
591                                        ProtocolLoc, AtProtoInterfaceLoc,
592                                        /*isForwardDecl=*/false);
593 
594     } else {
595       ObjCList<ObjCProtocolDecl> PList;
596       PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
597       err = CheckForwardProtocolDeclarationForCircularDependency(
598               ProtocolName, ProtocolLoc, PDecl->getLocation(), PList);
599 
600       // Make sure the cached decl gets a valid start location.
601       PDecl->setAtStartLoc(AtProtoInterfaceLoc);
602       PDecl->setLocation(ProtocolLoc);
603       // Since this ObjCProtocolDecl was created by a forward declaration,
604       // we now add it to the DeclContext since it wasn't added before
605       PDecl->setLexicalDeclContext(CurContext);
606       CurContext->addDecl(PDecl);
607       PDecl->completedForwardDecl();
608     }
609   } else {
610     PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
611                                      ProtocolLoc, AtProtoInterfaceLoc,
612                                      /*isForwardDecl=*/false);
613     PushOnScopeChains(PDecl, TUScope);
614   }
615   if (AttrList)
616     ProcessDeclAttributeList(TUScope, PDecl, AttrList);
617   if (!err && NumProtoRefs ) {
618     /// Check then save referenced protocols.
619     PDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
620                            ProtoLocs, Context);
621     PDecl->setLocEnd(EndProtoLoc);
622   }
623 
624   CheckObjCDeclScope(PDecl);
625   return ActOnObjCContainerStartDefinition(PDecl);
626 }
627 
628 /// FindProtocolDeclaration - This routine looks up protocols and
629 /// issues an error if they are not declared. It returns list of
630 /// protocol declarations in its 'Protocols' argument.
631 void
632 Sema::FindProtocolDeclaration(bool WarnOnDeclarations,
633                               const IdentifierLocPair *ProtocolId,
634                               unsigned NumProtocols,
635                               SmallVectorImpl<Decl *> &Protocols) {
636   for (unsigned i = 0; i != NumProtocols; ++i) {
637     ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolId[i].first,
638                                              ProtocolId[i].second);
639     if (!PDecl) {
640       TypoCorrection Corrected = CorrectTypo(
641           DeclarationNameInfo(ProtocolId[i].first, ProtocolId[i].second),
642           LookupObjCProtocolName, TUScope, NULL, NULL, false, CTC_NoKeywords);
643       if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>())) {
644         Diag(ProtocolId[i].second, diag::err_undeclared_protocol_suggest)
645           << ProtocolId[i].first << Corrected.getCorrection();
646         Diag(PDecl->getLocation(), diag::note_previous_decl)
647           << PDecl->getDeclName();
648       }
649     }
650 
651     if (!PDecl) {
652       Diag(ProtocolId[i].second, diag::err_undeclared_protocol)
653         << ProtocolId[i].first;
654       continue;
655     }
656 
657     (void)DiagnoseUseOfDecl(PDecl, ProtocolId[i].second);
658 
659     // If this is a forward declaration and we are supposed to warn in this
660     // case, do it.
661     if (WarnOnDeclarations && PDecl->isForwardDecl())
662       Diag(ProtocolId[i].second, diag::warn_undef_protocolref)
663         << ProtocolId[i].first;
664     Protocols.push_back(PDecl);
665   }
666 }
667 
668 /// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
669 /// a class method in its extension.
670 ///
671 void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
672                                             ObjCInterfaceDecl *ID) {
673   if (!ID)
674     return;  // Possibly due to previous error
675 
676   llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
677   for (ObjCInterfaceDecl::method_iterator i = ID->meth_begin(),
678        e =  ID->meth_end(); i != e; ++i) {
679     ObjCMethodDecl *MD = *i;
680     MethodMap[MD->getSelector()] = MD;
681   }
682 
683   if (MethodMap.empty())
684     return;
685   for (ObjCCategoryDecl::method_iterator i = CAT->meth_begin(),
686        e =  CAT->meth_end(); i != e; ++i) {
687     ObjCMethodDecl *Method = *i;
688     const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
689     if (PrevMethod && !MatchTwoMethodDeclarations(Method, PrevMethod)) {
690       Diag(Method->getLocation(), diag::err_duplicate_method_decl)
691             << Method->getDeclName();
692       Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
693     }
694   }
695 }
696 
697 /// ActOnForwardProtocolDeclaration - Handle @protocol foo;
698 Decl *
699 Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
700                                       const IdentifierLocPair *IdentList,
701                                       unsigned NumElts,
702                                       AttributeList *attrList) {
703   SmallVector<ObjCProtocolDecl*, 32> Protocols;
704   SmallVector<SourceLocation, 8> ProtoLocs;
705 
706   for (unsigned i = 0; i != NumElts; ++i) {
707     IdentifierInfo *Ident = IdentList[i].first;
708     ObjCProtocolDecl *PDecl = LookupProtocol(Ident, IdentList[i].second);
709     bool isNew = false;
710     if (PDecl == 0) { // Not already seen?
711       PDecl = ObjCProtocolDecl::Create(Context, CurContext, Ident,
712                                        IdentList[i].second, AtProtocolLoc,
713                                        /*isForwardDecl=*/true);
714       PushOnScopeChains(PDecl, TUScope, false);
715       isNew = true;
716     }
717     if (attrList) {
718       ProcessDeclAttributeList(TUScope, PDecl, attrList);
719       if (!isNew) {
720         if (ASTMutationListener *L = Context.getASTMutationListener())
721           L->UpdatedAttributeList(PDecl);
722       }
723     }
724     Protocols.push_back(PDecl);
725     ProtoLocs.push_back(IdentList[i].second);
726   }
727 
728   ObjCForwardProtocolDecl *PDecl =
729     ObjCForwardProtocolDecl::Create(Context, CurContext, AtProtocolLoc,
730                                     Protocols.data(), Protocols.size(),
731                                     ProtoLocs.data());
732   CurContext->addDecl(PDecl);
733   CheckObjCDeclScope(PDecl);
734   return PDecl;
735 }
736 
737 Decl *Sema::
738 ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
739                             IdentifierInfo *ClassName, SourceLocation ClassLoc,
740                             IdentifierInfo *CategoryName,
741                             SourceLocation CategoryLoc,
742                             Decl * const *ProtoRefs,
743                             unsigned NumProtoRefs,
744                             const SourceLocation *ProtoLocs,
745                             SourceLocation EndProtoLoc) {
746   ObjCCategoryDecl *CDecl;
747   ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
748 
749   /// Check that class of this category is already completely declared.
750 
751   if (!IDecl
752       || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
753                              PDiag(diag::err_category_forward_interface)
754                                << (CategoryName == 0))) {
755     // Create an invalid ObjCCategoryDecl to serve as context for
756     // the enclosing method declarations.  We mark the decl invalid
757     // to make it clear that this isn't a valid AST.
758     CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
759                                      ClassLoc, CategoryLoc, CategoryName,IDecl);
760     CDecl->setInvalidDecl();
761 
762     if (!IDecl)
763       Diag(ClassLoc, diag::err_undef_interface) << ClassName;
764     return ActOnObjCContainerStartDefinition(CDecl);
765   }
766 
767   if (!CategoryName && IDecl->getImplementation()) {
768     Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
769     Diag(IDecl->getImplementation()->getLocation(),
770           diag::note_implementation_declared);
771   }
772 
773   if (CategoryName) {
774     /// Check for duplicate interface declaration for this category
775     ObjCCategoryDecl *CDeclChain;
776     for (CDeclChain = IDecl->getCategoryList(); CDeclChain;
777          CDeclChain = CDeclChain->getNextClassCategory()) {
778       if (CDeclChain->getIdentifier() == CategoryName) {
779         // Class extensions can be declared multiple times.
780         Diag(CategoryLoc, diag::warn_dup_category_def)
781           << ClassName << CategoryName;
782         Diag(CDeclChain->getLocation(), diag::note_previous_definition);
783         break;
784       }
785     }
786   }
787 
788   CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
789                                    ClassLoc, CategoryLoc, CategoryName, IDecl);
790   // FIXME: PushOnScopeChains?
791   CurContext->addDecl(CDecl);
792 
793   if (NumProtoRefs) {
794     CDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
795                            ProtoLocs, Context);
796     // Protocols in the class extension belong to the class.
797     if (CDecl->IsClassExtension())
798      IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl**)ProtoRefs,
799                                             NumProtoRefs, Context);
800   }
801 
802   CheckObjCDeclScope(CDecl);
803   return ActOnObjCContainerStartDefinition(CDecl);
804 }
805 
806 /// ActOnStartCategoryImplementation - Perform semantic checks on the
807 /// category implementation declaration and build an ObjCCategoryImplDecl
808 /// object.
809 Decl *Sema::ActOnStartCategoryImplementation(
810                       SourceLocation AtCatImplLoc,
811                       IdentifierInfo *ClassName, SourceLocation ClassLoc,
812                       IdentifierInfo *CatName, SourceLocation CatLoc) {
813   ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
814   ObjCCategoryDecl *CatIDecl = 0;
815   if (IDecl) {
816     CatIDecl = IDecl->FindCategoryDeclaration(CatName);
817     if (!CatIDecl) {
818       // Category @implementation with no corresponding @interface.
819       // Create and install one.
820       CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, SourceLocation(),
821                                           SourceLocation(), SourceLocation(),
822                                           CatName, IDecl);
823     }
824   }
825 
826   ObjCCategoryImplDecl *CDecl =
827     ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl,
828                                  ClassLoc, AtCatImplLoc);
829   /// Check that class of this category is already completely declared.
830   if (!IDecl) {
831     Diag(ClassLoc, diag::err_undef_interface) << ClassName;
832     CDecl->setInvalidDecl();
833   } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
834                                  diag::err_undef_interface)) {
835     CDecl->setInvalidDecl();
836   }
837 
838   // FIXME: PushOnScopeChains?
839   CurContext->addDecl(CDecl);
840 
841   // If the interface is deprecated/unavailable, warn/error about it.
842   if (IDecl)
843     DiagnoseUseOfDecl(IDecl, ClassLoc);
844 
845   /// Check that CatName, category name, is not used in another implementation.
846   if (CatIDecl) {
847     if (CatIDecl->getImplementation()) {
848       Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
849         << CatName;
850       Diag(CatIDecl->getImplementation()->getLocation(),
851            diag::note_previous_definition);
852     } else {
853       CatIDecl->setImplementation(CDecl);
854       // Warn on implementating category of deprecated class under
855       // -Wdeprecated-implementations flag.
856       DiagnoseObjCImplementedDeprecations(*this,
857                                           dyn_cast<NamedDecl>(IDecl),
858                                           CDecl->getLocation(), 2);
859     }
860   }
861 
862   CheckObjCDeclScope(CDecl);
863   return ActOnObjCContainerStartDefinition(CDecl);
864 }
865 
866 Decl *Sema::ActOnStartClassImplementation(
867                       SourceLocation AtClassImplLoc,
868                       IdentifierInfo *ClassName, SourceLocation ClassLoc,
869                       IdentifierInfo *SuperClassname,
870                       SourceLocation SuperClassLoc) {
871   ObjCInterfaceDecl* IDecl = 0;
872   // Check for another declaration kind with the same name.
873   NamedDecl *PrevDecl
874     = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
875                        ForRedeclaration);
876   if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
877     Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
878     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
879   } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
880     if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
881                             diag::warn_undef_interface))
882       IDecl = 0;
883   } else {
884     // We did not find anything with the name ClassName; try to correct for
885     // typos in the class name.
886     TypoCorrection Corrected = CorrectTypo(
887         DeclarationNameInfo(ClassName, ClassLoc), LookupOrdinaryName, TUScope,
888         NULL, NULL, false, CTC_NoKeywords);
889     if ((IDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>())) {
890       // Suggest the (potentially) correct interface name. However, put the
891       // fix-it hint itself in a separate note, since changing the name in
892       // the warning would make the fix-it change semantics.However, don't
893       // provide a code-modification hint or use the typo name for recovery,
894       // because this is just a warning. The program may actually be correct.
895       DeclarationName CorrectedName = Corrected.getCorrection();
896       Diag(ClassLoc, diag::warn_undef_interface_suggest)
897         << ClassName << CorrectedName;
898       Diag(IDecl->getLocation(), diag::note_previous_decl) << CorrectedName
899         << FixItHint::CreateReplacement(ClassLoc, CorrectedName.getAsString());
900       IDecl = 0;
901     } else {
902       Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
903     }
904   }
905 
906   // Check that super class name is valid class name
907   ObjCInterfaceDecl* SDecl = 0;
908   if (SuperClassname) {
909     // Check if a different kind of symbol declared in this scope.
910     PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
911                                 LookupOrdinaryName);
912     if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
913       Diag(SuperClassLoc, diag::err_redefinition_different_kind)
914         << SuperClassname;
915       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
916     } else {
917       SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
918       if (!SDecl)
919         Diag(SuperClassLoc, diag::err_undef_superclass)
920           << SuperClassname << ClassName;
921       else if (IDecl && IDecl->getSuperClass() != SDecl) {
922         // This implementation and its interface do not have the same
923         // super class.
924         Diag(SuperClassLoc, diag::err_conflicting_super_class)
925           << SDecl->getDeclName();
926         Diag(SDecl->getLocation(), diag::note_previous_definition);
927       }
928     }
929   }
930 
931   if (!IDecl) {
932     // Legacy case of @implementation with no corresponding @interface.
933     // Build, chain & install the interface decl into the identifier.
934 
935     // FIXME: Do we support attributes on the @implementation? If so we should
936     // copy them over.
937     IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
938                                       ClassName, ClassLoc, false, true);
939     IDecl->setSuperClass(SDecl);
940     IDecl->setLocEnd(ClassLoc);
941 
942     PushOnScopeChains(IDecl, TUScope);
943   } else {
944     // Mark the interface as being completed, even if it was just as
945     //   @class ....;
946     // declaration; the user cannot reopen it.
947     if (IDecl->isForwardDecl())
948       IDecl->completedForwardDecl();
949   }
950 
951   ObjCImplementationDecl* IMPDecl =
952     ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl,
953                                    ClassLoc, AtClassImplLoc);
954 
955   if (CheckObjCDeclScope(IMPDecl))
956     return ActOnObjCContainerStartDefinition(IMPDecl);
957 
958   // Check that there is no duplicate implementation of this class.
959   if (IDecl->getImplementation()) {
960     // FIXME: Don't leak everything!
961     Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
962     Diag(IDecl->getImplementation()->getLocation(),
963          diag::note_previous_definition);
964   } else { // add it to the list.
965     IDecl->setImplementation(IMPDecl);
966     PushOnScopeChains(IMPDecl, TUScope);
967     // Warn on implementating deprecated class under
968     // -Wdeprecated-implementations flag.
969     DiagnoseObjCImplementedDeprecations(*this,
970                                         dyn_cast<NamedDecl>(IDecl),
971                                         IMPDecl->getLocation(), 1);
972   }
973   return ActOnObjCContainerStartDefinition(IMPDecl);
974 }
975 
976 void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
977                                     ObjCIvarDecl **ivars, unsigned numIvars,
978                                     SourceLocation RBrace) {
979   assert(ImpDecl && "missing implementation decl");
980   ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
981   if (!IDecl)
982     return;
983   /// Check case of non-existing @interface decl.
984   /// (legacy objective-c @implementation decl without an @interface decl).
985   /// Add implementations's ivar to the synthesize class's ivar list.
986   if (IDecl->isImplicitInterfaceDecl()) {
987     IDecl->setLocEnd(RBrace);
988     // Add ivar's to class's DeclContext.
989     for (unsigned i = 0, e = numIvars; i != e; ++i) {
990       ivars[i]->setLexicalDeclContext(ImpDecl);
991       IDecl->makeDeclVisibleInContext(ivars[i], false);
992       ImpDecl->addDecl(ivars[i]);
993     }
994 
995     return;
996   }
997   // If implementation has empty ivar list, just return.
998   if (numIvars == 0)
999     return;
1000 
1001   assert(ivars && "missing @implementation ivars");
1002   if (LangOpts.ObjCNonFragileABI2) {
1003     if (ImpDecl->getSuperClass())
1004       Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
1005     for (unsigned i = 0; i < numIvars; i++) {
1006       ObjCIvarDecl* ImplIvar = ivars[i];
1007       if (const ObjCIvarDecl *ClsIvar =
1008             IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
1009         Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
1010         Diag(ClsIvar->getLocation(), diag::note_previous_definition);
1011         continue;
1012       }
1013       // Instance ivar to Implementation's DeclContext.
1014       ImplIvar->setLexicalDeclContext(ImpDecl);
1015       IDecl->makeDeclVisibleInContext(ImplIvar, false);
1016       ImpDecl->addDecl(ImplIvar);
1017     }
1018     return;
1019   }
1020   // Check interface's Ivar list against those in the implementation.
1021   // names and types must match.
1022   //
1023   unsigned j = 0;
1024   ObjCInterfaceDecl::ivar_iterator
1025     IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
1026   for (; numIvars > 0 && IVI != IVE; ++IVI) {
1027     ObjCIvarDecl* ImplIvar = ivars[j++];
1028     ObjCIvarDecl* ClsIvar = *IVI;
1029     assert (ImplIvar && "missing implementation ivar");
1030     assert (ClsIvar && "missing class ivar");
1031 
1032     // First, make sure the types match.
1033     if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) {
1034       Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
1035         << ImplIvar->getIdentifier()
1036         << ImplIvar->getType() << ClsIvar->getType();
1037       Diag(ClsIvar->getLocation(), diag::note_previous_definition);
1038     } else if (ImplIvar->isBitField() && ClsIvar->isBitField() &&
1039                ImplIvar->getBitWidthValue(Context) !=
1040                ClsIvar->getBitWidthValue(Context)) {
1041       Diag(ImplIvar->getBitWidth()->getLocStart(),
1042            diag::err_conflicting_ivar_bitwidth) << ImplIvar->getIdentifier();
1043       Diag(ClsIvar->getBitWidth()->getLocStart(),
1044            diag::note_previous_definition);
1045     }
1046     // Make sure the names are identical.
1047     if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
1048       Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
1049         << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
1050       Diag(ClsIvar->getLocation(), diag::note_previous_definition);
1051     }
1052     --numIvars;
1053   }
1054 
1055   if (numIvars > 0)
1056     Diag(ivars[j]->getLocation(), diag::err_inconsistant_ivar_count);
1057   else if (IVI != IVE)
1058     Diag((*IVI)->getLocation(), diag::err_inconsistant_ivar_count);
1059 }
1060 
1061 void Sema::WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method,
1062                                bool &IncompleteImpl, unsigned DiagID) {
1063   // No point warning no definition of method which is 'unavailable'.
1064   if (method->hasAttr<UnavailableAttr>())
1065     return;
1066   if (!IncompleteImpl) {
1067     Diag(ImpLoc, diag::warn_incomplete_impl);
1068     IncompleteImpl = true;
1069   }
1070   if (DiagID == diag::warn_unimplemented_protocol_method)
1071     Diag(ImpLoc, DiagID) << method->getDeclName();
1072   else
1073     Diag(method->getLocation(), DiagID) << method->getDeclName();
1074 }
1075 
1076 /// Determines if type B can be substituted for type A.  Returns true if we can
1077 /// guarantee that anything that the user will do to an object of type A can
1078 /// also be done to an object of type B.  This is trivially true if the two
1079 /// types are the same, or if B is a subclass of A.  It becomes more complex
1080 /// in cases where protocols are involved.
1081 ///
1082 /// Object types in Objective-C describe the minimum requirements for an
1083 /// object, rather than providing a complete description of a type.  For
1084 /// example, if A is a subclass of B, then B* may refer to an instance of A.
1085 /// The principle of substitutability means that we may use an instance of A
1086 /// anywhere that we may use an instance of B - it will implement all of the
1087 /// ivars of B and all of the methods of B.
1088 ///
1089 /// This substitutability is important when type checking methods, because
1090 /// the implementation may have stricter type definitions than the interface.
1091 /// The interface specifies minimum requirements, but the implementation may
1092 /// have more accurate ones.  For example, a method may privately accept
1093 /// instances of B, but only publish that it accepts instances of A.  Any
1094 /// object passed to it will be type checked against B, and so will implicitly
1095 /// by a valid A*.  Similarly, a method may return a subclass of the class that
1096 /// it is declared as returning.
1097 ///
1098 /// This is most important when considering subclassing.  A method in a
1099 /// subclass must accept any object as an argument that its superclass's
1100 /// implementation accepts.  It may, however, accept a more general type
1101 /// without breaking substitutability (i.e. you can still use the subclass
1102 /// anywhere that you can use the superclass, but not vice versa).  The
1103 /// converse requirement applies to return types: the return type for a
1104 /// subclass method must be a valid object of the kind that the superclass
1105 /// advertises, but it may be specified more accurately.  This avoids the need
1106 /// for explicit down-casting by callers.
1107 ///
1108 /// Note: This is a stricter requirement than for assignment.
1109 static bool isObjCTypeSubstitutable(ASTContext &Context,
1110                                     const ObjCObjectPointerType *A,
1111                                     const ObjCObjectPointerType *B,
1112                                     bool rejectId) {
1113   // Reject a protocol-unqualified id.
1114   if (rejectId && B->isObjCIdType()) return false;
1115 
1116   // If B is a qualified id, then A must also be a qualified id and it must
1117   // implement all of the protocols in B.  It may not be a qualified class.
1118   // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
1119   // stricter definition so it is not substitutable for id<A>.
1120   if (B->isObjCQualifiedIdType()) {
1121     return A->isObjCQualifiedIdType() &&
1122            Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0),
1123                                                      QualType(B,0),
1124                                                      false);
1125   }
1126 
1127   /*
1128   // id is a special type that bypasses type checking completely.  We want a
1129   // warning when it is used in one place but not another.
1130   if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
1131 
1132 
1133   // If B is a qualified id, then A must also be a qualified id (which it isn't
1134   // if we've got this far)
1135   if (B->isObjCQualifiedIdType()) return false;
1136   */
1137 
1138   // Now we know that A and B are (potentially-qualified) class types.  The
1139   // normal rules for assignment apply.
1140   return Context.canAssignObjCInterfaces(A, B);
1141 }
1142 
1143 static SourceRange getTypeRange(TypeSourceInfo *TSI) {
1144   return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
1145 }
1146 
1147 static bool CheckMethodOverrideReturn(Sema &S,
1148                                       ObjCMethodDecl *MethodImpl,
1149                                       ObjCMethodDecl *MethodDecl,
1150                                       bool IsProtocolMethodDecl,
1151                                       bool IsOverridingMode,
1152                                       bool Warn) {
1153   if (IsProtocolMethodDecl &&
1154       (MethodDecl->getObjCDeclQualifier() !=
1155        MethodImpl->getObjCDeclQualifier())) {
1156     if (Warn) {
1157         S.Diag(MethodImpl->getLocation(),
1158                (IsOverridingMode ?
1159                  diag::warn_conflicting_overriding_ret_type_modifiers
1160                  : diag::warn_conflicting_ret_type_modifiers))
1161           << MethodImpl->getDeclName()
1162           << getTypeRange(MethodImpl->getResultTypeSourceInfo());
1163         S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
1164           << getTypeRange(MethodDecl->getResultTypeSourceInfo());
1165     }
1166     else
1167       return false;
1168   }
1169 
1170   if (S.Context.hasSameUnqualifiedType(MethodImpl->getResultType(),
1171                                        MethodDecl->getResultType()))
1172     return true;
1173   if (!Warn)
1174     return false;
1175 
1176   unsigned DiagID =
1177     IsOverridingMode ? diag::warn_conflicting_overriding_ret_types
1178                      : diag::warn_conflicting_ret_types;
1179 
1180   // Mismatches between ObjC pointers go into a different warning
1181   // category, and sometimes they're even completely whitelisted.
1182   if (const ObjCObjectPointerType *ImplPtrTy =
1183         MethodImpl->getResultType()->getAs<ObjCObjectPointerType>()) {
1184     if (const ObjCObjectPointerType *IfacePtrTy =
1185           MethodDecl->getResultType()->getAs<ObjCObjectPointerType>()) {
1186       // Allow non-matching return types as long as they don't violate
1187       // the principle of substitutability.  Specifically, we permit
1188       // return types that are subclasses of the declared return type,
1189       // or that are more-qualified versions of the declared type.
1190       if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
1191         return false;
1192 
1193       DiagID =
1194         IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types
1195                           : diag::warn_non_covariant_ret_types;
1196     }
1197   }
1198 
1199   S.Diag(MethodImpl->getLocation(), DiagID)
1200     << MethodImpl->getDeclName()
1201     << MethodDecl->getResultType()
1202     << MethodImpl->getResultType()
1203     << getTypeRange(MethodImpl->getResultTypeSourceInfo());
1204   S.Diag(MethodDecl->getLocation(),
1205          IsOverridingMode ? diag::note_previous_declaration
1206                           : diag::note_previous_definition)
1207     << getTypeRange(MethodDecl->getResultTypeSourceInfo());
1208   return false;
1209 }
1210 
1211 static bool CheckMethodOverrideParam(Sema &S,
1212                                      ObjCMethodDecl *MethodImpl,
1213                                      ObjCMethodDecl *MethodDecl,
1214                                      ParmVarDecl *ImplVar,
1215                                      ParmVarDecl *IfaceVar,
1216                                      bool IsProtocolMethodDecl,
1217                                      bool IsOverridingMode,
1218                                      bool Warn) {
1219   if (IsProtocolMethodDecl &&
1220       (ImplVar->getObjCDeclQualifier() !=
1221        IfaceVar->getObjCDeclQualifier())) {
1222     if (Warn) {
1223       if (IsOverridingMode)
1224         S.Diag(ImplVar->getLocation(),
1225                diag::warn_conflicting_overriding_param_modifiers)
1226             << getTypeRange(ImplVar->getTypeSourceInfo())
1227             << MethodImpl->getDeclName();
1228       else S.Diag(ImplVar->getLocation(),
1229              diag::warn_conflicting_param_modifiers)
1230           << getTypeRange(ImplVar->getTypeSourceInfo())
1231           << MethodImpl->getDeclName();
1232       S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
1233           << getTypeRange(IfaceVar->getTypeSourceInfo());
1234     }
1235     else
1236       return false;
1237   }
1238 
1239   QualType ImplTy = ImplVar->getType();
1240   QualType IfaceTy = IfaceVar->getType();
1241 
1242   if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
1243     return true;
1244 
1245   if (!Warn)
1246     return false;
1247   unsigned DiagID =
1248     IsOverridingMode ? diag::warn_conflicting_overriding_param_types
1249                      : diag::warn_conflicting_param_types;
1250 
1251   // Mismatches between ObjC pointers go into a different warning
1252   // category, and sometimes they're even completely whitelisted.
1253   if (const ObjCObjectPointerType *ImplPtrTy =
1254         ImplTy->getAs<ObjCObjectPointerType>()) {
1255     if (const ObjCObjectPointerType *IfacePtrTy =
1256           IfaceTy->getAs<ObjCObjectPointerType>()) {
1257       // Allow non-matching argument types as long as they don't
1258       // violate the principle of substitutability.  Specifically, the
1259       // implementation must accept any objects that the superclass
1260       // accepts, however it may also accept others.
1261       if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
1262         return false;
1263 
1264       DiagID =
1265       IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types
1266                        :  diag::warn_non_contravariant_param_types;
1267     }
1268   }
1269 
1270   S.Diag(ImplVar->getLocation(), DiagID)
1271     << getTypeRange(ImplVar->getTypeSourceInfo())
1272     << MethodImpl->getDeclName() << IfaceTy << ImplTy;
1273   S.Diag(IfaceVar->getLocation(),
1274          (IsOverridingMode ? diag::note_previous_declaration
1275                         : diag::note_previous_definition))
1276     << getTypeRange(IfaceVar->getTypeSourceInfo());
1277   return false;
1278 }
1279 
1280 /// In ARC, check whether the conventional meanings of the two methods
1281 /// match.  If they don't, it's a hard error.
1282 static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
1283                                       ObjCMethodDecl *decl) {
1284   ObjCMethodFamily implFamily = impl->getMethodFamily();
1285   ObjCMethodFamily declFamily = decl->getMethodFamily();
1286   if (implFamily == declFamily) return false;
1287 
1288   // Since conventions are sorted by selector, the only possibility is
1289   // that the types differ enough to cause one selector or the other
1290   // to fall out of the family.
1291   assert(implFamily == OMF_None || declFamily == OMF_None);
1292 
1293   // No further diagnostics required on invalid declarations.
1294   if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
1295 
1296   const ObjCMethodDecl *unmatched = impl;
1297   ObjCMethodFamily family = declFamily;
1298   unsigned errorID = diag::err_arc_lost_method_convention;
1299   unsigned noteID = diag::note_arc_lost_method_convention;
1300   if (declFamily == OMF_None) {
1301     unmatched = decl;
1302     family = implFamily;
1303     errorID = diag::err_arc_gained_method_convention;
1304     noteID = diag::note_arc_gained_method_convention;
1305   }
1306 
1307   // Indexes into a %select clause in the diagnostic.
1308   enum FamilySelector {
1309     F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
1310   };
1311   FamilySelector familySelector = FamilySelector();
1312 
1313   switch (family) {
1314   case OMF_None: llvm_unreachable("logic error, no method convention");
1315   case OMF_retain:
1316   case OMF_release:
1317   case OMF_autorelease:
1318   case OMF_dealloc:
1319   case OMF_finalize:
1320   case OMF_retainCount:
1321   case OMF_self:
1322   case OMF_performSelector:
1323     // Mismatches for these methods don't change ownership
1324     // conventions, so we don't care.
1325     return false;
1326 
1327   case OMF_init: familySelector = F_init; break;
1328   case OMF_alloc: familySelector = F_alloc; break;
1329   case OMF_copy: familySelector = F_copy; break;
1330   case OMF_mutableCopy: familySelector = F_mutableCopy; break;
1331   case OMF_new: familySelector = F_new; break;
1332   }
1333 
1334   enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
1335   ReasonSelector reasonSelector;
1336 
1337   // The only reason these methods don't fall within their families is
1338   // due to unusual result types.
1339   if (unmatched->getResultType()->isObjCObjectPointerType()) {
1340     reasonSelector = R_UnrelatedReturn;
1341   } else {
1342     reasonSelector = R_NonObjectReturn;
1343   }
1344 
1345   S.Diag(impl->getLocation(), errorID) << familySelector << reasonSelector;
1346   S.Diag(decl->getLocation(), noteID) << familySelector << reasonSelector;
1347 
1348   return true;
1349 }
1350 
1351 void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
1352                                        ObjCMethodDecl *MethodDecl,
1353                                        bool IsProtocolMethodDecl) {
1354   if (getLangOptions().ObjCAutoRefCount &&
1355       checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
1356     return;
1357 
1358   CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
1359                             IsProtocolMethodDecl, false,
1360                             true);
1361 
1362   for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
1363        IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end();
1364        IM != EM; ++IM, ++IF) {
1365     CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
1366                              IsProtocolMethodDecl, false, true);
1367   }
1368 
1369   if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
1370     Diag(ImpMethodDecl->getLocation(),
1371          diag::warn_conflicting_variadic);
1372     Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
1373   }
1374 }
1375 
1376 void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
1377                                        ObjCMethodDecl *Overridden,
1378                                        bool IsProtocolMethodDecl) {
1379 
1380   CheckMethodOverrideReturn(*this, Method, Overridden,
1381                             IsProtocolMethodDecl, true,
1382                             true);
1383 
1384   for (ObjCMethodDecl::param_iterator IM = Method->param_begin(),
1385        IF = Overridden->param_begin(), EM = Method->param_end();
1386        IM != EM; ++IM, ++IF) {
1387     CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF,
1388                              IsProtocolMethodDecl, true, true);
1389   }
1390 
1391   if (Method->isVariadic() != Overridden->isVariadic()) {
1392     Diag(Method->getLocation(),
1393          diag::warn_conflicting_overriding_variadic);
1394     Diag(Overridden->getLocation(), diag::note_previous_declaration);
1395   }
1396 }
1397 
1398 /// WarnExactTypedMethods - This routine issues a warning if method
1399 /// implementation declaration matches exactly that of its declaration.
1400 void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
1401                                  ObjCMethodDecl *MethodDecl,
1402                                  bool IsProtocolMethodDecl) {
1403   // don't issue warning when protocol method is optional because primary
1404   // class is not required to implement it and it is safe for protocol
1405   // to implement it.
1406   if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional)
1407     return;
1408   // don't issue warning when primary class's method is
1409   // depecated/unavailable.
1410   if (MethodDecl->hasAttr<UnavailableAttr>() ||
1411       MethodDecl->hasAttr<DeprecatedAttr>())
1412     return;
1413 
1414   bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
1415                                       IsProtocolMethodDecl, false, false);
1416   if (match)
1417     for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
1418          IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end();
1419          IM != EM; ++IM, ++IF) {
1420       match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl,
1421                                        *IM, *IF,
1422                                        IsProtocolMethodDecl, false, false);
1423       if (!match)
1424         break;
1425     }
1426   if (match)
1427     match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
1428   if (match)
1429     match = !(MethodDecl->isClassMethod() &&
1430               MethodDecl->getSelector() == GetNullarySelector("load", Context));
1431 
1432   if (match) {
1433     Diag(ImpMethodDecl->getLocation(),
1434          diag::warn_category_method_impl_match);
1435     Diag(MethodDecl->getLocation(), diag::note_method_declared_at);
1436   }
1437 }
1438 
1439 /// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
1440 /// improve the efficiency of selector lookups and type checking by associating
1441 /// with each protocol / interface / category the flattened instance tables. If
1442 /// we used an immutable set to keep the table then it wouldn't add significant
1443 /// memory cost and it would be handy for lookups.
1444 
1445 /// CheckProtocolMethodDefs - This routine checks unimplemented methods
1446 /// Declared in protocol, and those referenced by it.
1447 void Sema::CheckProtocolMethodDefs(SourceLocation ImpLoc,
1448                                    ObjCProtocolDecl *PDecl,
1449                                    bool& IncompleteImpl,
1450                                    const llvm::DenseSet<Selector> &InsMap,
1451                                    const llvm::DenseSet<Selector> &ClsMap,
1452                                    ObjCContainerDecl *CDecl) {
1453   ObjCInterfaceDecl *IDecl;
1454   if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl))
1455     IDecl = C->getClassInterface();
1456   else
1457     IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
1458   assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
1459 
1460   ObjCInterfaceDecl *Super = IDecl->getSuperClass();
1461   ObjCInterfaceDecl *NSIDecl = 0;
1462   if (getLangOptions().NeXTRuntime) {
1463     // check to see if class implements forwardInvocation method and objects
1464     // of this class are derived from 'NSProxy' so that to forward requests
1465     // from one object to another.
1466     // Under such conditions, which means that every method possible is
1467     // implemented in the class, we should not issue "Method definition not
1468     // found" warnings.
1469     // FIXME: Use a general GetUnarySelector method for this.
1470     IdentifierInfo* II = &Context.Idents.get("forwardInvocation");
1471     Selector fISelector = Context.Selectors.getSelector(1, &II);
1472     if (InsMap.count(fISelector))
1473       // Is IDecl derived from 'NSProxy'? If so, no instance methods
1474       // need be implemented in the implementation.
1475       NSIDecl = IDecl->lookupInheritedClass(&Context.Idents.get("NSProxy"));
1476   }
1477 
1478   // If a method lookup fails locally we still need to look and see if
1479   // the method was implemented by a base class or an inherited
1480   // protocol. This lookup is slow, but occurs rarely in correct code
1481   // and otherwise would terminate in a warning.
1482 
1483   // check unimplemented instance methods.
1484   if (!NSIDecl)
1485     for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
1486          E = PDecl->instmeth_end(); I != E; ++I) {
1487       ObjCMethodDecl *method = *I;
1488       if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
1489           !method->isSynthesized() && !InsMap.count(method->getSelector()) &&
1490           (!Super ||
1491            !Super->lookupInstanceMethod(method->getSelector()))) {
1492             // Ugly, but necessary. Method declared in protcol might have
1493             // have been synthesized due to a property declared in the class which
1494             // uses the protocol.
1495             ObjCMethodDecl *MethodInClass =
1496             IDecl->lookupInstanceMethod(method->getSelector());
1497             if (!MethodInClass || !MethodInClass->isSynthesized()) {
1498               unsigned DIAG = diag::warn_unimplemented_protocol_method;
1499               if (Diags.getDiagnosticLevel(DIAG, ImpLoc)
1500                       != DiagnosticsEngine::Ignored) {
1501                 WarnUndefinedMethod(ImpLoc, method, IncompleteImpl, DIAG);
1502                 Diag(method->getLocation(), diag::note_method_declared_at);
1503                 Diag(CDecl->getLocation(), diag::note_required_for_protocol_at)
1504                   << PDecl->getDeclName();
1505               }
1506             }
1507           }
1508     }
1509   // check unimplemented class methods
1510   for (ObjCProtocolDecl::classmeth_iterator
1511          I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1512        I != E; ++I) {
1513     ObjCMethodDecl *method = *I;
1514     if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
1515         !ClsMap.count(method->getSelector()) &&
1516         (!Super || !Super->lookupClassMethod(method->getSelector()))) {
1517       unsigned DIAG = diag::warn_unimplemented_protocol_method;
1518       if (Diags.getDiagnosticLevel(DIAG, ImpLoc) !=
1519             DiagnosticsEngine::Ignored) {
1520         WarnUndefinedMethod(ImpLoc, method, IncompleteImpl, DIAG);
1521         Diag(method->getLocation(), diag::note_method_declared_at);
1522         Diag(IDecl->getLocation(), diag::note_required_for_protocol_at) <<
1523           PDecl->getDeclName();
1524       }
1525     }
1526   }
1527   // Check on this protocols's referenced protocols, recursively.
1528   for (ObjCProtocolDecl::protocol_iterator PI = PDecl->protocol_begin(),
1529        E = PDecl->protocol_end(); PI != E; ++PI)
1530     CheckProtocolMethodDefs(ImpLoc, *PI, IncompleteImpl, InsMap, ClsMap, IDecl);
1531 }
1532 
1533 /// MatchAllMethodDeclarations - Check methods declared in interface
1534 /// or protocol against those declared in their implementations.
1535 ///
1536 void Sema::MatchAllMethodDeclarations(const llvm::DenseSet<Selector> &InsMap,
1537                                       const llvm::DenseSet<Selector> &ClsMap,
1538                                       llvm::DenseSet<Selector> &InsMapSeen,
1539                                       llvm::DenseSet<Selector> &ClsMapSeen,
1540                                       ObjCImplDecl* IMPDecl,
1541                                       ObjCContainerDecl* CDecl,
1542                                       bool &IncompleteImpl,
1543                                       bool ImmediateClass,
1544                                       bool WarnExactMatch) {
1545   // Check and see if instance methods in class interface have been
1546   // implemented in the implementation class. If so, their types match.
1547   for (ObjCInterfaceDecl::instmeth_iterator I = CDecl->instmeth_begin(),
1548        E = CDecl->instmeth_end(); I != E; ++I) {
1549     if (InsMapSeen.count((*I)->getSelector()))
1550         continue;
1551     InsMapSeen.insert((*I)->getSelector());
1552     if (!(*I)->isSynthesized() &&
1553         !InsMap.count((*I)->getSelector())) {
1554       if (ImmediateClass)
1555         WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl,
1556                             diag::note_undef_method_impl);
1557       continue;
1558     } else {
1559       ObjCMethodDecl *ImpMethodDecl =
1560         IMPDecl->getInstanceMethod((*I)->getSelector());
1561       assert(CDecl->getInstanceMethod((*I)->getSelector()) &&
1562              "Expected to find the method through lookup as well");
1563       ObjCMethodDecl *MethodDecl = *I;
1564       // ImpMethodDecl may be null as in a @dynamic property.
1565       if (ImpMethodDecl) {
1566         if (!WarnExactMatch)
1567           WarnConflictingTypedMethods(ImpMethodDecl, MethodDecl,
1568                                       isa<ObjCProtocolDecl>(CDecl));
1569         else if (!MethodDecl->isSynthesized())
1570           WarnExactTypedMethods(ImpMethodDecl, MethodDecl,
1571                                isa<ObjCProtocolDecl>(CDecl));
1572       }
1573     }
1574   }
1575 
1576   // Check and see if class methods in class interface have been
1577   // implemented in the implementation class. If so, their types match.
1578    for (ObjCInterfaceDecl::classmeth_iterator
1579        I = CDecl->classmeth_begin(), E = CDecl->classmeth_end(); I != E; ++I) {
1580      if (ClsMapSeen.count((*I)->getSelector()))
1581        continue;
1582      ClsMapSeen.insert((*I)->getSelector());
1583     if (!ClsMap.count((*I)->getSelector())) {
1584       if (ImmediateClass)
1585         WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl,
1586                             diag::note_undef_method_impl);
1587     } else {
1588       ObjCMethodDecl *ImpMethodDecl =
1589         IMPDecl->getClassMethod((*I)->getSelector());
1590       assert(CDecl->getClassMethod((*I)->getSelector()) &&
1591              "Expected to find the method through lookup as well");
1592       ObjCMethodDecl *MethodDecl = *I;
1593       if (!WarnExactMatch)
1594         WarnConflictingTypedMethods(ImpMethodDecl, MethodDecl,
1595                                     isa<ObjCProtocolDecl>(CDecl));
1596       else
1597         WarnExactTypedMethods(ImpMethodDecl, MethodDecl,
1598                              isa<ObjCProtocolDecl>(CDecl));
1599     }
1600   }
1601 
1602   if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
1603     // Also methods in class extensions need be looked at next.
1604     for (const ObjCCategoryDecl *ClsExtDecl = I->getFirstClassExtension();
1605          ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension())
1606       MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1607                                  IMPDecl,
1608                                  const_cast<ObjCCategoryDecl *>(ClsExtDecl),
1609                                  IncompleteImpl, false, WarnExactMatch);
1610 
1611     // Check for any implementation of a methods declared in protocol.
1612     for (ObjCInterfaceDecl::all_protocol_iterator
1613           PI = I->all_referenced_protocol_begin(),
1614           E = I->all_referenced_protocol_end(); PI != E; ++PI)
1615       MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1616                                  IMPDecl,
1617                                  (*PI), IncompleteImpl, false, WarnExactMatch);
1618 
1619     // FIXME. For now, we are not checking for extact match of methods
1620     // in category implementation and its primary class's super class.
1621     if (!WarnExactMatch && I->getSuperClass())
1622       MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1623                                  IMPDecl,
1624                                  I->getSuperClass(), IncompleteImpl, false);
1625   }
1626 }
1627 
1628 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
1629 /// category matches with those implemented in its primary class and
1630 /// warns each time an exact match is found.
1631 void Sema::CheckCategoryVsClassMethodMatches(
1632                                   ObjCCategoryImplDecl *CatIMPDecl) {
1633   llvm::DenseSet<Selector> InsMap, ClsMap;
1634 
1635   for (ObjCImplementationDecl::instmeth_iterator
1636        I = CatIMPDecl->instmeth_begin(),
1637        E = CatIMPDecl->instmeth_end(); I!=E; ++I)
1638     InsMap.insert((*I)->getSelector());
1639 
1640   for (ObjCImplementationDecl::classmeth_iterator
1641        I = CatIMPDecl->classmeth_begin(),
1642        E = CatIMPDecl->classmeth_end(); I != E; ++I)
1643     ClsMap.insert((*I)->getSelector());
1644   if (InsMap.empty() && ClsMap.empty())
1645     return;
1646 
1647   // Get category's primary class.
1648   ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
1649   if (!CatDecl)
1650     return;
1651   ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
1652   if (!IDecl)
1653     return;
1654   llvm::DenseSet<Selector> InsMapSeen, ClsMapSeen;
1655   bool IncompleteImpl = false;
1656   MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1657                              CatIMPDecl, IDecl,
1658                              IncompleteImpl, false, true /*WarnExactMatch*/);
1659 }
1660 
1661 void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
1662                                      ObjCContainerDecl* CDecl,
1663                                      bool IncompleteImpl) {
1664   llvm::DenseSet<Selector> InsMap;
1665   // Check and see if instance methods in class interface have been
1666   // implemented in the implementation class.
1667   for (ObjCImplementationDecl::instmeth_iterator
1668          I = IMPDecl->instmeth_begin(), E = IMPDecl->instmeth_end(); I!=E; ++I)
1669     InsMap.insert((*I)->getSelector());
1670 
1671   // Check and see if properties declared in the interface have either 1)
1672   // an implementation or 2) there is a @synthesize/@dynamic implementation
1673   // of the property in the @implementation.
1674   if (isa<ObjCInterfaceDecl>(CDecl) &&
1675         !(LangOpts.ObjCDefaultSynthProperties && LangOpts.ObjCNonFragileABI2))
1676     DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, InsMap);
1677 
1678   llvm::DenseSet<Selector> ClsMap;
1679   for (ObjCImplementationDecl::classmeth_iterator
1680        I = IMPDecl->classmeth_begin(),
1681        E = IMPDecl->classmeth_end(); I != E; ++I)
1682     ClsMap.insert((*I)->getSelector());
1683 
1684   // Check for type conflict of methods declared in a class/protocol and
1685   // its implementation; if any.
1686   llvm::DenseSet<Selector> InsMapSeen, ClsMapSeen;
1687   MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1688                              IMPDecl, CDecl,
1689                              IncompleteImpl, true);
1690 
1691   // check all methods implemented in category against those declared
1692   // in its primary class.
1693   if (ObjCCategoryImplDecl *CatDecl =
1694         dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
1695     CheckCategoryVsClassMethodMatches(CatDecl);
1696 
1697   // Check the protocol list for unimplemented methods in the @implementation
1698   // class.
1699   // Check and see if class methods in class interface have been
1700   // implemented in the implementation class.
1701 
1702   if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
1703     for (ObjCInterfaceDecl::all_protocol_iterator
1704           PI = I->all_referenced_protocol_begin(),
1705           E = I->all_referenced_protocol_end(); PI != E; ++PI)
1706       CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl,
1707                               InsMap, ClsMap, I);
1708     // Check class extensions (unnamed categories)
1709     for (const ObjCCategoryDecl *Categories = I->getFirstClassExtension();
1710          Categories; Categories = Categories->getNextClassExtension())
1711       ImplMethodsVsClassMethods(S, IMPDecl,
1712                                 const_cast<ObjCCategoryDecl*>(Categories),
1713                                 IncompleteImpl);
1714   } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1715     // For extended class, unimplemented methods in its protocols will
1716     // be reported in the primary class.
1717     if (!C->IsClassExtension()) {
1718       for (ObjCCategoryDecl::protocol_iterator PI = C->protocol_begin(),
1719            E = C->protocol_end(); PI != E; ++PI)
1720         CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl,
1721                                 InsMap, ClsMap, CDecl);
1722       // Report unimplemented properties in the category as well.
1723       // When reporting on missing setter/getters, do not report when
1724       // setter/getter is implemented in category's primary class
1725       // implementation.
1726       if (ObjCInterfaceDecl *ID = C->getClassInterface())
1727         if (ObjCImplDecl *IMP = ID->getImplementation()) {
1728           for (ObjCImplementationDecl::instmeth_iterator
1729                I = IMP->instmeth_begin(), E = IMP->instmeth_end(); I!=E; ++I)
1730             InsMap.insert((*I)->getSelector());
1731         }
1732       DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, InsMap);
1733     }
1734   } else
1735     llvm_unreachable("invalid ObjCContainerDecl type.");
1736 }
1737 
1738 /// ActOnForwardClassDeclaration -
1739 Sema::DeclGroupPtrTy
1740 Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
1741                                    IdentifierInfo **IdentList,
1742                                    SourceLocation *IdentLocs,
1743                                    unsigned NumElts) {
1744   SmallVector<Decl *, 8> DeclsInGroup;
1745   for (unsigned i = 0; i != NumElts; ++i) {
1746     // Check for another declaration kind with the same name.
1747     NamedDecl *PrevDecl
1748       = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
1749                          LookupOrdinaryName, ForRedeclaration);
1750     if (PrevDecl && PrevDecl->isTemplateParameter()) {
1751       // Maybe we will complain about the shadowed template parameter.
1752       DiagnoseTemplateParameterShadow(AtClassLoc, PrevDecl);
1753       // Just pretend that we didn't see the previous declaration.
1754       PrevDecl = 0;
1755     }
1756 
1757     if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
1758       // GCC apparently allows the following idiom:
1759       //
1760       // typedef NSObject < XCElementTogglerP > XCElementToggler;
1761       // @class XCElementToggler;
1762       //
1763       // FIXME: Make an extension?
1764       TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
1765       if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
1766         Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
1767         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1768       } else {
1769         // a forward class declaration matching a typedef name of a class refers
1770         // to the underlying class.
1771         if (const ObjCObjectType *OI =
1772               TDD->getUnderlyingType()->getAs<ObjCObjectType>())
1773           PrevDecl = OI->getInterface();
1774       }
1775     }
1776     ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
1777     if (!IDecl) {  // Not already seen?  Make a forward decl.
1778       IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
1779                                         IdentList[i], IdentLocs[i], true);
1780 
1781       // Push the ObjCInterfaceDecl on the scope chain but do *not* add it to
1782       // the current DeclContext.  This prevents clients that walk DeclContext
1783       // from seeing the imaginary ObjCInterfaceDecl until it is actually
1784       // declared later (if at all).  We also take care to explicitly make
1785       // sure this declaration is visible for name lookup.
1786       PushOnScopeChains(IDecl, TUScope, false);
1787       CurContext->makeDeclVisibleInContext(IDecl, true);
1788     }
1789     ObjCClassDecl *CDecl = ObjCClassDecl::Create(Context, CurContext, AtClassLoc,
1790                                                  IDecl, IdentLocs[i]);
1791     CurContext->addDecl(CDecl);
1792     CheckObjCDeclScope(CDecl);
1793     DeclsInGroup.push_back(CDecl);
1794   }
1795 
1796   return BuildDeclaratorGroup(DeclsInGroup.data(), DeclsInGroup.size(), false);
1797 }
1798 
1799 static bool tryMatchRecordTypes(ASTContext &Context,
1800                                 Sema::MethodMatchStrategy strategy,
1801                                 const Type *left, const Type *right);
1802 
1803 static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
1804                        QualType leftQT, QualType rightQT) {
1805   const Type *left =
1806     Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
1807   const Type *right =
1808     Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
1809 
1810   if (left == right) return true;
1811 
1812   // If we're doing a strict match, the types have to match exactly.
1813   if (strategy == Sema::MMS_strict) return false;
1814 
1815   if (left->isIncompleteType() || right->isIncompleteType()) return false;
1816 
1817   // Otherwise, use this absurdly complicated algorithm to try to
1818   // validate the basic, low-level compatibility of the two types.
1819 
1820   // As a minimum, require the sizes and alignments to match.
1821   if (Context.getTypeInfo(left) != Context.getTypeInfo(right))
1822     return false;
1823 
1824   // Consider all the kinds of non-dependent canonical types:
1825   // - functions and arrays aren't possible as return and parameter types
1826 
1827   // - vector types of equal size can be arbitrarily mixed
1828   if (isa<VectorType>(left)) return isa<VectorType>(right);
1829   if (isa<VectorType>(right)) return false;
1830 
1831   // - references should only match references of identical type
1832   // - structs, unions, and Objective-C objects must match more-or-less
1833   //   exactly
1834   // - everything else should be a scalar
1835   if (!left->isScalarType() || !right->isScalarType())
1836     return tryMatchRecordTypes(Context, strategy, left, right);
1837 
1838   // Make scalars agree in kind, except count bools as chars, and group
1839   // all non-member pointers together.
1840   Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
1841   Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
1842   if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
1843   if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
1844   if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
1845     leftSK = Type::STK_ObjCObjectPointer;
1846   if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
1847     rightSK = Type::STK_ObjCObjectPointer;
1848 
1849   // Note that data member pointers and function member pointers don't
1850   // intermix because of the size differences.
1851 
1852   return (leftSK == rightSK);
1853 }
1854 
1855 static bool tryMatchRecordTypes(ASTContext &Context,
1856                                 Sema::MethodMatchStrategy strategy,
1857                                 const Type *lt, const Type *rt) {
1858   assert(lt && rt && lt != rt);
1859 
1860   if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
1861   RecordDecl *left = cast<RecordType>(lt)->getDecl();
1862   RecordDecl *right = cast<RecordType>(rt)->getDecl();
1863 
1864   // Require union-hood to match.
1865   if (left->isUnion() != right->isUnion()) return false;
1866 
1867   // Require an exact match if either is non-POD.
1868   if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
1869       (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
1870     return false;
1871 
1872   // Require size and alignment to match.
1873   if (Context.getTypeInfo(lt) != Context.getTypeInfo(rt)) return false;
1874 
1875   // Require fields to match.
1876   RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
1877   RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
1878   for (; li != le && ri != re; ++li, ++ri) {
1879     if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
1880       return false;
1881   }
1882   return (li == le && ri == re);
1883 }
1884 
1885 /// MatchTwoMethodDeclarations - Checks that two methods have matching type and
1886 /// returns true, or false, accordingly.
1887 /// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
1888 bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
1889                                       const ObjCMethodDecl *right,
1890                                       MethodMatchStrategy strategy) {
1891   if (!matchTypes(Context, strategy,
1892                   left->getResultType(), right->getResultType()))
1893     return false;
1894 
1895   if (getLangOptions().ObjCAutoRefCount &&
1896       (left->hasAttr<NSReturnsRetainedAttr>()
1897          != right->hasAttr<NSReturnsRetainedAttr>() ||
1898        left->hasAttr<NSConsumesSelfAttr>()
1899          != right->hasAttr<NSConsumesSelfAttr>()))
1900     return false;
1901 
1902   ObjCMethodDecl::param_const_iterator
1903     li = left->param_begin(), le = left->param_end(), ri = right->param_begin();
1904 
1905   for (; li != le; ++li, ++ri) {
1906     assert(ri != right->param_end() && "Param mismatch");
1907     const ParmVarDecl *lparm = *li, *rparm = *ri;
1908 
1909     if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
1910       return false;
1911 
1912     if (getLangOptions().ObjCAutoRefCount &&
1913         lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
1914       return false;
1915   }
1916   return true;
1917 }
1918 
1919 /// \brief Read the contents of the method pool for a given selector from
1920 /// external storage.
1921 ///
1922 /// This routine should only be called once, when the method pool has no entry
1923 /// for this selector.
1924 Sema::GlobalMethodPool::iterator Sema::ReadMethodPool(Selector Sel) {
1925   assert(ExternalSource && "We need an external AST source");
1926   assert(MethodPool.find(Sel) == MethodPool.end() &&
1927          "Selector data already loaded into the method pool");
1928 
1929   // Read the method list from the external source.
1930   GlobalMethods Methods = ExternalSource->ReadMethodPool(Sel);
1931 
1932   return MethodPool.insert(std::make_pair(Sel, Methods)).first;
1933 }
1934 
1935 void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
1936                                  bool instance) {
1937   GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
1938   if (Pos == MethodPool.end()) {
1939     if (ExternalSource)
1940       Pos = ReadMethodPool(Method->getSelector());
1941     else
1942       Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
1943                                              GlobalMethods())).first;
1944   }
1945   Method->setDefined(impl);
1946   ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
1947   if (Entry.Method == 0) {
1948     // Haven't seen a method with this selector name yet - add it.
1949     Entry.Method = Method;
1950     Entry.Next = 0;
1951     return;
1952   }
1953 
1954   // We've seen a method with this name, see if we have already seen this type
1955   // signature.
1956   for (ObjCMethodList *List = &Entry; List; List = List->Next) {
1957     bool match = MatchTwoMethodDeclarations(Method, List->Method);
1958 
1959     if (match) {
1960       ObjCMethodDecl *PrevObjCMethod = List->Method;
1961       PrevObjCMethod->setDefined(impl);
1962       // If a method is deprecated, push it in the global pool.
1963       // This is used for better diagnostics.
1964       if (Method->isDeprecated()) {
1965         if (!PrevObjCMethod->isDeprecated())
1966           List->Method = Method;
1967       }
1968       // If new method is unavailable, push it into global pool
1969       // unless previous one is deprecated.
1970       if (Method->isUnavailable()) {
1971         if (PrevObjCMethod->getAvailability() < AR_Deprecated)
1972           List->Method = Method;
1973       }
1974       return;
1975     }
1976   }
1977 
1978   // We have a new signature for an existing method - add it.
1979   // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
1980   ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
1981   Entry.Next = new (Mem) ObjCMethodList(Method, Entry.Next);
1982 }
1983 
1984 /// Determines if this is an "acceptable" loose mismatch in the global
1985 /// method pool.  This exists mostly as a hack to get around certain
1986 /// global mismatches which we can't afford to make warnings / errors.
1987 /// Really, what we want is a way to take a method out of the global
1988 /// method pool.
1989 static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
1990                                        ObjCMethodDecl *other) {
1991   if (!chosen->isInstanceMethod())
1992     return false;
1993 
1994   Selector sel = chosen->getSelector();
1995   if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
1996     return false;
1997 
1998   // Don't complain about mismatches for -length if the method we
1999   // chose has an integral result type.
2000   return (chosen->getResultType()->isIntegerType());
2001 }
2002 
2003 ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
2004                                                bool receiverIdOrClass,
2005                                                bool warn, bool instance) {
2006   GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
2007   if (Pos == MethodPool.end()) {
2008     if (ExternalSource)
2009       Pos = ReadMethodPool(Sel);
2010     else
2011       return 0;
2012   }
2013 
2014   ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
2015 
2016   if (warn && MethList.Method && MethList.Next) {
2017     bool issueDiagnostic = false, issueError = false;
2018 
2019     // We support a warning which complains about *any* difference in
2020     // method signature.
2021     bool strictSelectorMatch =
2022       (receiverIdOrClass && warn &&
2023        (Diags.getDiagnosticLevel(diag::warn_strict_multiple_method_decl,
2024                                  R.getBegin()) !=
2025       DiagnosticsEngine::Ignored));
2026     if (strictSelectorMatch)
2027       for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next) {
2028         if (!MatchTwoMethodDeclarations(MethList.Method, Next->Method,
2029                                         MMS_strict)) {
2030           issueDiagnostic = true;
2031           break;
2032         }
2033       }
2034 
2035     // If we didn't see any strict differences, we won't see any loose
2036     // differences.  In ARC, however, we also need to check for loose
2037     // mismatches, because most of them are errors.
2038     if (!strictSelectorMatch ||
2039         (issueDiagnostic && getLangOptions().ObjCAutoRefCount))
2040       for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next) {
2041         // This checks if the methods differ in type mismatch.
2042         if (!MatchTwoMethodDeclarations(MethList.Method, Next->Method,
2043                                         MMS_loose) &&
2044             !isAcceptableMethodMismatch(MethList.Method, Next->Method)) {
2045           issueDiagnostic = true;
2046           if (getLangOptions().ObjCAutoRefCount)
2047             issueError = true;
2048           break;
2049         }
2050       }
2051 
2052     if (issueDiagnostic) {
2053       if (issueError)
2054         Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
2055       else if (strictSelectorMatch)
2056         Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
2057       else
2058         Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
2059 
2060       Diag(MethList.Method->getLocStart(),
2061            issueError ? diag::note_possibility : diag::note_using)
2062         << MethList.Method->getSourceRange();
2063       for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next)
2064         Diag(Next->Method->getLocStart(), diag::note_also_found)
2065           << Next->Method->getSourceRange();
2066     }
2067   }
2068   return MethList.Method;
2069 }
2070 
2071 ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
2072   GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
2073   if (Pos == MethodPool.end())
2074     return 0;
2075 
2076   GlobalMethods &Methods = Pos->second;
2077 
2078   if (Methods.first.Method && Methods.first.Method->isDefined())
2079     return Methods.first.Method;
2080   if (Methods.second.Method && Methods.second.Method->isDefined())
2081     return Methods.second.Method;
2082   return 0;
2083 }
2084 
2085 /// CompareMethodParamsInBaseAndSuper - This routine compares methods with
2086 /// identical selector names in current and its super classes and issues
2087 /// a warning if any of their argument types are incompatible.
2088 void Sema::CompareMethodParamsInBaseAndSuper(Decl *ClassDecl,
2089                                              ObjCMethodDecl *Method,
2090                                              bool IsInstance)  {
2091   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
2092   if (ID == 0) return;
2093 
2094   while (ObjCInterfaceDecl *SD = ID->getSuperClass()) {
2095     ObjCMethodDecl *SuperMethodDecl =
2096         SD->lookupMethod(Method->getSelector(), IsInstance);
2097     if (SuperMethodDecl == 0) {
2098       ID = SD;
2099       continue;
2100     }
2101     ObjCMethodDecl::param_iterator ParamI = Method->param_begin(),
2102       E = Method->param_end();
2103     ObjCMethodDecl::param_iterator PrevI = SuperMethodDecl->param_begin();
2104     for (; ParamI != E; ++ParamI, ++PrevI) {
2105       // Number of parameters are the same and is guaranteed by selector match.
2106       assert(PrevI != SuperMethodDecl->param_end() && "Param mismatch");
2107       QualType T1 = Context.getCanonicalType((*ParamI)->getType());
2108       QualType T2 = Context.getCanonicalType((*PrevI)->getType());
2109       // If type of argument of method in this class does not match its
2110       // respective argument type in the super class method, issue warning;
2111       if (!Context.typesAreCompatible(T1, T2)) {
2112         Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
2113           << T1 << T2;
2114         Diag(SuperMethodDecl->getLocation(), diag::note_previous_declaration);
2115         return;
2116       }
2117     }
2118     ID = SD;
2119   }
2120 }
2121 
2122 /// DiagnoseDuplicateIvars -
2123 /// Check for duplicate ivars in the entire class at the start of
2124 /// @implementation. This becomes necesssary because class extension can
2125 /// add ivars to a class in random order which will not be known until
2126 /// class's @implementation is seen.
2127 void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
2128                                   ObjCInterfaceDecl *SID) {
2129   for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
2130        IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
2131     ObjCIvarDecl* Ivar = (*IVI);
2132     if (Ivar->isInvalidDecl())
2133       continue;
2134     if (IdentifierInfo *II = Ivar->getIdentifier()) {
2135       ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
2136       if (prevIvar) {
2137         Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
2138         Diag(prevIvar->getLocation(), diag::note_previous_declaration);
2139         Ivar->setInvalidDecl();
2140       }
2141     }
2142   }
2143 }
2144 
2145 // Note: For class/category implemenations, allMethods/allProperties is
2146 // always null.
2147 void Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd,
2148                       Decl **allMethods, unsigned allNum,
2149                       Decl **allProperties, unsigned pNum,
2150                       DeclGroupPtrTy *allTUVars, unsigned tuvNum) {
2151 
2152   if (!CurContext->isObjCContainer())
2153     return;
2154   ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
2155   Decl *ClassDecl = cast<Decl>(OCD);
2156 
2157   bool isInterfaceDeclKind =
2158         isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
2159          || isa<ObjCProtocolDecl>(ClassDecl);
2160   bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
2161 
2162   if (!isInterfaceDeclKind && AtEnd.isInvalid()) {
2163     // FIXME: This is wrong.  We shouldn't be pretending that there is
2164     //  an '@end' in the declaration.
2165     SourceLocation L = OCD->getAtStartLoc();
2166     AtEnd.setBegin(L);
2167     AtEnd.setEnd(L);
2168     Diag(L, diag::err_missing_atend);
2169   }
2170 
2171   // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
2172   llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
2173   llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
2174 
2175   for (unsigned i = 0; i < allNum; i++ ) {
2176     ObjCMethodDecl *Method =
2177       cast_or_null<ObjCMethodDecl>(allMethods[i]);
2178 
2179     if (!Method) continue;  // Already issued a diagnostic.
2180     if (Method->isInstanceMethod()) {
2181       /// Check for instance method of the same name with incompatible types
2182       const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
2183       bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
2184                               : false;
2185       if ((isInterfaceDeclKind && PrevMethod && !match)
2186           || (checkIdenticalMethods && match)) {
2187           Diag(Method->getLocation(), diag::err_duplicate_method_decl)
2188             << Method->getDeclName();
2189           Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2190         Method->setInvalidDecl();
2191       } else {
2192         if (PrevMethod)
2193           Method->setAsRedeclaration(PrevMethod);
2194         InsMap[Method->getSelector()] = Method;
2195         /// The following allows us to typecheck messages to "id".
2196         AddInstanceMethodToGlobalPool(Method);
2197         // verify that the instance method conforms to the same definition of
2198         // parent methods if it shadows one.
2199         CompareMethodParamsInBaseAndSuper(ClassDecl, Method, true);
2200       }
2201     } else {
2202       /// Check for class method of the same name with incompatible types
2203       const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
2204       bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
2205                               : false;
2206       if ((isInterfaceDeclKind && PrevMethod && !match)
2207           || (checkIdenticalMethods && match)) {
2208         Diag(Method->getLocation(), diag::err_duplicate_method_decl)
2209           << Method->getDeclName();
2210         Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2211         Method->setInvalidDecl();
2212       } else {
2213         if (PrevMethod)
2214           Method->setAsRedeclaration(PrevMethod);
2215         ClsMap[Method->getSelector()] = Method;
2216         /// The following allows us to typecheck messages to "Class".
2217         AddFactoryMethodToGlobalPool(Method);
2218         // verify that the class method conforms to the same definition of
2219         // parent methods if it shadows one.
2220         CompareMethodParamsInBaseAndSuper(ClassDecl, Method, false);
2221       }
2222     }
2223   }
2224   if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
2225     // Compares properties declared in this class to those of its
2226     // super class.
2227     ComparePropertiesInBaseAndSuper(I);
2228     CompareProperties(I, I);
2229   } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
2230     // Categories are used to extend the class by declaring new methods.
2231     // By the same token, they are also used to add new properties. No
2232     // need to compare the added property to those in the class.
2233 
2234     // Compare protocol properties with those in category
2235     CompareProperties(C, C);
2236     if (C->IsClassExtension()) {
2237       ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
2238       DiagnoseClassExtensionDupMethods(C, CCPrimary);
2239     }
2240   }
2241   if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
2242     if (CDecl->getIdentifier())
2243       // ProcessPropertyDecl is responsible for diagnosing conflicts with any
2244       // user-defined setter/getter. It also synthesizes setter/getter methods
2245       // and adds them to the DeclContext and global method pools.
2246       for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
2247                                             E = CDecl->prop_end();
2248            I != E; ++I)
2249         ProcessPropertyDecl(*I, CDecl);
2250     CDecl->setAtEndRange(AtEnd);
2251   }
2252   if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
2253     IC->setAtEndRange(AtEnd);
2254     if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
2255       // Any property declared in a class extension might have user
2256       // declared setter or getter in current class extension or one
2257       // of the other class extensions. Mark them as synthesized as
2258       // property will be synthesized when property with same name is
2259       // seen in the @implementation.
2260       for (const ObjCCategoryDecl *ClsExtDecl =
2261            IDecl->getFirstClassExtension();
2262            ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension()) {
2263         for (ObjCContainerDecl::prop_iterator I = ClsExtDecl->prop_begin(),
2264              E = ClsExtDecl->prop_end(); I != E; ++I) {
2265           ObjCPropertyDecl *Property = (*I);
2266           // Skip over properties declared @dynamic
2267           if (const ObjCPropertyImplDecl *PIDecl
2268               = IC->FindPropertyImplDecl(Property->getIdentifier()))
2269             if (PIDecl->getPropertyImplementation()
2270                   == ObjCPropertyImplDecl::Dynamic)
2271               continue;
2272 
2273           for (const ObjCCategoryDecl *CExtDecl =
2274                IDecl->getFirstClassExtension();
2275                CExtDecl; CExtDecl = CExtDecl->getNextClassExtension()) {
2276             if (ObjCMethodDecl *GetterMethod =
2277                 CExtDecl->getInstanceMethod(Property->getGetterName()))
2278               GetterMethod->setSynthesized(true);
2279             if (!Property->isReadOnly())
2280               if (ObjCMethodDecl *SetterMethod =
2281                   CExtDecl->getInstanceMethod(Property->getSetterName()))
2282                 SetterMethod->setSynthesized(true);
2283           }
2284         }
2285       }
2286       ImplMethodsVsClassMethods(S, IC, IDecl);
2287       AtomicPropertySetterGetterRules(IC, IDecl);
2288       DiagnoseOwningPropertyGetterSynthesis(IC);
2289 
2290       if (LangOpts.ObjCNonFragileABI2)
2291         while (IDecl->getSuperClass()) {
2292           DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
2293           IDecl = IDecl->getSuperClass();
2294         }
2295     }
2296     SetIvarInitializers(IC);
2297   } else if (ObjCCategoryImplDecl* CatImplClass =
2298                                    dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
2299     CatImplClass->setAtEndRange(AtEnd);
2300 
2301     // Find category interface decl and then check that all methods declared
2302     // in this interface are implemented in the category @implementation.
2303     if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
2304       for (ObjCCategoryDecl *Categories = IDecl->getCategoryList();
2305            Categories; Categories = Categories->getNextClassCategory()) {
2306         if (Categories->getIdentifier() == CatImplClass->getIdentifier()) {
2307           ImplMethodsVsClassMethods(S, CatImplClass, Categories);
2308           break;
2309         }
2310       }
2311     }
2312   }
2313   if (isInterfaceDeclKind) {
2314     // Reject invalid vardecls.
2315     for (unsigned i = 0; i != tuvNum; i++) {
2316       DeclGroupRef DG = allTUVars[i].getAsVal<DeclGroupRef>();
2317       for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
2318         if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
2319           if (!VDecl->hasExternalStorage())
2320             Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
2321         }
2322     }
2323   }
2324   ActOnObjCContainerFinishDefinition();
2325 
2326   for (unsigned i = 0; i != tuvNum; i++) {
2327     DeclGroupRef DG = allTUVars[i].getAsVal<DeclGroupRef>();
2328     Consumer.HandleTopLevelDeclInObjCContainer(DG);
2329   }
2330 }
2331 
2332 
2333 /// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
2334 /// objective-c's type qualifier from the parser version of the same info.
2335 static Decl::ObjCDeclQualifier
2336 CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
2337   return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
2338 }
2339 
2340 static inline
2341 bool containsInvalidMethodImplAttribute(ObjCMethodDecl *IMD,
2342                                         const AttrVec &A) {
2343   // If method is only declared in implementation (private method),
2344   // No need to issue any diagnostics on method definition with attributes.
2345   if (!IMD)
2346     return false;
2347 
2348   // method declared in interface has no attribute.
2349   // But implementation has attributes. This is invalid
2350   if (!IMD->hasAttrs())
2351     return true;
2352 
2353   const AttrVec &D = IMD->getAttrs();
2354   if (D.size() != A.size())
2355     return true;
2356 
2357   // attributes on method declaration and definition must match exactly.
2358   // Note that we have at most a couple of attributes on methods, so this
2359   // n*n search is good enough.
2360   for (AttrVec::const_iterator i = A.begin(), e = A.end(); i != e; ++i) {
2361     bool match = false;
2362     for (AttrVec::const_iterator i1 = D.begin(), e1 = D.end(); i1 != e1; ++i1) {
2363       if ((*i)->getKind() == (*i1)->getKind()) {
2364         match = true;
2365         break;
2366       }
2367     }
2368     if (!match)
2369       return true;
2370   }
2371   return false;
2372 }
2373 
2374 namespace  {
2375   /// \brief Describes the compatibility of a result type with its method.
2376   enum ResultTypeCompatibilityKind {
2377     RTC_Compatible,
2378     RTC_Incompatible,
2379     RTC_Unknown
2380   };
2381 }
2382 
2383 /// \brief Check whether the declared result type of the given Objective-C
2384 /// method declaration is compatible with the method's class.
2385 ///
2386 static ResultTypeCompatibilityKind
2387 CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
2388                                     ObjCInterfaceDecl *CurrentClass) {
2389   QualType ResultType = Method->getResultType();
2390 
2391   // If an Objective-C method inherits its related result type, then its
2392   // declared result type must be compatible with its own class type. The
2393   // declared result type is compatible if:
2394   if (const ObjCObjectPointerType *ResultObjectType
2395                                 = ResultType->getAs<ObjCObjectPointerType>()) {
2396     //   - it is id or qualified id, or
2397     if (ResultObjectType->isObjCIdType() ||
2398         ResultObjectType->isObjCQualifiedIdType())
2399       return RTC_Compatible;
2400 
2401     if (CurrentClass) {
2402       if (ObjCInterfaceDecl *ResultClass
2403                                       = ResultObjectType->getInterfaceDecl()) {
2404         //   - it is the same as the method's class type, or
2405         if (CurrentClass == ResultClass)
2406           return RTC_Compatible;
2407 
2408         //   - it is a superclass of the method's class type
2409         if (ResultClass->isSuperClassOf(CurrentClass))
2410           return RTC_Compatible;
2411       }
2412     } else {
2413       // Any Objective-C pointer type might be acceptable for a protocol
2414       // method; we just don't know.
2415       return RTC_Unknown;
2416     }
2417   }
2418 
2419   return RTC_Incompatible;
2420 }
2421 
2422 namespace {
2423 /// A helper class for searching for methods which a particular method
2424 /// overrides.
2425 class OverrideSearch {
2426   Sema &S;
2427   ObjCMethodDecl *Method;
2428   llvm::SmallPtrSet<ObjCContainerDecl*, 8> Searched;
2429   llvm::SmallPtrSet<ObjCMethodDecl*, 8> Overridden;
2430   bool Recursive;
2431 
2432 public:
2433   OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) {
2434     Selector selector = method->getSelector();
2435 
2436     // Bypass this search if we've never seen an instance/class method
2437     // with this selector before.
2438     Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
2439     if (it == S.MethodPool.end()) {
2440       if (!S.ExternalSource) return;
2441       it = S.ReadMethodPool(selector);
2442     }
2443     ObjCMethodList &list =
2444       method->isInstanceMethod() ? it->second.first : it->second.second;
2445     if (!list.Method) return;
2446 
2447     ObjCContainerDecl *container
2448       = cast<ObjCContainerDecl>(method->getDeclContext());
2449 
2450     // Prevent the search from reaching this container again.  This is
2451     // important with categories, which override methods from the
2452     // interface and each other.
2453     Searched.insert(container);
2454     searchFromContainer(container);
2455   }
2456 
2457   typedef llvm::SmallPtrSet<ObjCMethodDecl*,8>::iterator iterator;
2458   iterator begin() const { return Overridden.begin(); }
2459   iterator end() const { return Overridden.end(); }
2460 
2461 private:
2462   void searchFromContainer(ObjCContainerDecl *container) {
2463     if (container->isInvalidDecl()) return;
2464 
2465     switch (container->getDeclKind()) {
2466 #define OBJCCONTAINER(type, base) \
2467     case Decl::type: \
2468       searchFrom(cast<type##Decl>(container)); \
2469       break;
2470 #define ABSTRACT_DECL(expansion)
2471 #define DECL(type, base) \
2472     case Decl::type:
2473 #include "clang/AST/DeclNodes.inc"
2474       llvm_unreachable("not an ObjC container!");
2475     }
2476   }
2477 
2478   void searchFrom(ObjCProtocolDecl *protocol) {
2479     // A method in a protocol declaration overrides declarations from
2480     // referenced ("parent") protocols.
2481     search(protocol->getReferencedProtocols());
2482   }
2483 
2484   void searchFrom(ObjCCategoryDecl *category) {
2485     // A method in a category declaration overrides declarations from
2486     // the main class and from protocols the category references.
2487     search(category->getClassInterface());
2488     search(category->getReferencedProtocols());
2489   }
2490 
2491   void searchFrom(ObjCCategoryImplDecl *impl) {
2492     // A method in a category definition that has a category
2493     // declaration overrides declarations from the category
2494     // declaration.
2495     if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
2496       search(category);
2497 
2498     // Otherwise it overrides declarations from the class.
2499     } else {
2500       search(impl->getClassInterface());
2501     }
2502   }
2503 
2504   void searchFrom(ObjCInterfaceDecl *iface) {
2505     // A method in a class declaration overrides declarations from
2506 
2507     //   - categories,
2508     for (ObjCCategoryDecl *category = iface->getCategoryList();
2509            category; category = category->getNextClassCategory())
2510       search(category);
2511 
2512     //   - the super class, and
2513     if (ObjCInterfaceDecl *super = iface->getSuperClass())
2514       search(super);
2515 
2516     //   - any referenced protocols.
2517     search(iface->getReferencedProtocols());
2518   }
2519 
2520   void searchFrom(ObjCImplementationDecl *impl) {
2521     // A method in a class implementation overrides declarations from
2522     // the class interface.
2523     search(impl->getClassInterface());
2524   }
2525 
2526 
2527   void search(const ObjCProtocolList &protocols) {
2528     for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end();
2529          i != e; ++i)
2530       search(*i);
2531   }
2532 
2533   void search(ObjCContainerDecl *container) {
2534     // Abort if we've already searched this container.
2535     if (!Searched.insert(container)) return;
2536 
2537     // Check for a method in this container which matches this selector.
2538     ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
2539                                                 Method->isInstanceMethod());
2540 
2541     // If we find one, record it and bail out.
2542     if (meth) {
2543       Overridden.insert(meth);
2544       return;
2545     }
2546 
2547     // Otherwise, search for methods that a hypothetical method here
2548     // would have overridden.
2549 
2550     // Note that we're now in a recursive case.
2551     Recursive = true;
2552 
2553     searchFromContainer(container);
2554   }
2555 };
2556 }
2557 
2558 Decl *Sema::ActOnMethodDeclaration(
2559     Scope *S,
2560     SourceLocation MethodLoc, SourceLocation EndLoc,
2561     tok::TokenKind MethodType,
2562     ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
2563     ArrayRef<SourceLocation> SelectorLocs,
2564     Selector Sel,
2565     // optional arguments. The number of types/arguments is obtained
2566     // from the Sel.getNumArgs().
2567     ObjCArgInfo *ArgInfo,
2568     DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
2569     AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
2570     bool isVariadic, bool MethodDefinition) {
2571   // Make sure we can establish a context for the method.
2572   if (!CurContext->isObjCContainer()) {
2573     Diag(MethodLoc, diag::error_missing_method_context);
2574     return 0;
2575   }
2576   ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
2577   Decl *ClassDecl = cast<Decl>(OCD);
2578   QualType resultDeclType;
2579 
2580   bool HasRelatedResultType = false;
2581   TypeSourceInfo *ResultTInfo = 0;
2582   if (ReturnType) {
2583     resultDeclType = GetTypeFromParser(ReturnType, &ResultTInfo);
2584 
2585     // Methods cannot return interface types. All ObjC objects are
2586     // passed by reference.
2587     if (resultDeclType->isObjCObjectType()) {
2588       Diag(MethodLoc, diag::err_object_cannot_be_passed_returned_by_value)
2589         << 0 << resultDeclType;
2590       return 0;
2591     }
2592 
2593     HasRelatedResultType = (resultDeclType == Context.getObjCInstanceType());
2594   } else { // get the type for "id".
2595     resultDeclType = Context.getObjCIdType();
2596     Diag(MethodLoc, diag::warn_missing_method_return_type)
2597       << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
2598   }
2599 
2600   ObjCMethodDecl* ObjCMethod =
2601     ObjCMethodDecl::Create(Context, MethodLoc, EndLoc, Sel,
2602                            resultDeclType,
2603                            ResultTInfo,
2604                            CurContext,
2605                            MethodType == tok::minus, isVariadic,
2606                            /*isSynthesized=*/false,
2607                            /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
2608                            MethodDeclKind == tok::objc_optional
2609                              ? ObjCMethodDecl::Optional
2610                              : ObjCMethodDecl::Required,
2611                            HasRelatedResultType);
2612 
2613   SmallVector<ParmVarDecl*, 16> Params;
2614 
2615   for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
2616     QualType ArgType;
2617     TypeSourceInfo *DI;
2618 
2619     if (ArgInfo[i].Type == 0) {
2620       ArgType = Context.getObjCIdType();
2621       DI = 0;
2622     } else {
2623       ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
2624       // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
2625       ArgType = Context.getAdjustedParameterType(ArgType);
2626     }
2627 
2628     LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
2629                    LookupOrdinaryName, ForRedeclaration);
2630     LookupName(R, S);
2631     if (R.isSingleResult()) {
2632       NamedDecl *PrevDecl = R.getFoundDecl();
2633       if (S->isDeclScope(PrevDecl)) {
2634         Diag(ArgInfo[i].NameLoc,
2635              (MethodDefinition ? diag::warn_method_param_redefinition
2636                                : diag::warn_method_param_declaration))
2637           << ArgInfo[i].Name;
2638         Diag(PrevDecl->getLocation(),
2639              diag::note_previous_declaration);
2640       }
2641     }
2642 
2643     SourceLocation StartLoc = DI
2644       ? DI->getTypeLoc().getBeginLoc()
2645       : ArgInfo[i].NameLoc;
2646 
2647     ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
2648                                         ArgInfo[i].NameLoc, ArgInfo[i].Name,
2649                                         ArgType, DI, SC_None, SC_None);
2650 
2651     Param->setObjCMethodScopeInfo(i);
2652 
2653     Param->setObjCDeclQualifier(
2654       CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
2655 
2656     // Apply the attributes to the parameter.
2657     ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
2658 
2659     S->AddDecl(Param);
2660     IdResolver.AddDecl(Param);
2661 
2662     Params.push_back(Param);
2663   }
2664 
2665   for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
2666     ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
2667     QualType ArgType = Param->getType();
2668     if (ArgType.isNull())
2669       ArgType = Context.getObjCIdType();
2670     else
2671       // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
2672       ArgType = Context.getAdjustedParameterType(ArgType);
2673     if (ArgType->isObjCObjectType()) {
2674       Diag(Param->getLocation(),
2675            diag::err_object_cannot_be_passed_returned_by_value)
2676       << 1 << ArgType;
2677       Param->setInvalidDecl();
2678     }
2679     Param->setDeclContext(ObjCMethod);
2680 
2681     Params.push_back(Param);
2682   }
2683 
2684   ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
2685   ObjCMethod->setObjCDeclQualifier(
2686     CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
2687 
2688   if (AttrList)
2689     ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
2690 
2691   // Add the method now.
2692   const ObjCMethodDecl *PrevMethod = 0;
2693   if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
2694     if (MethodType == tok::minus) {
2695       PrevMethod = ImpDecl->getInstanceMethod(Sel);
2696       ImpDecl->addInstanceMethod(ObjCMethod);
2697     } else {
2698       PrevMethod = ImpDecl->getClassMethod(Sel);
2699       ImpDecl->addClassMethod(ObjCMethod);
2700     }
2701 
2702     ObjCMethodDecl *IMD = 0;
2703     if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface())
2704       IMD = IDecl->lookupMethod(ObjCMethod->getSelector(),
2705                                 ObjCMethod->isInstanceMethod());
2706     if (ObjCMethod->hasAttrs() &&
2707         containsInvalidMethodImplAttribute(IMD, ObjCMethod->getAttrs()))
2708       Diag(EndLoc, diag::warn_attribute_method_def);
2709   } else {
2710     cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
2711   }
2712 
2713   if (PrevMethod) {
2714     // You can never have two method definitions with the same name.
2715     Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
2716       << ObjCMethod->getDeclName();
2717     Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2718   }
2719 
2720   // If this Objective-C method does not have a related result type, but we
2721   // are allowed to infer related result types, try to do so based on the
2722   // method family.
2723   ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
2724   if (!CurrentClass) {
2725     if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
2726       CurrentClass = Cat->getClassInterface();
2727     else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
2728       CurrentClass = Impl->getClassInterface();
2729     else if (ObjCCategoryImplDecl *CatImpl
2730                                    = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
2731       CurrentClass = CatImpl->getClassInterface();
2732   }
2733 
2734   ResultTypeCompatibilityKind RTC
2735     = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass);
2736 
2737   // Search for overridden methods and merge information down from them.
2738   OverrideSearch overrides(*this, ObjCMethod);
2739   for (OverrideSearch::iterator
2740          i = overrides.begin(), e = overrides.end(); i != e; ++i) {
2741     ObjCMethodDecl *overridden = *i;
2742 
2743     // Propagate down the 'related result type' bit from overridden methods.
2744     if (RTC != RTC_Incompatible && overridden->hasRelatedResultType())
2745       ObjCMethod->SetRelatedResultType();
2746 
2747     // Then merge the declarations.
2748     mergeObjCMethodDecls(ObjCMethod, overridden);
2749 
2750     // Check for overriding methods
2751     if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) ||
2752         isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext()))
2753       CheckConflictingOverridingMethod(ObjCMethod, overridden,
2754               isa<ObjCProtocolDecl>(overridden->getDeclContext()));
2755   }
2756 
2757   bool ARCError = false;
2758   if (getLangOptions().ObjCAutoRefCount)
2759     ARCError = CheckARCMethodDecl(*this, ObjCMethod);
2760 
2761   // Infer the related result type when possible.
2762   if (!ARCError && RTC == RTC_Compatible &&
2763       !ObjCMethod->hasRelatedResultType() &&
2764       LangOpts.ObjCInferRelatedResultType) {
2765     bool InferRelatedResultType = false;
2766     switch (ObjCMethod->getMethodFamily()) {
2767     case OMF_None:
2768     case OMF_copy:
2769     case OMF_dealloc:
2770     case OMF_finalize:
2771     case OMF_mutableCopy:
2772     case OMF_release:
2773     case OMF_retainCount:
2774     case OMF_performSelector:
2775       break;
2776 
2777     case OMF_alloc:
2778     case OMF_new:
2779       InferRelatedResultType = ObjCMethod->isClassMethod();
2780       break;
2781 
2782     case OMF_init:
2783     case OMF_autorelease:
2784     case OMF_retain:
2785     case OMF_self:
2786       InferRelatedResultType = ObjCMethod->isInstanceMethod();
2787       break;
2788     }
2789 
2790     if (InferRelatedResultType)
2791       ObjCMethod->SetRelatedResultType();
2792   }
2793 
2794   return ObjCMethod;
2795 }
2796 
2797 bool Sema::CheckObjCDeclScope(Decl *D) {
2798   if (isa<TranslationUnitDecl>(CurContext->getRedeclContext()))
2799     return false;
2800   // Following is also an error. But it is caused by a missing @end
2801   // and diagnostic is issued elsewhere.
2802   if (isa<ObjCContainerDecl>(CurContext->getRedeclContext())) {
2803     return false;
2804   }
2805 
2806   Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
2807   D->setInvalidDecl();
2808 
2809   return true;
2810 }
2811 
2812 /// Called whenever @defs(ClassName) is encountered in the source.  Inserts the
2813 /// instance variables of ClassName into Decls.
2814 void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2815                      IdentifierInfo *ClassName,
2816                      SmallVectorImpl<Decl*> &Decls) {
2817   // Check that ClassName is a valid class
2818   ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
2819   if (!Class) {
2820     Diag(DeclStart, diag::err_undef_interface) << ClassName;
2821     return;
2822   }
2823   if (LangOpts.ObjCNonFragileABI) {
2824     Diag(DeclStart, diag::err_atdef_nonfragile_interface);
2825     return;
2826   }
2827 
2828   // Collect the instance variables
2829   SmallVector<const ObjCIvarDecl*, 32> Ivars;
2830   Context.DeepCollectObjCIvars(Class, true, Ivars);
2831   // For each ivar, create a fresh ObjCAtDefsFieldDecl.
2832   for (unsigned i = 0; i < Ivars.size(); i++) {
2833     const FieldDecl* ID = cast<FieldDecl>(Ivars[i]);
2834     RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
2835     Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
2836                                            /*FIXME: StartL=*/ID->getLocation(),
2837                                            ID->getLocation(),
2838                                            ID->getIdentifier(), ID->getType(),
2839                                            ID->getBitWidth());
2840     Decls.push_back(FD);
2841   }
2842 
2843   // Introduce all of these fields into the appropriate scope.
2844   for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
2845        D != Decls.end(); ++D) {
2846     FieldDecl *FD = cast<FieldDecl>(*D);
2847     if (getLangOptions().CPlusPlus)
2848       PushOnScopeChains(cast<FieldDecl>(FD), S);
2849     else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
2850       Record->addDecl(FD);
2851   }
2852 }
2853 
2854 /// \brief Build a type-check a new Objective-C exception variable declaration.
2855 VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
2856                                       SourceLocation StartLoc,
2857                                       SourceLocation IdLoc,
2858                                       IdentifierInfo *Id,
2859                                       bool Invalid) {
2860   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
2861   // duration shall not be qualified by an address-space qualifier."
2862   // Since all parameters have automatic store duration, they can not have
2863   // an address space.
2864   if (T.getAddressSpace() != 0) {
2865     Diag(IdLoc, diag::err_arg_with_address_space);
2866     Invalid = true;
2867   }
2868 
2869   // An @catch parameter must be an unqualified object pointer type;
2870   // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
2871   if (Invalid) {
2872     // Don't do any further checking.
2873   } else if (T->isDependentType()) {
2874     // Okay: we don't know what this type will instantiate to.
2875   } else if (!T->isObjCObjectPointerType()) {
2876     Invalid = true;
2877     Diag(IdLoc ,diag::err_catch_param_not_objc_type);
2878   } else if (T->isObjCQualifiedIdType()) {
2879     Invalid = true;
2880     Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
2881   }
2882 
2883   VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
2884                                  T, TInfo, SC_None, SC_None);
2885   New->setExceptionVariable(true);
2886 
2887   if (Invalid)
2888     New->setInvalidDecl();
2889   return New;
2890 }
2891 
2892 Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
2893   const DeclSpec &DS = D.getDeclSpec();
2894 
2895   // We allow the "register" storage class on exception variables because
2896   // GCC did, but we drop it completely. Any other storage class is an error.
2897   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2898     Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
2899       << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
2900   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
2901     Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
2902       << DS.getStorageClassSpec();
2903   }
2904   if (D.getDeclSpec().isThreadSpecified())
2905     Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
2906   D.getMutableDeclSpec().ClearStorageClassSpecs();
2907 
2908   DiagnoseFunctionSpecifiers(D);
2909 
2910   // Check that there are no default arguments inside the type of this
2911   // exception object (C++ only).
2912   if (getLangOptions().CPlusPlus)
2913     CheckExtraCXXDefaultArguments(D);
2914 
2915   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
2916   QualType ExceptionType = TInfo->getType();
2917 
2918   VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
2919                                         D.getSourceRange().getBegin(),
2920                                         D.getIdentifierLoc(),
2921                                         D.getIdentifier(),
2922                                         D.isInvalidType());
2923 
2924   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2925   if (D.getCXXScopeSpec().isSet()) {
2926     Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
2927       << D.getCXXScopeSpec().getRange();
2928     New->setInvalidDecl();
2929   }
2930 
2931   // Add the parameter declaration into this scope.
2932   S->AddDecl(New);
2933   if (D.getIdentifier())
2934     IdResolver.AddDecl(New);
2935 
2936   ProcessDeclAttributes(S, New, D);
2937 
2938   if (New->hasAttr<BlocksAttr>())
2939     Diag(New->getLocation(), diag::err_block_on_nonlocal);
2940   return New;
2941 }
2942 
2943 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
2944 /// initialization.
2945 void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
2946                                 SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
2947   for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
2948        Iv= Iv->getNextIvar()) {
2949     QualType QT = Context.getBaseElementType(Iv->getType());
2950     if (QT->isRecordType())
2951       Ivars.push_back(Iv);
2952   }
2953 }
2954 
2955 void Sema::DiagnoseUseOfUnimplementedSelectors() {
2956   // Load referenced selectors from the external source.
2957   if (ExternalSource) {
2958     SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
2959     ExternalSource->ReadReferencedSelectors(Sels);
2960     for (unsigned I = 0, N = Sels.size(); I != N; ++I)
2961       ReferencedSelectors[Sels[I].first] = Sels[I].second;
2962   }
2963 
2964   // Warning will be issued only when selector table is
2965   // generated (which means there is at lease one implementation
2966   // in the TU). This is to match gcc's behavior.
2967   if (ReferencedSelectors.empty() ||
2968       !Context.AnyObjCImplementation())
2969     return;
2970   for (llvm::DenseMap<Selector, SourceLocation>::iterator S =
2971         ReferencedSelectors.begin(),
2972        E = ReferencedSelectors.end(); S != E; ++S) {
2973     Selector Sel = (*S).first;
2974     if (!LookupImplementedMethodInGlobalPool(Sel))
2975       Diag((*S).second, diag::warn_unimplemented_selector) << Sel;
2976   }
2977   return;
2978 }
2979