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