SemaExprObjC.cpp revision d305a86f087fd359cf0f033eba0c968e55a61ff4
1//===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===//
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 expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/AST/ExprObjC.h"
18#include "llvm/ADT/SmallString.h"
19using namespace clang;
20
21Sema::ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
22                                              ExprTy **strings,
23                                              unsigned NumStrings) {
24  StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
25
26  // Most ObjC strings are formed out of a single piece.  However, we *can*
27  // have strings formed out of multiple @ strings with multiple pptokens in
28  // each one, e.g. @"foo" "bar" @"baz" "qux"   which need to be turned into one
29  // StringLiteral for ObjCStringLiteral to hold onto.
30  StringLiteral *S = Strings[0];
31
32  // If we have a multi-part string, merge it all together.
33  if (NumStrings != 1) {
34    // Concatenate objc strings.
35    llvm::SmallString<128> StrBuf;
36    llvm::SmallVector<SourceLocation, 8> StrLocs;
37
38    for (unsigned i = 0; i != NumStrings; ++i) {
39      S = Strings[i];
40
41      // ObjC strings can't be wide.
42      if (S->isWide()) {
43        Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
44          << S->getSourceRange();
45        return true;
46      }
47
48      // Get the string data.
49      StrBuf.append(S->getStrData(), S->getStrData()+S->getByteLength());
50
51      // Get the locations of the string tokens.
52      StrLocs.append(S->tokloc_begin(), S->tokloc_end());
53
54      // Free the temporary string.
55      S->Destroy(Context);
56    }
57
58    // Create the aggregate string with the appropriate content and location
59    // information.
60    S = StringLiteral::Create(Context, &StrBuf[0], StrBuf.size(), false,
61                              Context.getPointerType(Context.CharTy),
62                              &StrLocs[0], StrLocs.size());
63  }
64
65  // Verify that this composite string is acceptable for ObjC strings.
66  if (CheckObjCString(S))
67    return true;
68
69  // Initialize the constant string interface lazily. This assumes
70  // the NSConstantString interface is seen in this translation unit.
71  QualType Ty = Context.getObjCConstantStringInterface();
72  if (!Ty.isNull()) {
73    Ty = Context.getPointerType(Ty);
74  } else {
75    IdentifierInfo *NSIdent = &Context.Idents.get("NSConstantString");
76    NamedDecl *IF = LookupName(TUScope, NSIdent, LookupOrdinaryName);
77    if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
78      Context.setObjCConstantStringInterface(StrIF);
79      Ty = Context.getObjCConstantStringInterface();
80      Ty = Context.getPointerType(Ty);
81    } else {
82      // If there is no NSConstantString interface defined then treat constant
83      // strings as untyped objects and let the runtime figure it out later.
84      Ty = Context.getObjCIdType();
85    }
86  }
87
88  return new (Context) ObjCStringLiteral(S, Ty, AtLocs[0]);
89}
90
91Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
92                                                 SourceLocation EncodeLoc,
93                                                 SourceLocation LParenLoc,
94                                                 TypeTy *ty,
95                                                 SourceLocation RParenLoc) {
96  QualType EncodedType = QualType::getFromOpaquePtr(ty);
97
98  QualType Ty = Context.getPointerType(Context.CharTy);
99  return new (Context) ObjCEncodeExpr(Ty, EncodedType, AtLoc, RParenLoc);
100}
101
102Sema::ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
103                                                   SourceLocation AtLoc,
104                                                   SourceLocation SelLoc,
105                                                   SourceLocation LParenLoc,
106                                                   SourceLocation RParenLoc) {
107  QualType Ty = Context.getObjCSelType();
108  return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
109}
110
111Sema::ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
112                                                   SourceLocation AtLoc,
113                                                   SourceLocation ProtoLoc,
114                                                   SourceLocation LParenLoc,
115                                                   SourceLocation RParenLoc) {
116  ObjCProtocolDecl* PDecl = ObjCProtocols[ProtocolId];
117  if (!PDecl) {
118    Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
119    return true;
120  }
121
122  QualType Ty = Context.getObjCProtoType();
123  if (Ty.isNull())
124    return true;
125  Ty = Context.getPointerType(Ty);
126  return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc);
127}
128
129bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs,
130                                     Selector Sel, ObjCMethodDecl *Method,
131                                     bool isClassMessage,
132                                     SourceLocation lbrac, SourceLocation rbrac,
133                                     QualType &ReturnType) {
134  if (!Method) {
135    // Apply default argument promotion as for (C99 6.5.2.2p6).
136    for (unsigned i = 0; i != NumArgs; i++)
137      DefaultArgumentPromotion(Args[i]);
138
139    unsigned DiagID = isClassMessage ? diag::warn_class_method_not_found :
140                                       diag::warn_inst_method_not_found;
141    Diag(lbrac, DiagID)
142      << Sel << isClassMessage << SourceRange(lbrac, rbrac);
143    ReturnType = Context.getObjCIdType();
144    return false;
145  }
146
147  ReturnType = Method->getResultType();
148
149  unsigned NumNamedArgs = Sel.getNumArgs();
150  assert(NumArgs >= NumNamedArgs && "Too few arguments for selector!");
151
152  bool anyIncompatibleArgs = false;
153  for (unsigned i = 0; i < NumNamedArgs; i++) {
154    Expr *argExpr = Args[i];
155    assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
156
157    QualType lhsType = Method->param_begin()[i]->getType();
158    QualType rhsType = argExpr->getType();
159
160    // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
161    if (lhsType->isArrayType())
162      lhsType = Context.getArrayDecayedType(lhsType);
163    else if (lhsType->isFunctionType())
164      lhsType = Context.getPointerType(lhsType);
165
166    AssignConvertType Result =
167      CheckSingleAssignmentConstraints(lhsType, argExpr);
168    if (Args[i] != argExpr) // The expression was converted.
169      Args[i] = argExpr; // Make sure we store the converted expression.
170
171    anyIncompatibleArgs |=
172      DiagnoseAssignmentResult(Result, argExpr->getLocStart(), lhsType, rhsType,
173                               argExpr, "sending");
174  }
175
176  // Promote additional arguments to variadic methods.
177  if (Method->isVariadic()) {
178    for (unsigned i = NumNamedArgs; i < NumArgs; ++i)
179      DefaultVariadicArgumentPromotion(Args[i], VariadicMethod);
180  } else {
181    // Check for extra arguments to non-variadic methods.
182    if (NumArgs != NumNamedArgs) {
183      Diag(Args[NumNamedArgs]->getLocStart(),
184           diag::err_typecheck_call_too_many_args)
185        << 2 /*method*/ << Method->getSourceRange()
186        << SourceRange(Args[NumNamedArgs]->getLocStart(),
187                       Args[NumArgs-1]->getLocEnd());
188    }
189  }
190
191  return anyIncompatibleArgs;
192}
193
194// ActOnClassMessage - used for both unary and keyword messages.
195// ArgExprs is optional - if it is present, the number of expressions
196// is obtained from Sel.getNumArgs().
197Sema::ExprResult Sema::ActOnClassMessage(
198  Scope *S,
199  IdentifierInfo *receiverName, Selector Sel,
200  SourceLocation lbrac, SourceLocation receiverLoc,
201  SourceLocation selectorLoc, SourceLocation rbrac,
202  ExprTy **Args, unsigned NumArgs)
203{
204  assert(receiverName && "missing receiver class name");
205
206  Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
207  ObjCInterfaceDecl* ClassDecl = 0;
208  bool isSuper = false;
209
210  if (receiverName->isStr("super")) {
211    if (getCurMethodDecl()) {
212      isSuper = true;
213      ObjCInterfaceDecl *OID = getCurMethodDecl()->getClassInterface();
214      if (!OID)
215        return Diag(lbrac, diag::error_no_super_class_message)
216                      << getCurMethodDecl()->getDeclName();
217      ClassDecl = OID->getSuperClass();
218      if (!ClassDecl)
219        return Diag(lbrac, diag::error_no_super_class) << OID->getDeclName();
220      if (getCurMethodDecl()->isInstanceMethod()) {
221        QualType superTy = Context.getObjCInterfaceType(ClassDecl);
222        superTy = Context.getPointerType(superTy);
223        ExprResult ReceiverExpr = new (Context) ObjCSuperExpr(SourceLocation(),
224                                                              superTy);
225        // We are really in an instance method, redirect.
226        return ActOnInstanceMessage(ReceiverExpr.get(), Sel, lbrac,
227                                    selectorLoc, rbrac, Args, NumArgs);
228      }
229      // We are sending a message to 'super' within a class method. Do nothing,
230      // the receiver will pass through as 'super' (how convenient:-).
231    } else {
232      // 'super' has been used outside a method context. If a variable named
233      // 'super' has been declared, redirect. If not, produce a diagnostic.
234      NamedDecl *SuperDecl = LookupName(S, receiverName, LookupOrdinaryName);
235      ValueDecl *VD = dyn_cast_or_null<ValueDecl>(SuperDecl);
236      if (VD) {
237        ExprResult ReceiverExpr = new (Context) DeclRefExpr(VD, VD->getType(),
238                                                            receiverLoc);
239        // We are really in an instance method, redirect.
240        return ActOnInstanceMessage(ReceiverExpr.get(), Sel, lbrac,
241                                    selectorLoc, rbrac, Args, NumArgs);
242      }
243      return Diag(receiverLoc, diag::err_undeclared_var_use) << receiverName;
244    }
245  } else
246    ClassDecl = getObjCInterfaceDecl(receiverName);
247
248  // The following code allows for the following GCC-ism:
249  //
250  //  typedef XCElementDisplayRect XCElementGraphicsRect;
251  //
252  //  @implementation XCRASlice
253  //  - whatever { // Note that XCElementGraphicsRect is a typedef name.
254  //    _sGraphicsDelegate =[[XCElementGraphicsRect alloc] init];
255  //  }
256  //
257  // If necessary, the following lookup could move to getObjCInterfaceDecl().
258  if (!ClassDecl) {
259    NamedDecl *IDecl = LookupName(TUScope, receiverName, LookupOrdinaryName);
260    if (TypedefDecl *OCTD = dyn_cast_or_null<TypedefDecl>(IDecl)) {
261      const ObjCInterfaceType *OCIT;
262      OCIT = OCTD->getUnderlyingType()->getAsObjCInterfaceType();
263      if (!OCIT)
264        return Diag(receiverLoc, diag::err_invalid_receiver_to_message);
265      ClassDecl = OCIT->getDecl();
266    }
267  }
268  assert(ClassDecl && "missing interface declaration");
269  ObjCMethodDecl *Method = 0;
270  QualType returnType;
271  Method = ClassDecl->lookupClassMethod(Sel);
272
273  // If we have an implementation in scope, check "private" methods.
274  if (!Method) {
275    if (ObjCImplementationDecl *ImpDecl =
276        ObjCImplementations[ClassDecl->getIdentifier()])
277      Method = ImpDecl->getClassMethod(Sel);
278
279    // Look through local category implementations associated with the class.
280    if (!Method) {
281      for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Method; i++) {
282        if (ObjCCategoryImpls[i]->getClassInterface() == ClassDecl)
283          Method = ObjCCategoryImpls[i]->getClassMethod(Sel);
284      }
285    }
286  }
287  // Before we give up, check if the selector is an instance method.
288  if (!Method)
289    Method = ClassDecl->lookupInstanceMethod(Sel);
290
291  if (Method && DiagnoseUseOfDecl(Method, receiverLoc))
292    return true;
293
294  if (CheckMessageArgumentTypes(ArgExprs, NumArgs, Sel, Method, true,
295                                lbrac, rbrac, returnType))
296    return true;
297
298  // If we have the ObjCInterfaceDecl* for the class that is receiving
299  // the message, use that to construct the ObjCMessageExpr.  Otherwise
300  // pass on the IdentifierInfo* for the class.
301  // FIXME: need to do a better job handling 'super' usage within a class
302  // For now, we simply pass the "super" identifier through (which isn't
303  // consistent with instance methods.
304  if (isSuper)
305    return new (Context) ObjCMessageExpr(receiverName, Sel, returnType, Method,
306                                         lbrac, rbrac, ArgExprs, NumArgs);
307  else
308    return new (Context) ObjCMessageExpr(ClassDecl, Sel, returnType, Method,
309                                         lbrac, rbrac, ArgExprs, NumArgs);
310}
311
312// ActOnInstanceMessage - used for both unary and keyword messages.
313// ArgExprs is optional - if it is present, the number of expressions
314// is obtained from Sel.getNumArgs().
315Sema::ExprResult Sema::ActOnInstanceMessage(ExprTy *receiver, Selector Sel,
316                                            SourceLocation lbrac,
317                                            SourceLocation receiverLoc,
318                                            SourceLocation rbrac,
319                                            ExprTy **Args, unsigned NumArgs) {
320  assert(receiver && "missing receiver expression");
321
322  Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
323  Expr *RExpr = static_cast<Expr *>(receiver);
324  QualType returnType;
325
326  QualType ReceiverCType =
327    Context.getCanonicalType(RExpr->getType()).getUnqualifiedType();
328
329  // Handle messages to 'super'.
330  if (isa<ObjCSuperExpr>(RExpr)) {
331    ObjCMethodDecl *Method = 0;
332    if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
333      // If we have an interface in scope, check 'super' methods.
334      if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
335        if (ObjCInterfaceDecl *SuperDecl = ClassDecl->getSuperClass())
336          Method = SuperDecl->lookupInstanceMethod(Sel);
337    }
338
339    if (Method && DiagnoseUseOfDecl(Method, receiverLoc))
340      return true;
341
342    if (CheckMessageArgumentTypes(ArgExprs, NumArgs, Sel, Method, false,
343                                  lbrac, rbrac, returnType))
344      return true;
345    return new (Context) ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac,
346                                         rbrac, ArgExprs, NumArgs);
347  }
348
349  // Handle messages to id.
350  if (ReceiverCType == Context.getCanonicalType(Context.getObjCIdType()) ||
351      ReceiverCType->getAsBlockPointerType()) {
352    ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(
353                               Sel, SourceRange(lbrac,rbrac));
354    if (!Method)
355      Method = FactoryMethodPool[Sel].Method;
356    if (CheckMessageArgumentTypes(ArgExprs, NumArgs, Sel, Method, false,
357                                  lbrac, rbrac, returnType))
358      return true;
359    return new (Context) ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac,
360                                         rbrac, ArgExprs, NumArgs);
361  }
362
363  // Handle messages to Class.
364  if (ReceiverCType == Context.getCanonicalType(Context.getObjCClassType())) {
365    ObjCMethodDecl *Method = 0;
366    if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
367      // If we have an implementation in scope, check "private" methods.
368      if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
369        if (ObjCImplementationDecl *ImpDecl =
370              ObjCImplementations[ClassDecl->getIdentifier()])
371          Method = ImpDecl->getClassMethod(Sel);
372
373      if (Method && DiagnoseUseOfDecl(Method, receiverLoc))
374        return true;
375    }
376    if (!Method)
377      Method = FactoryMethodPool[Sel].Method;
378    if (!Method)
379      Method = LookupInstanceMethodInGlobalPool(
380                               Sel, SourceRange(lbrac,rbrac));
381    if (CheckMessageArgumentTypes(ArgExprs, NumArgs, Sel, Method, false,
382                                  lbrac, rbrac, returnType))
383      return true;
384    return new (Context) ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac,
385                                         rbrac, ArgExprs, NumArgs);
386  }
387
388  ObjCMethodDecl *Method = 0;
389  ObjCInterfaceDecl* ClassDecl = 0;
390
391  // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
392  // long as one of the protocols implements the selector (if not, warn).
393  if (ObjCQualifiedIdType *QIT = dyn_cast<ObjCQualifiedIdType>(ReceiverCType)) {
394    // Search protocols for instance methods.
395    ReceiverCType.dump();
396    for (unsigned i = 0; i < QIT->getNumProtocols(); i++) {
397      ObjCProtocolDecl *PDecl = QIT->getProtocols(i);
398      if (PDecl && (Method = PDecl->lookupInstanceMethod(Sel)))
399        break;
400    }
401    if (!Method)
402      Diag(lbrac, diag::warn_method_not_found_in_protocol)
403        << Sel << RExpr->getSourceRange();
404  // Check for GCC extension "Class<foo>".
405  } else if (ObjCQualifiedClassType *QIT =
406               dyn_cast<ObjCQualifiedClassType>(ReceiverCType)) {
407    // Search protocols for class methods.
408    for (unsigned i = 0; i < QIT->getNumProtocols(); i++) {
409      ObjCProtocolDecl *PDecl = QIT->getProtocols(i);
410      if (PDecl && (Method = PDecl->lookupClassMethod(Sel)))
411        break;
412    }
413    if (!Method)
414      Diag(lbrac, diag::warn_method_not_found_in_protocol)
415        << Sel << RExpr->getSourceRange();
416  } else if (const ObjCInterfaceType *OCIReceiver =
417                ReceiverCType->getAsPointerToObjCInterfaceType()) {
418    // We allow sending a message to a pointer to an interface (an object).
419
420    ClassDecl = OCIReceiver->getDecl();
421    // FIXME: consider using LookupInstanceMethodInGlobalPool, since it will be
422    // faster than the following method (which can do *many* linear searches).
423    // The idea is to add class info to InstanceMethodPool.
424    Method = ClassDecl->lookupInstanceMethod(Sel);
425
426    if (!Method) {
427      // Search protocol qualifiers.
428      for (ObjCQualifiedIdType::qual_iterator QI = OCIReceiver->qual_begin(),
429           E = OCIReceiver->qual_end(); QI != E; ++QI) {
430        if ((Method = (*QI)->lookupInstanceMethod(Sel)))
431          break;
432      }
433    }
434
435    if (!Method && !OCIReceiver->qual_empty())
436      Diag(lbrac, diag::warn_method_not_found_in_protocol)
437        << Sel << SourceRange(lbrac, rbrac);
438
439    if (Method && DiagnoseUseOfDecl(Method, receiverLoc))
440      return true;
441  } else {
442    Diag(lbrac, diag::error_bad_receiver_type)
443      << RExpr->getType() << RExpr->getSourceRange();
444    return true;
445  }
446
447  if (!Method) {
448    // If we have an implementation in scope, check "private" methods.
449    if (ClassDecl)
450      if (ObjCImplementationDecl *ImpDecl =
451            ObjCImplementations[ClassDecl->getIdentifier()])
452        Method = ImpDecl->getInstanceMethod(Sel);
453        // If we still haven't found a method, look in the global pool. This
454        // behavior isn't very desirable, however we need it for GCC
455        // compatibility.
456        if (!Method)
457          Method = LookupInstanceMethodInGlobalPool(
458                               Sel, SourceRange(lbrac,rbrac));
459  }
460  if (CheckMessageArgumentTypes(ArgExprs, NumArgs, Sel, Method, false,
461                                lbrac, rbrac, returnType))
462    return true;
463  return new (Context) ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac,
464                                       rbrac, ArgExprs, NumArgs);
465}
466
467//===----------------------------------------------------------------------===//
468// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
469//===----------------------------------------------------------------------===//
470
471/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
472/// inheritance hierarchy of 'rProto'.
473static bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
474                                           ObjCProtocolDecl *rProto) {
475  if (lProto == rProto)
476    return true;
477  for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
478       E = rProto->protocol_end(); PI != E; ++PI)
479    if (ProtocolCompatibleWithProtocol(lProto, *PI))
480      return true;
481  return false;
482}
483
484/// ClassImplementsProtocol - Checks that 'lProto' protocol
485/// has been implemented in IDecl class, its super class or categories (if
486/// lookupCategory is true).
487static bool ClassImplementsProtocol(ObjCProtocolDecl *lProto,
488                                    ObjCInterfaceDecl *IDecl,
489                                    bool lookupCategory,
490                                    bool RHSIsQualifiedID = false) {
491
492  // 1st, look up the class.
493  const ObjCList<ObjCProtocolDecl> &Protocols =
494    IDecl->getReferencedProtocols();
495
496  for (ObjCList<ObjCProtocolDecl>::iterator PI = Protocols.begin(),
497       E = Protocols.end(); PI != E; ++PI) {
498    if (ProtocolCompatibleWithProtocol(lProto, *PI))
499      return true;
500    // This is dubious and is added to be compatible with gcc.
501    // In gcc, it is also allowed assigning a protocol-qualified 'id'
502    // type to a LHS object when protocol in qualified LHS is in list
503    // of protocols in the rhs 'id' object. This IMO, should be a bug.
504    // FIXME: Treat this as an extension, and flag this as an error when
505    //  GCC extensions are not enabled.
506    if (RHSIsQualifiedID && ProtocolCompatibleWithProtocol(*PI, lProto))
507      return true;
508  }
509
510  // 2nd, look up the category.
511  if (lookupCategory)
512    for (ObjCCategoryDecl *CDecl = IDecl->getCategoryList(); CDecl;
513         CDecl = CDecl->getNextClassCategory()) {
514      for (ObjCCategoryDecl::protocol_iterator PI = CDecl->protocol_begin(),
515           E = CDecl->protocol_end(); PI != E; ++PI)
516        if (ProtocolCompatibleWithProtocol(lProto, *PI))
517          return true;
518    }
519
520  // 3rd, look up the super class(s)
521  if (IDecl->getSuperClass())
522    return
523      ClassImplementsProtocol(lProto, IDecl->getSuperClass(), lookupCategory,
524                              RHSIsQualifiedID);
525
526  return false;
527}
528
529/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
530/// ObjCQualifiedIDType.
531bool Sema::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
532                                             bool compare) {
533  // Allow id<P..> and an 'id' or void* type in all cases.
534  if (const PointerType *PT = lhs->getAsPointerType()) {
535    QualType PointeeTy = PT->getPointeeType();
536    if (Context.isObjCIdStructType(PointeeTy) || PointeeTy->isVoidType())
537      return true;
538  } else if (const PointerType *PT = rhs->getAsPointerType()) {
539    QualType PointeeTy = PT->getPointeeType();
540    if (Context.isObjCIdStructType(PointeeTy) || PointeeTy->isVoidType())
541      return true;
542  }
543
544  if (const ObjCQualifiedIdType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
545    const ObjCQualifiedIdType *rhsQID = rhs->getAsObjCQualifiedIdType();
546    const ObjCQualifiedInterfaceType *rhsQI = 0;
547    QualType rtype;
548
549    if (!rhsQID) {
550      // Not comparing two ObjCQualifiedIdType's?
551      if (!rhs->isPointerType()) return false;
552
553      rtype = rhs->getAsPointerType()->getPointeeType();
554      rhsQI = rtype->getAsObjCQualifiedInterfaceType();
555      if (rhsQI == 0) {
556        // If the RHS is a unqualified interface pointer "NSString*",
557        // make sure we check the class hierarchy.
558        if (const ObjCInterfaceType *IT = rtype->getAsObjCInterfaceType()) {
559          ObjCInterfaceDecl *rhsID = IT->getDecl();
560          for (unsigned i = 0; i != lhsQID->getNumProtocols(); ++i) {
561            // when comparing an id<P> on lhs with a static type on rhs,
562            // see if static class implements all of id's protocols, directly or
563            // through its super class and categories.
564            if (!ClassImplementsProtocol(lhsQID->getProtocols(i), rhsID, true))
565              return false;
566          }
567          return true;
568        }
569      }
570    }
571
572    ObjCQualifiedIdType::qual_iterator RHSProtoI, RHSProtoE;
573    if (rhsQI) { // We have a qualified interface (e.g. "NSObject<Proto> *").
574      RHSProtoI = rhsQI->qual_begin();
575      RHSProtoE = rhsQI->qual_end();
576    } else if (rhsQID) { // We have a qualified id (e.g. "id<Proto> *").
577      RHSProtoI = rhsQID->qual_begin();
578      RHSProtoE = rhsQID->qual_end();
579    } else {
580      return false;
581    }
582
583    for (unsigned i =0; i < lhsQID->getNumProtocols(); i++) {
584      ObjCProtocolDecl *lhsProto = lhsQID->getProtocols(i);
585      bool match = false;
586
587      // when comparing an id<P> on lhs with a static type on rhs,
588      // see if static class implements all of id's protocols, directly or
589      // through its super class and categories.
590      for (; RHSProtoI != RHSProtoE; ++RHSProtoI) {
591        ObjCProtocolDecl *rhsProto = *RHSProtoI;
592        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
593            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
594          match = true;
595          break;
596        }
597      }
598      if (rhsQI) {
599        // If the RHS is a qualified interface pointer "NSString<P>*",
600        // make sure we check the class hierarchy.
601        if (const ObjCInterfaceType *IT = rtype->getAsObjCInterfaceType()) {
602          ObjCInterfaceDecl *rhsID = IT->getDecl();
603          for (unsigned i = 0; i != lhsQID->getNumProtocols(); ++i) {
604            // when comparing an id<P> on lhs with a static type on rhs,
605            // see if static class implements all of id's protocols, directly or
606            // through its super class and categories.
607            if (ClassImplementsProtocol(lhsQID->getProtocols(i), rhsID, true)) {
608              match = true;
609              break;
610            }
611          }
612        }
613      }
614      if (!match)
615        return false;
616    }
617
618    return true;
619  }
620
621  const ObjCQualifiedIdType *rhsQID = rhs->getAsObjCQualifiedIdType();
622  assert(rhsQID && "One of the LHS/RHS should be id<x>");
623
624  if (!lhs->isPointerType())
625    return false;
626
627  QualType ltype = lhs->getAsPointerType()->getPointeeType();
628  if (const ObjCQualifiedInterfaceType *lhsQI =
629         ltype->getAsObjCQualifiedInterfaceType()) {
630    ObjCQualifiedIdType::qual_iterator LHSProtoI = lhsQI->qual_begin();
631    ObjCQualifiedIdType::qual_iterator LHSProtoE = lhsQI->qual_end();
632    for (; LHSProtoI != LHSProtoE; ++LHSProtoI) {
633      bool match = false;
634      ObjCProtocolDecl *lhsProto = *LHSProtoI;
635      for (unsigned j = 0; j < rhsQID->getNumProtocols(); j++) {
636        ObjCProtocolDecl *rhsProto = rhsQID->getProtocols(j);
637        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
638            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
639          match = true;
640          break;
641        }
642      }
643      if (!match)
644        return false;
645    }
646    return true;
647  }
648
649  if (const ObjCInterfaceType *IT = ltype->getAsObjCInterfaceType()) {
650    // for static type vs. qualified 'id' type, check that class implements
651    // all of 'id's protocols.
652    ObjCInterfaceDecl *lhsID = IT->getDecl();
653    for (unsigned j = 0; j < rhsQID->getNumProtocols(); j++) {
654      ObjCProtocolDecl *rhsProto = rhsQID->getProtocols(j);
655      if (!ClassImplementsProtocol(rhsProto, lhsID, compare, true))
656        return false;
657    }
658    return true;
659  }
660  return false;
661}
662
663