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