1 //===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements semantic analysis for Objective-C expressions.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/DeclObjC.h"
15 #include "clang/AST/ExprObjC.h"
16 #include "clang/AST/StmtVisitor.h"
17 #include "clang/AST/TypeLoc.h"
18 #include "clang/Analysis/DomainSpecific/CocoaConventions.h"
19 #include "clang/Basic/Builtins.h"
20 #include "clang/Edit/Commit.h"
21 #include "clang/Edit/Rewriters.h"
22 #include "clang/Lex/Preprocessor.h"
23 #include "clang/Sema/Initialization.h"
24 #include "clang/Sema/Lookup.h"
25 #include "clang/Sema/Scope.h"
26 #include "clang/Sema/ScopeInfo.h"
27 #include "clang/Sema/SemaInternal.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/Support/ConvertUTF.h"
30
31 using namespace clang;
32 using namespace sema;
33 using llvm::makeArrayRef;
34
ParseObjCStringLiteral(SourceLocation * AtLocs,ArrayRef<Expr * > Strings)35 ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
36 ArrayRef<Expr *> Strings) {
37 // Most ObjC strings are formed out of a single piece. However, we *can*
38 // have strings formed out of multiple @ strings with multiple pptokens in
39 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
40 // StringLiteral for ObjCStringLiteral to hold onto.
41 StringLiteral *S = cast<StringLiteral>(Strings[0]);
42
43 // If we have a multi-part string, merge it all together.
44 if (Strings.size() != 1) {
45 // Concatenate objc strings.
46 SmallString<128> StrBuf;
47 SmallVector<SourceLocation, 8> StrLocs;
48
49 for (Expr *E : Strings) {
50 S = cast<StringLiteral>(E);
51
52 // ObjC strings can't be wide or UTF.
53 if (!S->isAscii()) {
54 Diag(S->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
55 << S->getSourceRange();
56 return true;
57 }
58
59 // Append the string.
60 StrBuf += S->getString();
61
62 // Get the locations of the string tokens.
63 StrLocs.append(S->tokloc_begin(), S->tokloc_end());
64 }
65
66 // Create the aggregate string with the appropriate content and location
67 // information.
68 const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
69 assert(CAT && "String literal not of constant array type!");
70 QualType StrTy = Context.getConstantArrayType(
71 CAT->getElementType(), llvm::APInt(32, StrBuf.size() + 1), nullptr,
72 CAT->getSizeModifier(), CAT->getIndexTypeCVRQualifiers());
73 S = StringLiteral::Create(Context, StrBuf, StringLiteral::Ascii,
74 /*Pascal=*/false, StrTy, &StrLocs[0],
75 StrLocs.size());
76 }
77
78 return BuildObjCStringLiteral(AtLocs[0], S);
79 }
80
BuildObjCStringLiteral(SourceLocation AtLoc,StringLiteral * S)81 ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){
82 // Verify that this composite string is acceptable for ObjC strings.
83 if (CheckObjCString(S))
84 return true;
85
86 // Initialize the constant string interface lazily. This assumes
87 // the NSString interface is seen in this translation unit. Note: We
88 // don't use NSConstantString, since the runtime team considers this
89 // interface private (even though it appears in the header files).
90 QualType Ty = Context.getObjCConstantStringInterface();
91 if (!Ty.isNull()) {
92 Ty = Context.getObjCObjectPointerType(Ty);
93 } else if (getLangOpts().NoConstantCFStrings) {
94 IdentifierInfo *NSIdent=nullptr;
95 std::string StringClass(getLangOpts().ObjCConstantStringClass);
96
97 if (StringClass.empty())
98 NSIdent = &Context.Idents.get("NSConstantString");
99 else
100 NSIdent = &Context.Idents.get(StringClass);
101
102 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
103 LookupOrdinaryName);
104 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
105 Context.setObjCConstantStringInterface(StrIF);
106 Ty = Context.getObjCConstantStringInterface();
107 Ty = Context.getObjCObjectPointerType(Ty);
108 } else {
109 // If there is no NSConstantString interface defined then treat this
110 // as error and recover from it.
111 Diag(S->getBeginLoc(), diag::err_no_nsconstant_string_class)
112 << NSIdent << S->getSourceRange();
113 Ty = Context.getObjCIdType();
114 }
115 } else {
116 IdentifierInfo *NSIdent = NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
117 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
118 LookupOrdinaryName);
119 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
120 Context.setObjCConstantStringInterface(StrIF);
121 Ty = Context.getObjCConstantStringInterface();
122 Ty = Context.getObjCObjectPointerType(Ty);
123 } else {
124 // If there is no NSString interface defined, implicitly declare
125 // a @class NSString; and use that instead. This is to make sure
126 // type of an NSString literal is represented correctly, instead of
127 // being an 'id' type.
128 Ty = Context.getObjCNSStringType();
129 if (Ty.isNull()) {
130 ObjCInterfaceDecl *NSStringIDecl =
131 ObjCInterfaceDecl::Create (Context,
132 Context.getTranslationUnitDecl(),
133 SourceLocation(), NSIdent,
134 nullptr, nullptr, SourceLocation());
135 Ty = Context.getObjCInterfaceType(NSStringIDecl);
136 Context.setObjCNSStringType(Ty);
137 }
138 Ty = Context.getObjCObjectPointerType(Ty);
139 }
140 }
141
142 return new (Context) ObjCStringLiteral(S, Ty, AtLoc);
143 }
144
145 /// Emits an error if the given method does not exist, or if the return
146 /// type is not an Objective-C object.
validateBoxingMethod(Sema & S,SourceLocation Loc,const ObjCInterfaceDecl * Class,Selector Sel,const ObjCMethodDecl * Method)147 static bool validateBoxingMethod(Sema &S, SourceLocation Loc,
148 const ObjCInterfaceDecl *Class,
149 Selector Sel, const ObjCMethodDecl *Method) {
150 if (!Method) {
151 // FIXME: Is there a better way to avoid quotes than using getName()?
152 S.Diag(Loc, diag::err_undeclared_boxing_method) << Sel << Class->getName();
153 return false;
154 }
155
156 // Make sure the return type is reasonable.
157 QualType ReturnType = Method->getReturnType();
158 if (!ReturnType->isObjCObjectPointerType()) {
159 S.Diag(Loc, diag::err_objc_literal_method_sig)
160 << Sel;
161 S.Diag(Method->getLocation(), diag::note_objc_literal_method_return)
162 << ReturnType;
163 return false;
164 }
165
166 return true;
167 }
168
169 /// Maps ObjCLiteralKind to NSClassIdKindKind
ClassKindFromLiteralKind(Sema::ObjCLiteralKind LiteralKind)170 static NSAPI::NSClassIdKindKind ClassKindFromLiteralKind(
171 Sema::ObjCLiteralKind LiteralKind) {
172 switch (LiteralKind) {
173 case Sema::LK_Array:
174 return NSAPI::ClassId_NSArray;
175 case Sema::LK_Dictionary:
176 return NSAPI::ClassId_NSDictionary;
177 case Sema::LK_Numeric:
178 return NSAPI::ClassId_NSNumber;
179 case Sema::LK_String:
180 return NSAPI::ClassId_NSString;
181 case Sema::LK_Boxed:
182 return NSAPI::ClassId_NSValue;
183
184 // there is no corresponding matching
185 // between LK_None/LK_Block and NSClassIdKindKind
186 case Sema::LK_Block:
187 case Sema::LK_None:
188 break;
189 }
190 llvm_unreachable("LiteralKind can't be converted into a ClassKind");
191 }
192
193 /// Validates ObjCInterfaceDecl availability.
194 /// ObjCInterfaceDecl, used to create ObjC literals, should be defined
195 /// if clang not in a debugger mode.
ValidateObjCLiteralInterfaceDecl(Sema & S,ObjCInterfaceDecl * Decl,SourceLocation Loc,Sema::ObjCLiteralKind LiteralKind)196 static bool ValidateObjCLiteralInterfaceDecl(Sema &S, ObjCInterfaceDecl *Decl,
197 SourceLocation Loc,
198 Sema::ObjCLiteralKind LiteralKind) {
199 if (!Decl) {
200 NSAPI::NSClassIdKindKind Kind = ClassKindFromLiteralKind(LiteralKind);
201 IdentifierInfo *II = S.NSAPIObj->getNSClassId(Kind);
202 S.Diag(Loc, diag::err_undeclared_objc_literal_class)
203 << II->getName() << LiteralKind;
204 return false;
205 } else if (!Decl->hasDefinition() && !S.getLangOpts().DebuggerObjCLiteral) {
206 S.Diag(Loc, diag::err_undeclared_objc_literal_class)
207 << Decl->getName() << LiteralKind;
208 S.Diag(Decl->getLocation(), diag::note_forward_class);
209 return false;
210 }
211
212 return true;
213 }
214
215 /// Looks up ObjCInterfaceDecl of a given NSClassIdKindKind.
216 /// Used to create ObjC literals, such as NSDictionary (@{}),
217 /// NSArray (@[]) and Boxed Expressions (@())
LookupObjCInterfaceDeclForLiteral(Sema & S,SourceLocation Loc,Sema::ObjCLiteralKind LiteralKind)218 static ObjCInterfaceDecl *LookupObjCInterfaceDeclForLiteral(Sema &S,
219 SourceLocation Loc,
220 Sema::ObjCLiteralKind LiteralKind) {
221 NSAPI::NSClassIdKindKind ClassKind = ClassKindFromLiteralKind(LiteralKind);
222 IdentifierInfo *II = S.NSAPIObj->getNSClassId(ClassKind);
223 NamedDecl *IF = S.LookupSingleName(S.TUScope, II, Loc,
224 Sema::LookupOrdinaryName);
225 ObjCInterfaceDecl *ID = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
226 if (!ID && S.getLangOpts().DebuggerObjCLiteral) {
227 ASTContext &Context = S.Context;
228 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
229 ID = ObjCInterfaceDecl::Create (Context, TU, SourceLocation(), II,
230 nullptr, nullptr, SourceLocation());
231 }
232
233 if (!ValidateObjCLiteralInterfaceDecl(S, ID, Loc, LiteralKind)) {
234 ID = nullptr;
235 }
236
237 return ID;
238 }
239
240 /// Retrieve the NSNumber factory method that should be used to create
241 /// an Objective-C literal for the given type.
getNSNumberFactoryMethod(Sema & S,SourceLocation Loc,QualType NumberType,bool isLiteral=false,SourceRange R=SourceRange ())242 static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc,
243 QualType NumberType,
244 bool isLiteral = false,
245 SourceRange R = SourceRange()) {
246 Optional<NSAPI::NSNumberLiteralMethodKind> Kind =
247 S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType);
248
249 if (!Kind) {
250 if (isLiteral) {
251 S.Diag(Loc, diag::err_invalid_nsnumber_type)
252 << NumberType << R;
253 }
254 return nullptr;
255 }
256
257 // If we already looked up this method, we're done.
258 if (S.NSNumberLiteralMethods[*Kind])
259 return S.NSNumberLiteralMethods[*Kind];
260
261 Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind,
262 /*Instance=*/false);
263
264 ASTContext &CX = S.Context;
265
266 // Look up the NSNumber class, if we haven't done so already. It's cached
267 // in the Sema instance.
268 if (!S.NSNumberDecl) {
269 S.NSNumberDecl = LookupObjCInterfaceDeclForLiteral(S, Loc,
270 Sema::LK_Numeric);
271 if (!S.NSNumberDecl) {
272 return nullptr;
273 }
274 }
275
276 if (S.NSNumberPointer.isNull()) {
277 // generate the pointer to NSNumber type.
278 QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl);
279 S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject);
280 }
281
282 // Look for the appropriate method within NSNumber.
283 ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);
284 if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
285 // create a stub definition this NSNumber factory method.
286 TypeSourceInfo *ReturnTInfo = nullptr;
287 Method =
288 ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel,
289 S.NSNumberPointer, ReturnTInfo, S.NSNumberDecl,
290 /*isInstance=*/false, /*isVariadic=*/false,
291 /*isPropertyAccessor=*/false,
292 /*isSynthesizedAccessorStub=*/false,
293 /*isImplicitlyDeclared=*/true,
294 /*isDefined=*/false, ObjCMethodDecl::Required,
295 /*HasRelatedResultType=*/false);
296 ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method,
297 SourceLocation(), SourceLocation(),
298 &CX.Idents.get("value"),
299 NumberType, /*TInfo=*/nullptr,
300 SC_None, nullptr);
301 Method->setMethodParams(S.Context, value, None);
302 }
303
304 if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method))
305 return nullptr;
306
307 // Note: if the parameter type is out-of-line, we'll catch it later in the
308 // implicit conversion.
309
310 S.NSNumberLiteralMethods[*Kind] = Method;
311 return Method;
312 }
313
314 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
315 /// numeric literal expression. Type of the expression will be "NSNumber *".
BuildObjCNumericLiteral(SourceLocation AtLoc,Expr * Number)316 ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
317 // Determine the type of the literal.
318 QualType NumberType = Number->getType();
319 if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
320 // In C, character literals have type 'int'. That's not the type we want
321 // to use to determine the Objective-c literal kind.
322 switch (Char->getKind()) {
323 case CharacterLiteral::Ascii:
324 case CharacterLiteral::UTF8:
325 NumberType = Context.CharTy;
326 break;
327
328 case CharacterLiteral::Wide:
329 NumberType = Context.getWideCharType();
330 break;
331
332 case CharacterLiteral::UTF16:
333 NumberType = Context.Char16Ty;
334 break;
335
336 case CharacterLiteral::UTF32:
337 NumberType = Context.Char32Ty;
338 break;
339 }
340 }
341
342 // Look for the appropriate method within NSNumber.
343 // Construct the literal.
344 SourceRange NR(Number->getSourceRange());
345 ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType,
346 true, NR);
347 if (!Method)
348 return ExprError();
349
350 // Convert the number to the type that the parameter expects.
351 ParmVarDecl *ParamDecl = Method->parameters()[0];
352 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
353 ParamDecl);
354 ExprResult ConvertedNumber = PerformCopyInitialization(Entity,
355 SourceLocation(),
356 Number);
357 if (ConvertedNumber.isInvalid())
358 return ExprError();
359 Number = ConvertedNumber.get();
360
361 // Use the effective source range of the literal, including the leading '@'.
362 return MaybeBindToTemporary(
363 new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method,
364 SourceRange(AtLoc, NR.getEnd())));
365 }
366
ActOnObjCBoolLiteral(SourceLocation AtLoc,SourceLocation ValueLoc,bool Value)367 ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
368 SourceLocation ValueLoc,
369 bool Value) {
370 ExprResult Inner;
371 if (getLangOpts().CPlusPlus) {
372 Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
373 } else {
374 // C doesn't actually have a way to represent literal values of type
375 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
376 Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
377 Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
378 CK_IntegralToBoolean);
379 }
380
381 return BuildObjCNumericLiteral(AtLoc, Inner.get());
382 }
383
384 /// Check that the given expression is a valid element of an Objective-C
385 /// collection literal.
CheckObjCCollectionLiteralElement(Sema & S,Expr * Element,QualType T,bool ArrayLiteral=false)386 static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element,
387 QualType T,
388 bool ArrayLiteral = false) {
389 // If the expression is type-dependent, there's nothing for us to do.
390 if (Element->isTypeDependent())
391 return Element;
392
393 ExprResult Result = S.CheckPlaceholderExpr(Element);
394 if (Result.isInvalid())
395 return ExprError();
396 Element = Result.get();
397
398 // In C++, check for an implicit conversion to an Objective-C object pointer
399 // type.
400 if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
401 InitializedEntity Entity
402 = InitializedEntity::InitializeParameter(S.Context, T,
403 /*Consumed=*/false);
404 InitializationKind Kind = InitializationKind::CreateCopy(
405 Element->getBeginLoc(), SourceLocation());
406 InitializationSequence Seq(S, Entity, Kind, Element);
407 if (!Seq.Failed())
408 return Seq.Perform(S, Entity, Kind, Element);
409 }
410
411 Expr *OrigElement = Element;
412
413 // Perform lvalue-to-rvalue conversion.
414 Result = S.DefaultLvalueConversion(Element);
415 if (Result.isInvalid())
416 return ExprError();
417 Element = Result.get();
418
419 // Make sure that we have an Objective-C pointer type or block.
420 if (!Element->getType()->isObjCObjectPointerType() &&
421 !Element->getType()->isBlockPointerType()) {
422 bool Recovered = false;
423
424 // If this is potentially an Objective-C numeric literal, add the '@'.
425 if (isa<IntegerLiteral>(OrigElement) ||
426 isa<CharacterLiteral>(OrigElement) ||
427 isa<FloatingLiteral>(OrigElement) ||
428 isa<ObjCBoolLiteralExpr>(OrigElement) ||
429 isa<CXXBoolLiteralExpr>(OrigElement)) {
430 if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
431 int Which = isa<CharacterLiteral>(OrigElement) ? 1
432 : (isa<CXXBoolLiteralExpr>(OrigElement) ||
433 isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
434 : 3;
435
436 S.Diag(OrigElement->getBeginLoc(), diag::err_box_literal_collection)
437 << Which << OrigElement->getSourceRange()
438 << FixItHint::CreateInsertion(OrigElement->getBeginLoc(), "@");
439
440 Result =
441 S.BuildObjCNumericLiteral(OrigElement->getBeginLoc(), OrigElement);
442 if (Result.isInvalid())
443 return ExprError();
444
445 Element = Result.get();
446 Recovered = true;
447 }
448 }
449 // If this is potentially an Objective-C string literal, add the '@'.
450 else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
451 if (String->isAscii()) {
452 S.Diag(OrigElement->getBeginLoc(), diag::err_box_literal_collection)
453 << 0 << OrigElement->getSourceRange()
454 << FixItHint::CreateInsertion(OrigElement->getBeginLoc(), "@");
455
456 Result = S.BuildObjCStringLiteral(OrigElement->getBeginLoc(), String);
457 if (Result.isInvalid())
458 return ExprError();
459
460 Element = Result.get();
461 Recovered = true;
462 }
463 }
464
465 if (!Recovered) {
466 S.Diag(Element->getBeginLoc(), diag::err_invalid_collection_element)
467 << Element->getType();
468 return ExprError();
469 }
470 }
471 if (ArrayLiteral)
472 if (ObjCStringLiteral *getString =
473 dyn_cast<ObjCStringLiteral>(OrigElement)) {
474 if (StringLiteral *SL = getString->getString()) {
475 unsigned numConcat = SL->getNumConcatenated();
476 if (numConcat > 1) {
477 // Only warn if the concatenated string doesn't come from a macro.
478 bool hasMacro = false;
479 for (unsigned i = 0; i < numConcat ; ++i)
480 if (SL->getStrTokenLoc(i).isMacroID()) {
481 hasMacro = true;
482 break;
483 }
484 if (!hasMacro)
485 S.Diag(Element->getBeginLoc(),
486 diag::warn_concatenated_nsarray_literal)
487 << Element->getType();
488 }
489 }
490 }
491
492 // Make sure that the element has the type that the container factory
493 // function expects.
494 return S.PerformCopyInitialization(
495 InitializedEntity::InitializeParameter(S.Context, T,
496 /*Consumed=*/false),
497 Element->getBeginLoc(), Element);
498 }
499
BuildObjCBoxedExpr(SourceRange SR,Expr * ValueExpr)500 ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
501 if (ValueExpr->isTypeDependent()) {
502 ObjCBoxedExpr *BoxedExpr =
503 new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, nullptr, SR);
504 return BoxedExpr;
505 }
506 ObjCMethodDecl *BoxingMethod = nullptr;
507 QualType BoxedType;
508 // Convert the expression to an RValue, so we can check for pointer types...
509 ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
510 if (RValue.isInvalid()) {
511 return ExprError();
512 }
513 SourceLocation Loc = SR.getBegin();
514 ValueExpr = RValue.get();
515 QualType ValueType(ValueExpr->getType());
516 if (const PointerType *PT = ValueType->getAs<PointerType>()) {
517 QualType PointeeType = PT->getPointeeType();
518 if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
519
520 if (!NSStringDecl) {
521 NSStringDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
522 Sema::LK_String);
523 if (!NSStringDecl) {
524 return ExprError();
525 }
526 QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl);
527 NSStringPointer = Context.getObjCObjectPointerType(NSStringObject);
528 }
529
530 // The boxed expression can be emitted as a compile time constant if it is
531 // a string literal whose character encoding is compatible with UTF-8.
532 if (auto *CE = dyn_cast<ImplicitCastExpr>(ValueExpr))
533 if (CE->getCastKind() == CK_ArrayToPointerDecay)
534 if (auto *SL =
535 dyn_cast<StringLiteral>(CE->getSubExpr()->IgnoreParens())) {
536 assert((SL->isAscii() || SL->isUTF8()) &&
537 "unexpected character encoding");
538 StringRef Str = SL->getString();
539 const llvm::UTF8 *StrBegin = Str.bytes_begin();
540 const llvm::UTF8 *StrEnd = Str.bytes_end();
541 // Check that this is a valid UTF-8 string.
542 if (llvm::isLegalUTF8String(&StrBegin, StrEnd)) {
543 BoxedType = Context.getAttributedType(
544 AttributedType::getNullabilityAttrKind(
545 NullabilityKind::NonNull),
546 NSStringPointer, NSStringPointer);
547 return new (Context) ObjCBoxedExpr(CE, BoxedType, nullptr, SR);
548 }
549
550 Diag(SL->getBeginLoc(), diag::warn_objc_boxing_invalid_utf8_string)
551 << NSStringPointer << SL->getSourceRange();
552 }
553
554 if (!StringWithUTF8StringMethod) {
555 IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
556 Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
557
558 // Look for the appropriate method within NSString.
559 BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
560 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
561 // Debugger needs to work even if NSString hasn't been defined.
562 TypeSourceInfo *ReturnTInfo = nullptr;
563 ObjCMethodDecl *M = ObjCMethodDecl::Create(
564 Context, SourceLocation(), SourceLocation(), stringWithUTF8String,
565 NSStringPointer, ReturnTInfo, NSStringDecl,
566 /*isInstance=*/false, /*isVariadic=*/false,
567 /*isPropertyAccessor=*/false,
568 /*isSynthesizedAccessorStub=*/false,
569 /*isImplicitlyDeclared=*/true,
570 /*isDefined=*/false, ObjCMethodDecl::Required,
571 /*HasRelatedResultType=*/false);
572 QualType ConstCharType = Context.CharTy.withConst();
573 ParmVarDecl *value =
574 ParmVarDecl::Create(Context, M,
575 SourceLocation(), SourceLocation(),
576 &Context.Idents.get("value"),
577 Context.getPointerType(ConstCharType),
578 /*TInfo=*/nullptr,
579 SC_None, nullptr);
580 M->setMethodParams(Context, value, None);
581 BoxingMethod = M;
582 }
583
584 if (!validateBoxingMethod(*this, Loc, NSStringDecl,
585 stringWithUTF8String, BoxingMethod))
586 return ExprError();
587
588 StringWithUTF8StringMethod = BoxingMethod;
589 }
590
591 BoxingMethod = StringWithUTF8StringMethod;
592 BoxedType = NSStringPointer;
593 // Transfer the nullability from method's return type.
594 Optional<NullabilityKind> Nullability =
595 BoxingMethod->getReturnType()->getNullability(Context);
596 if (Nullability)
597 BoxedType = Context.getAttributedType(
598 AttributedType::getNullabilityAttrKind(*Nullability), BoxedType,
599 BoxedType);
600 }
601 } else if (ValueType->isBuiltinType()) {
602 // The other types we support are numeric, char and BOOL/bool. We could also
603 // provide limited support for structure types, such as NSRange, NSRect, and
604 // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
605 // for more details.
606
607 // Check for a top-level character literal.
608 if (const CharacterLiteral *Char =
609 dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
610 // In C, character literals have type 'int'. That's not the type we want
611 // to use to determine the Objective-c literal kind.
612 switch (Char->getKind()) {
613 case CharacterLiteral::Ascii:
614 case CharacterLiteral::UTF8:
615 ValueType = Context.CharTy;
616 break;
617
618 case CharacterLiteral::Wide:
619 ValueType = Context.getWideCharType();
620 break;
621
622 case CharacterLiteral::UTF16:
623 ValueType = Context.Char16Ty;
624 break;
625
626 case CharacterLiteral::UTF32:
627 ValueType = Context.Char32Ty;
628 break;
629 }
630 }
631 // FIXME: Do I need to do anything special with BoolTy expressions?
632
633 // Look for the appropriate method within NSNumber.
634 BoxingMethod = getNSNumberFactoryMethod(*this, Loc, ValueType);
635 BoxedType = NSNumberPointer;
636 } else if (const EnumType *ET = ValueType->getAs<EnumType>()) {
637 if (!ET->getDecl()->isComplete()) {
638 Diag(Loc, diag::err_objc_incomplete_boxed_expression_type)
639 << ValueType << ValueExpr->getSourceRange();
640 return ExprError();
641 }
642
643 BoxingMethod = getNSNumberFactoryMethod(*this, Loc,
644 ET->getDecl()->getIntegerType());
645 BoxedType = NSNumberPointer;
646 } else if (ValueType->isObjCBoxableRecordType()) {
647 // Support for structure types, that marked as objc_boxable
648 // struct __attribute__((objc_boxable)) s { ... };
649
650 // Look up the NSValue class, if we haven't done so already. It's cached
651 // in the Sema instance.
652 if (!NSValueDecl) {
653 NSValueDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
654 Sema::LK_Boxed);
655 if (!NSValueDecl) {
656 return ExprError();
657 }
658
659 // generate the pointer to NSValue type.
660 QualType NSValueObject = Context.getObjCInterfaceType(NSValueDecl);
661 NSValuePointer = Context.getObjCObjectPointerType(NSValueObject);
662 }
663
664 if (!ValueWithBytesObjCTypeMethod) {
665 IdentifierInfo *II[] = {
666 &Context.Idents.get("valueWithBytes"),
667 &Context.Idents.get("objCType")
668 };
669 Selector ValueWithBytesObjCType = Context.Selectors.getSelector(2, II);
670
671 // Look for the appropriate method within NSValue.
672 BoxingMethod = NSValueDecl->lookupClassMethod(ValueWithBytesObjCType);
673 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
674 // Debugger needs to work even if NSValue hasn't been defined.
675 TypeSourceInfo *ReturnTInfo = nullptr;
676 ObjCMethodDecl *M = ObjCMethodDecl::Create(
677 Context, SourceLocation(), SourceLocation(), ValueWithBytesObjCType,
678 NSValuePointer, ReturnTInfo, NSValueDecl,
679 /*isInstance=*/false,
680 /*isVariadic=*/false,
681 /*isPropertyAccessor=*/false,
682 /*isSynthesizedAccessorStub=*/false,
683 /*isImplicitlyDeclared=*/true,
684 /*isDefined=*/false, ObjCMethodDecl::Required,
685 /*HasRelatedResultType=*/false);
686
687 SmallVector<ParmVarDecl *, 2> Params;
688
689 ParmVarDecl *bytes =
690 ParmVarDecl::Create(Context, M,
691 SourceLocation(), SourceLocation(),
692 &Context.Idents.get("bytes"),
693 Context.VoidPtrTy.withConst(),
694 /*TInfo=*/nullptr,
695 SC_None, nullptr);
696 Params.push_back(bytes);
697
698 QualType ConstCharType = Context.CharTy.withConst();
699 ParmVarDecl *type =
700 ParmVarDecl::Create(Context, M,
701 SourceLocation(), SourceLocation(),
702 &Context.Idents.get("type"),
703 Context.getPointerType(ConstCharType),
704 /*TInfo=*/nullptr,
705 SC_None, nullptr);
706 Params.push_back(type);
707
708 M->setMethodParams(Context, Params, None);
709 BoxingMethod = M;
710 }
711
712 if (!validateBoxingMethod(*this, Loc, NSValueDecl,
713 ValueWithBytesObjCType, BoxingMethod))
714 return ExprError();
715
716 ValueWithBytesObjCTypeMethod = BoxingMethod;
717 }
718
719 if (!ValueType.isTriviallyCopyableType(Context)) {
720 Diag(Loc, diag::err_objc_non_trivially_copyable_boxed_expression_type)
721 << ValueType << ValueExpr->getSourceRange();
722 return ExprError();
723 }
724
725 BoxingMethod = ValueWithBytesObjCTypeMethod;
726 BoxedType = NSValuePointer;
727 }
728
729 if (!BoxingMethod) {
730 Diag(Loc, diag::err_objc_illegal_boxed_expression_type)
731 << ValueType << ValueExpr->getSourceRange();
732 return ExprError();
733 }
734
735 DiagnoseUseOfDecl(BoxingMethod, Loc);
736
737 ExprResult ConvertedValueExpr;
738 if (ValueType->isObjCBoxableRecordType()) {
739 InitializedEntity IE = InitializedEntity::InitializeTemporary(ValueType);
740 ConvertedValueExpr = PerformCopyInitialization(IE, ValueExpr->getExprLoc(),
741 ValueExpr);
742 } else {
743 // Convert the expression to the type that the parameter requires.
744 ParmVarDecl *ParamDecl = BoxingMethod->parameters()[0];
745 InitializedEntity IE = InitializedEntity::InitializeParameter(Context,
746 ParamDecl);
747 ConvertedValueExpr = PerformCopyInitialization(IE, SourceLocation(),
748 ValueExpr);
749 }
750
751 if (ConvertedValueExpr.isInvalid())
752 return ExprError();
753 ValueExpr = ConvertedValueExpr.get();
754
755 ObjCBoxedExpr *BoxedExpr =
756 new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
757 BoxingMethod, SR);
758 return MaybeBindToTemporary(BoxedExpr);
759 }
760
761 /// Build an ObjC subscript pseudo-object expression, given that
762 /// that's supported by the runtime.
BuildObjCSubscriptExpression(SourceLocation RB,Expr * BaseExpr,Expr * IndexExpr,ObjCMethodDecl * getterMethod,ObjCMethodDecl * setterMethod)763 ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
764 Expr *IndexExpr,
765 ObjCMethodDecl *getterMethod,
766 ObjCMethodDecl *setterMethod) {
767 assert(!LangOpts.isSubscriptPointerArithmetic());
768
769 // We can't get dependent types here; our callers should have
770 // filtered them out.
771 assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
772 "base or index cannot have dependent type here");
773
774 // Filter out placeholders in the index. In theory, overloads could
775 // be preserved here, although that might not actually work correctly.
776 ExprResult Result = CheckPlaceholderExpr(IndexExpr);
777 if (Result.isInvalid())
778 return ExprError();
779 IndexExpr = Result.get();
780
781 // Perform lvalue-to-rvalue conversion on the base.
782 Result = DefaultLvalueConversion(BaseExpr);
783 if (Result.isInvalid())
784 return ExprError();
785 BaseExpr = Result.get();
786
787 // Build the pseudo-object expression.
788 return new (Context) ObjCSubscriptRefExpr(
789 BaseExpr, IndexExpr, Context.PseudoObjectTy, VK_LValue, OK_ObjCSubscript,
790 getterMethod, setterMethod, RB);
791 }
792
BuildObjCArrayLiteral(SourceRange SR,MultiExprArg Elements)793 ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
794 SourceLocation Loc = SR.getBegin();
795
796 if (!NSArrayDecl) {
797 NSArrayDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
798 Sema::LK_Array);
799 if (!NSArrayDecl) {
800 return ExprError();
801 }
802 }
803
804 // Find the arrayWithObjects:count: method, if we haven't done so already.
805 QualType IdT = Context.getObjCIdType();
806 if (!ArrayWithObjectsMethod) {
807 Selector
808 Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
809 ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel);
810 if (!Method && getLangOpts().DebuggerObjCLiteral) {
811 TypeSourceInfo *ReturnTInfo = nullptr;
812 Method = ObjCMethodDecl::Create(
813 Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo,
814 Context.getTranslationUnitDecl(), false /*Instance*/,
815 false /*isVariadic*/,
816 /*isPropertyAccessor=*/false, /*isSynthesizedAccessorStub=*/false,
817 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
818 ObjCMethodDecl::Required, false);
819 SmallVector<ParmVarDecl *, 2> Params;
820 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
821 SourceLocation(),
822 SourceLocation(),
823 &Context.Idents.get("objects"),
824 Context.getPointerType(IdT),
825 /*TInfo=*/nullptr,
826 SC_None, nullptr);
827 Params.push_back(objects);
828 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
829 SourceLocation(),
830 SourceLocation(),
831 &Context.Idents.get("cnt"),
832 Context.UnsignedLongTy,
833 /*TInfo=*/nullptr, SC_None,
834 nullptr);
835 Params.push_back(cnt);
836 Method->setMethodParams(Context, Params, None);
837 }
838
839 if (!validateBoxingMethod(*this, Loc, NSArrayDecl, Sel, Method))
840 return ExprError();
841
842 // Dig out the type that all elements should be converted to.
843 QualType T = Method->parameters()[0]->getType();
844 const PointerType *PtrT = T->getAs<PointerType>();
845 if (!PtrT ||
846 !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
847 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
848 << Sel;
849 Diag(Method->parameters()[0]->getLocation(),
850 diag::note_objc_literal_method_param)
851 << 0 << T
852 << Context.getPointerType(IdT.withConst());
853 return ExprError();
854 }
855
856 // Check that the 'count' parameter is integral.
857 if (!Method->parameters()[1]->getType()->isIntegerType()) {
858 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
859 << Sel;
860 Diag(Method->parameters()[1]->getLocation(),
861 diag::note_objc_literal_method_param)
862 << 1
863 << Method->parameters()[1]->getType()
864 << "integral";
865 return ExprError();
866 }
867
868 // We've found a good +arrayWithObjects:count: method. Save it!
869 ArrayWithObjectsMethod = Method;
870 }
871
872 QualType ObjectsType = ArrayWithObjectsMethod->parameters()[0]->getType();
873 QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
874
875 // Check that each of the elements provided is valid in a collection literal,
876 // performing conversions as necessary.
877 Expr **ElementsBuffer = Elements.data();
878 for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
879 ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
880 ElementsBuffer[I],
881 RequiredType, true);
882 if (Converted.isInvalid())
883 return ExprError();
884
885 ElementsBuffer[I] = Converted.get();
886 }
887
888 QualType Ty
889 = Context.getObjCObjectPointerType(
890 Context.getObjCInterfaceType(NSArrayDecl));
891
892 return MaybeBindToTemporary(
893 ObjCArrayLiteral::Create(Context, Elements, Ty,
894 ArrayWithObjectsMethod, SR));
895 }
896
897 /// Check for duplicate keys in an ObjC dictionary literal. For instance:
898 /// NSDictionary *nd = @{ @"foo" : @"bar", @"foo" : @"baz" };
899 static void
CheckObjCDictionaryLiteralDuplicateKeys(Sema & S,ObjCDictionaryLiteral * Literal)900 CheckObjCDictionaryLiteralDuplicateKeys(Sema &S,
901 ObjCDictionaryLiteral *Literal) {
902 if (Literal->isValueDependent() || Literal->isTypeDependent())
903 return;
904
905 // NSNumber has quite relaxed equality semantics (for instance, @YES is
906 // considered equal to @1.0). For now, ignore floating points and just do a
907 // bit-width and sign agnostic integer compare.
908 struct APSIntCompare {
909 bool operator()(const llvm::APSInt &LHS, const llvm::APSInt &RHS) const {
910 return llvm::APSInt::compareValues(LHS, RHS) < 0;
911 }
912 };
913
914 llvm::DenseMap<StringRef, SourceLocation> StringKeys;
915 std::map<llvm::APSInt, SourceLocation, APSIntCompare> IntegralKeys;
916
917 auto checkOneKey = [&](auto &Map, const auto &Key, SourceLocation Loc) {
918 auto Pair = Map.insert({Key, Loc});
919 if (!Pair.second) {
920 S.Diag(Loc, diag::warn_nsdictionary_duplicate_key);
921 S.Diag(Pair.first->second, diag::note_nsdictionary_duplicate_key_here);
922 }
923 };
924
925 for (unsigned Idx = 0, End = Literal->getNumElements(); Idx != End; ++Idx) {
926 Expr *Key = Literal->getKeyValueElement(Idx).Key->IgnoreParenImpCasts();
927
928 if (auto *StrLit = dyn_cast<ObjCStringLiteral>(Key)) {
929 StringRef Bytes = StrLit->getString()->getBytes();
930 SourceLocation Loc = StrLit->getExprLoc();
931 checkOneKey(StringKeys, Bytes, Loc);
932 }
933
934 if (auto *BE = dyn_cast<ObjCBoxedExpr>(Key)) {
935 Expr *Boxed = BE->getSubExpr();
936 SourceLocation Loc = BE->getExprLoc();
937
938 // Check for @("foo").
939 if (auto *Str = dyn_cast<StringLiteral>(Boxed->IgnoreParenImpCasts())) {
940 checkOneKey(StringKeys, Str->getBytes(), Loc);
941 continue;
942 }
943
944 Expr::EvalResult Result;
945 if (Boxed->EvaluateAsInt(Result, S.getASTContext(),
946 Expr::SE_AllowSideEffects)) {
947 checkOneKey(IntegralKeys, Result.Val.getInt(), Loc);
948 }
949 }
950 }
951 }
952
BuildObjCDictionaryLiteral(SourceRange SR,MutableArrayRef<ObjCDictionaryElement> Elements)953 ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
954 MutableArrayRef<ObjCDictionaryElement> Elements) {
955 SourceLocation Loc = SR.getBegin();
956
957 if (!NSDictionaryDecl) {
958 NSDictionaryDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
959 Sema::LK_Dictionary);
960 if (!NSDictionaryDecl) {
961 return ExprError();
962 }
963 }
964
965 // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
966 // so already.
967 QualType IdT = Context.getObjCIdType();
968 if (!DictionaryWithObjectsMethod) {
969 Selector Sel = NSAPIObj->getNSDictionarySelector(
970 NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
971 ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
972 if (!Method && getLangOpts().DebuggerObjCLiteral) {
973 Method = ObjCMethodDecl::Create(
974 Context, SourceLocation(), SourceLocation(), Sel, IdT,
975 nullptr /*TypeSourceInfo */, Context.getTranslationUnitDecl(),
976 false /*Instance*/, false /*isVariadic*/,
977 /*isPropertyAccessor=*/false,
978 /*isSynthesizedAccessorStub=*/false,
979 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
980 ObjCMethodDecl::Required, false);
981 SmallVector<ParmVarDecl *, 3> Params;
982 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
983 SourceLocation(),
984 SourceLocation(),
985 &Context.Idents.get("objects"),
986 Context.getPointerType(IdT),
987 /*TInfo=*/nullptr, SC_None,
988 nullptr);
989 Params.push_back(objects);
990 ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
991 SourceLocation(),
992 SourceLocation(),
993 &Context.Idents.get("keys"),
994 Context.getPointerType(IdT),
995 /*TInfo=*/nullptr, SC_None,
996 nullptr);
997 Params.push_back(keys);
998 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
999 SourceLocation(),
1000 SourceLocation(),
1001 &Context.Idents.get("cnt"),
1002 Context.UnsignedLongTy,
1003 /*TInfo=*/nullptr, SC_None,
1004 nullptr);
1005 Params.push_back(cnt);
1006 Method->setMethodParams(Context, Params, None);
1007 }
1008
1009 if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
1010 Method))
1011 return ExprError();
1012
1013 // Dig out the type that all values should be converted to.
1014 QualType ValueT = Method->parameters()[0]->getType();
1015 const PointerType *PtrValue = ValueT->getAs<PointerType>();
1016 if (!PtrValue ||
1017 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
1018 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
1019 << Sel;
1020 Diag(Method->parameters()[0]->getLocation(),
1021 diag::note_objc_literal_method_param)
1022 << 0 << ValueT
1023 << Context.getPointerType(IdT.withConst());
1024 return ExprError();
1025 }
1026
1027 // Dig out the type that all keys should be converted to.
1028 QualType KeyT = Method->parameters()[1]->getType();
1029 const PointerType *PtrKey = KeyT->getAs<PointerType>();
1030 if (!PtrKey ||
1031 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
1032 IdT)) {
1033 bool err = true;
1034 if (PtrKey) {
1035 if (QIDNSCopying.isNull()) {
1036 // key argument of selector is id<NSCopying>?
1037 if (ObjCProtocolDecl *NSCopyingPDecl =
1038 LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
1039 ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
1040 QIDNSCopying =
1041 Context.getObjCObjectType(Context.ObjCBuiltinIdTy, { },
1042 llvm::makeArrayRef(
1043 (ObjCProtocolDecl**) PQ,
1044 1),
1045 false);
1046 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
1047 }
1048 }
1049 if (!QIDNSCopying.isNull())
1050 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
1051 QIDNSCopying);
1052 }
1053
1054 if (err) {
1055 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
1056 << Sel;
1057 Diag(Method->parameters()[1]->getLocation(),
1058 diag::note_objc_literal_method_param)
1059 << 1 << KeyT
1060 << Context.getPointerType(IdT.withConst());
1061 return ExprError();
1062 }
1063 }
1064
1065 // Check that the 'count' parameter is integral.
1066 QualType CountType = Method->parameters()[2]->getType();
1067 if (!CountType->isIntegerType()) {
1068 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
1069 << Sel;
1070 Diag(Method->parameters()[2]->getLocation(),
1071 diag::note_objc_literal_method_param)
1072 << 2 << CountType
1073 << "integral";
1074 return ExprError();
1075 }
1076
1077 // We've found a good +dictionaryWithObjects:keys:count: method; save it!
1078 DictionaryWithObjectsMethod = Method;
1079 }
1080
1081 QualType ValuesT = DictionaryWithObjectsMethod->parameters()[0]->getType();
1082 QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
1083 QualType KeysT = DictionaryWithObjectsMethod->parameters()[1]->getType();
1084 QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
1085
1086 // Check that each of the keys and values provided is valid in a collection
1087 // literal, performing conversions as necessary.
1088 bool HasPackExpansions = false;
1089 for (ObjCDictionaryElement &Element : Elements) {
1090 // Check the key.
1091 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Element.Key,
1092 KeyT);
1093 if (Key.isInvalid())
1094 return ExprError();
1095
1096 // Check the value.
1097 ExprResult Value
1098 = CheckObjCCollectionLiteralElement(*this, Element.Value, ValueT);
1099 if (Value.isInvalid())
1100 return ExprError();
1101
1102 Element.Key = Key.get();
1103 Element.Value = Value.get();
1104
1105 if (Element.EllipsisLoc.isInvalid())
1106 continue;
1107
1108 if (!Element.Key->containsUnexpandedParameterPack() &&
1109 !Element.Value->containsUnexpandedParameterPack()) {
1110 Diag(Element.EllipsisLoc,
1111 diag::err_pack_expansion_without_parameter_packs)
1112 << SourceRange(Element.Key->getBeginLoc(),
1113 Element.Value->getEndLoc());
1114 return ExprError();
1115 }
1116
1117 HasPackExpansions = true;
1118 }
1119
1120 QualType Ty = Context.getObjCObjectPointerType(
1121 Context.getObjCInterfaceType(NSDictionaryDecl));
1122
1123 auto *Literal =
1124 ObjCDictionaryLiteral::Create(Context, Elements, HasPackExpansions, Ty,
1125 DictionaryWithObjectsMethod, SR);
1126 CheckObjCDictionaryLiteralDuplicateKeys(*this, Literal);
1127 return MaybeBindToTemporary(Literal);
1128 }
1129
BuildObjCEncodeExpression(SourceLocation AtLoc,TypeSourceInfo * EncodedTypeInfo,SourceLocation RParenLoc)1130 ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
1131 TypeSourceInfo *EncodedTypeInfo,
1132 SourceLocation RParenLoc) {
1133 QualType EncodedType = EncodedTypeInfo->getType();
1134 QualType StrTy;
1135 if (EncodedType->isDependentType())
1136 StrTy = Context.DependentTy;
1137 else {
1138 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
1139 !EncodedType->isVoidType()) // void is handled too.
1140 if (RequireCompleteType(AtLoc, EncodedType,
1141 diag::err_incomplete_type_objc_at_encode,
1142 EncodedTypeInfo->getTypeLoc()))
1143 return ExprError();
1144
1145 std::string Str;
1146 QualType NotEncodedT;
1147 Context.getObjCEncodingForType(EncodedType, Str, nullptr, &NotEncodedT);
1148 if (!NotEncodedT.isNull())
1149 Diag(AtLoc, diag::warn_incomplete_encoded_type)
1150 << EncodedType << NotEncodedT;
1151
1152 // The type of @encode is the same as the type of the corresponding string,
1153 // which is an array type.
1154 StrTy = Context.getStringLiteralArrayType(Context.CharTy, Str.size());
1155 }
1156
1157 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
1158 }
1159
ParseObjCEncodeExpression(SourceLocation AtLoc,SourceLocation EncodeLoc,SourceLocation LParenLoc,ParsedType ty,SourceLocation RParenLoc)1160 ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
1161 SourceLocation EncodeLoc,
1162 SourceLocation LParenLoc,
1163 ParsedType ty,
1164 SourceLocation RParenLoc) {
1165 // FIXME: Preserve type source info ?
1166 TypeSourceInfo *TInfo;
1167 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
1168 if (!TInfo)
1169 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
1170 getLocForEndOfToken(LParenLoc));
1171
1172 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
1173 }
1174
HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema & S,SourceLocation AtLoc,SourceLocation LParenLoc,SourceLocation RParenLoc,ObjCMethodDecl * Method,ObjCMethodList & MethList)1175 static bool HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S,
1176 SourceLocation AtLoc,
1177 SourceLocation LParenLoc,
1178 SourceLocation RParenLoc,
1179 ObjCMethodDecl *Method,
1180 ObjCMethodList &MethList) {
1181 ObjCMethodList *M = &MethList;
1182 bool Warned = false;
1183 for (M = M->getNext(); M; M=M->getNext()) {
1184 ObjCMethodDecl *MatchingMethodDecl = M->getMethod();
1185 if (MatchingMethodDecl == Method ||
1186 isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext()) ||
1187 MatchingMethodDecl->getSelector() != Method->getSelector())
1188 continue;
1189 if (!S.MatchTwoMethodDeclarations(Method,
1190 MatchingMethodDecl, Sema::MMS_loose)) {
1191 if (!Warned) {
1192 Warned = true;
1193 S.Diag(AtLoc, diag::warn_multiple_selectors)
1194 << Method->getSelector() << FixItHint::CreateInsertion(LParenLoc, "(")
1195 << FixItHint::CreateInsertion(RParenLoc, ")");
1196 S.Diag(Method->getLocation(), diag::note_method_declared_at)
1197 << Method->getDeclName();
1198 }
1199 S.Diag(MatchingMethodDecl->getLocation(), diag::note_method_declared_at)
1200 << MatchingMethodDecl->getDeclName();
1201 }
1202 }
1203 return Warned;
1204 }
1205
DiagnoseMismatchedSelectors(Sema & S,SourceLocation AtLoc,ObjCMethodDecl * Method,SourceLocation LParenLoc,SourceLocation RParenLoc,bool WarnMultipleSelectors)1206 static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc,
1207 ObjCMethodDecl *Method,
1208 SourceLocation LParenLoc,
1209 SourceLocation RParenLoc,
1210 bool WarnMultipleSelectors) {
1211 if (!WarnMultipleSelectors ||
1212 S.Diags.isIgnored(diag::warn_multiple_selectors, SourceLocation()))
1213 return;
1214 bool Warned = false;
1215 for (Sema::GlobalMethodPool::iterator b = S.MethodPool.begin(),
1216 e = S.MethodPool.end(); b != e; b++) {
1217 // first, instance methods
1218 ObjCMethodList &InstMethList = b->second.first;
1219 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
1220 Method, InstMethList))
1221 Warned = true;
1222
1223 // second, class methods
1224 ObjCMethodList &ClsMethList = b->second.second;
1225 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
1226 Method, ClsMethList) || Warned)
1227 return;
1228 }
1229 }
1230
LookupDirectMethodInMethodList(Sema & S,Selector Sel,ObjCMethodList & MethList,bool & onlyDirect,bool & anyDirect)1231 static ObjCMethodDecl *LookupDirectMethodInMethodList(Sema &S, Selector Sel,
1232 ObjCMethodList &MethList,
1233 bool &onlyDirect,
1234 bool &anyDirect) {
1235 (void)Sel;
1236 ObjCMethodList *M = &MethList;
1237 ObjCMethodDecl *DirectMethod = nullptr;
1238 for (; M; M = M->getNext()) {
1239 ObjCMethodDecl *Method = M->getMethod();
1240 if (!Method)
1241 continue;
1242 assert(Method->getSelector() == Sel && "Method with wrong selector in method list");
1243 if (Method->isDirectMethod()) {
1244 anyDirect = true;
1245 DirectMethod = Method;
1246 } else
1247 onlyDirect = false;
1248 }
1249
1250 return DirectMethod;
1251 }
1252
1253 // Search the global pool for (potentially) direct methods matching the given
1254 // selector. If a non-direct method is found, set \param onlyDirect to false. If
1255 // a direct method is found, set \param anyDirect to true. Returns a direct
1256 // method, if any.
LookupDirectMethodInGlobalPool(Sema & S,Selector Sel,bool & onlyDirect,bool & anyDirect)1257 static ObjCMethodDecl *LookupDirectMethodInGlobalPool(Sema &S, Selector Sel,
1258 bool &onlyDirect,
1259 bool &anyDirect) {
1260 auto Iter = S.MethodPool.find(Sel);
1261 if (Iter == S.MethodPool.end())
1262 return nullptr;
1263
1264 ObjCMethodDecl *DirectInstance = LookupDirectMethodInMethodList(
1265 S, Sel, Iter->second.first, onlyDirect, anyDirect);
1266 ObjCMethodDecl *DirectClass = LookupDirectMethodInMethodList(
1267 S, Sel, Iter->second.second, onlyDirect, anyDirect);
1268
1269 return DirectInstance ? DirectInstance : DirectClass;
1270 }
1271
findMethodInCurrentClass(Sema & S,Selector Sel)1272 static ObjCMethodDecl *findMethodInCurrentClass(Sema &S, Selector Sel) {
1273 auto *CurMD = S.getCurMethodDecl();
1274 if (!CurMD)
1275 return nullptr;
1276 ObjCInterfaceDecl *IFace = CurMD->getClassInterface();
1277
1278 // The language enforce that only one direct method is present in a given
1279 // class, so we just need to find one method in the current class to know
1280 // whether Sel is potentially direct in this context.
1281 if (ObjCMethodDecl *MD = IFace->lookupMethod(Sel, /*isInstance=*/true))
1282 return MD;
1283 if (ObjCMethodDecl *MD = IFace->lookupPrivateMethod(Sel, /*isInstance=*/true))
1284 return MD;
1285 if (ObjCMethodDecl *MD = IFace->lookupMethod(Sel, /*isInstance=*/false))
1286 return MD;
1287 if (ObjCMethodDecl *MD = IFace->lookupPrivateMethod(Sel, /*isInstance=*/false))
1288 return MD;
1289
1290 return nullptr;
1291 }
1292
ParseObjCSelectorExpression(Selector Sel,SourceLocation AtLoc,SourceLocation SelLoc,SourceLocation LParenLoc,SourceLocation RParenLoc,bool WarnMultipleSelectors)1293 ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
1294 SourceLocation AtLoc,
1295 SourceLocation SelLoc,
1296 SourceLocation LParenLoc,
1297 SourceLocation RParenLoc,
1298 bool WarnMultipleSelectors) {
1299 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
1300 SourceRange(LParenLoc, RParenLoc));
1301 if (!Method)
1302 Method = LookupFactoryMethodInGlobalPool(Sel,
1303 SourceRange(LParenLoc, RParenLoc));
1304 if (!Method) {
1305 if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) {
1306 Selector MatchedSel = OM->getSelector();
1307 SourceRange SelectorRange(LParenLoc.getLocWithOffset(1),
1308 RParenLoc.getLocWithOffset(-1));
1309 Diag(SelLoc, diag::warn_undeclared_selector_with_typo)
1310 << Sel << MatchedSel
1311 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1312
1313 } else
1314 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
1315 } else {
1316 DiagnoseMismatchedSelectors(*this, AtLoc, Method, LParenLoc, RParenLoc,
1317 WarnMultipleSelectors);
1318
1319 bool onlyDirect = true;
1320 bool anyDirect = false;
1321 ObjCMethodDecl *GlobalDirectMethod =
1322 LookupDirectMethodInGlobalPool(*this, Sel, onlyDirect, anyDirect);
1323
1324 if (onlyDirect) {
1325 Diag(AtLoc, diag::err_direct_selector_expression)
1326 << Method->getSelector();
1327 Diag(Method->getLocation(), diag::note_direct_method_declared_at)
1328 << Method->getDeclName();
1329 } else if (anyDirect) {
1330 // If we saw any direct methods, see if we see a direct member of the
1331 // current class. If so, the @selector will likely be used to refer to
1332 // this direct method.
1333 ObjCMethodDecl *LikelyTargetMethod = findMethodInCurrentClass(*this, Sel);
1334 if (LikelyTargetMethod && LikelyTargetMethod->isDirectMethod()) {
1335 Diag(AtLoc, diag::warn_potentially_direct_selector_expression) << Sel;
1336 Diag(LikelyTargetMethod->getLocation(),
1337 diag::note_direct_method_declared_at)
1338 << LikelyTargetMethod->getDeclName();
1339 } else if (!LikelyTargetMethod) {
1340 // Otherwise, emit the "strict" variant of this diagnostic, unless
1341 // LikelyTargetMethod is non-direct.
1342 Diag(AtLoc, diag::warn_strict_potentially_direct_selector_expression)
1343 << Sel;
1344 Diag(GlobalDirectMethod->getLocation(),
1345 diag::note_direct_method_declared_at)
1346 << GlobalDirectMethod->getDeclName();
1347 }
1348 }
1349 }
1350
1351 if (Method &&
1352 Method->getImplementationControl() != ObjCMethodDecl::Optional &&
1353 !getSourceManager().isInSystemHeader(Method->getLocation()))
1354 ReferencedSelectors.insert(std::make_pair(Sel, AtLoc));
1355
1356 // In ARC, forbid the user from using @selector for
1357 // retain/release/autorelease/dealloc/retainCount.
1358 if (getLangOpts().ObjCAutoRefCount) {
1359 switch (Sel.getMethodFamily()) {
1360 case OMF_retain:
1361 case OMF_release:
1362 case OMF_autorelease:
1363 case OMF_retainCount:
1364 case OMF_dealloc:
1365 Diag(AtLoc, diag::err_arc_illegal_selector) <<
1366 Sel << SourceRange(LParenLoc, RParenLoc);
1367 break;
1368
1369 case OMF_None:
1370 case OMF_alloc:
1371 case OMF_copy:
1372 case OMF_finalize:
1373 case OMF_init:
1374 case OMF_mutableCopy:
1375 case OMF_new:
1376 case OMF_self:
1377 case OMF_initialize:
1378 case OMF_performSelector:
1379 break;
1380 }
1381 }
1382 QualType Ty = Context.getObjCSelType();
1383 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
1384 }
1385
ParseObjCProtocolExpression(IdentifierInfo * ProtocolId,SourceLocation AtLoc,SourceLocation ProtoLoc,SourceLocation LParenLoc,SourceLocation ProtoIdLoc,SourceLocation RParenLoc)1386 ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1387 SourceLocation AtLoc,
1388 SourceLocation ProtoLoc,
1389 SourceLocation LParenLoc,
1390 SourceLocation ProtoIdLoc,
1391 SourceLocation RParenLoc) {
1392 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
1393 if (!PDecl) {
1394 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
1395 return true;
1396 }
1397 if (PDecl->isNonRuntimeProtocol())
1398 Diag(ProtoLoc, diag::err_objc_non_runtime_protocol_in_protocol_expr)
1399 << PDecl;
1400 if (!PDecl->hasDefinition()) {
1401 Diag(ProtoLoc, diag::err_atprotocol_protocol) << PDecl;
1402 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
1403 } else {
1404 PDecl = PDecl->getDefinition();
1405 }
1406
1407 QualType Ty = Context.getObjCProtoType();
1408 if (Ty.isNull())
1409 return true;
1410 Ty = Context.getObjCObjectPointerType(Ty);
1411 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
1412 }
1413
1414 /// Try to capture an implicit reference to 'self'.
tryCaptureObjCSelf(SourceLocation Loc)1415 ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1416 DeclContext *DC = getFunctionLevelDeclContext();
1417
1418 // If we're not in an ObjC method, error out. Note that, unlike the
1419 // C++ case, we don't require an instance method --- class methods
1420 // still have a 'self', and we really do still need to capture it!
1421 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1422 if (!method)
1423 return nullptr;
1424
1425 tryCaptureVariable(method->getSelfDecl(), Loc);
1426
1427 return method;
1428 }
1429
stripObjCInstanceType(ASTContext & Context,QualType T)1430 static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
1431 QualType origType = T;
1432 if (auto nullability = AttributedType::stripOuterNullability(T)) {
1433 if (T == Context.getObjCInstanceType()) {
1434 return Context.getAttributedType(
1435 AttributedType::getNullabilityAttrKind(*nullability),
1436 Context.getObjCIdType(),
1437 Context.getObjCIdType());
1438 }
1439
1440 return origType;
1441 }
1442
1443 if (T == Context.getObjCInstanceType())
1444 return Context.getObjCIdType();
1445
1446 return origType;
1447 }
1448
1449 /// Determine the result type of a message send based on the receiver type,
1450 /// method, and the kind of message send.
1451 ///
1452 /// This is the "base" result type, which will still need to be adjusted
1453 /// to account for nullability.
getBaseMessageSendResultType(Sema & S,QualType ReceiverType,ObjCMethodDecl * Method,bool isClassMessage,bool isSuperMessage)1454 static QualType getBaseMessageSendResultType(Sema &S,
1455 QualType ReceiverType,
1456 ObjCMethodDecl *Method,
1457 bool isClassMessage,
1458 bool isSuperMessage) {
1459 assert(Method && "Must have a method");
1460 if (!Method->hasRelatedResultType())
1461 return Method->getSendResultType(ReceiverType);
1462
1463 ASTContext &Context = S.Context;
1464
1465 // Local function that transfers the nullability of the method's
1466 // result type to the returned result.
1467 auto transferNullability = [&](QualType type) -> QualType {
1468 // If the method's result type has nullability, extract it.
1469 if (auto nullability = Method->getSendResultType(ReceiverType)
1470 ->getNullability(Context)){
1471 // Strip off any outer nullability sugar from the provided type.
1472 (void)AttributedType::stripOuterNullability(type);
1473
1474 // Form a new attributed type using the method result type's nullability.
1475 return Context.getAttributedType(
1476 AttributedType::getNullabilityAttrKind(*nullability),
1477 type,
1478 type);
1479 }
1480
1481 return type;
1482 };
1483
1484 // If a method has a related return type:
1485 // - if the method found is an instance method, but the message send
1486 // was a class message send, T is the declared return type of the method
1487 // found
1488 if (Method->isInstanceMethod() && isClassMessage)
1489 return stripObjCInstanceType(Context,
1490 Method->getSendResultType(ReceiverType));
1491
1492 // - if the receiver is super, T is a pointer to the class of the
1493 // enclosing method definition
1494 if (isSuperMessage) {
1495 if (ObjCMethodDecl *CurMethod = S.getCurMethodDecl())
1496 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface()) {
1497 return transferNullability(
1498 Context.getObjCObjectPointerType(
1499 Context.getObjCInterfaceType(Class)));
1500 }
1501 }
1502
1503 // - if the receiver is the name of a class U, T is a pointer to U
1504 if (ReceiverType->getAsObjCInterfaceType())
1505 return transferNullability(Context.getObjCObjectPointerType(ReceiverType));
1506 // - if the receiver is of type Class or qualified Class type,
1507 // T is the declared return type of the method.
1508 if (ReceiverType->isObjCClassType() ||
1509 ReceiverType->isObjCQualifiedClassType())
1510 return stripObjCInstanceType(Context,
1511 Method->getSendResultType(ReceiverType));
1512
1513 // - if the receiver is id, qualified id, Class, or qualified Class, T
1514 // is the receiver type, otherwise
1515 // - T is the type of the receiver expression.
1516 return transferNullability(ReceiverType);
1517 }
1518
getMessageSendResultType(const Expr * Receiver,QualType ReceiverType,ObjCMethodDecl * Method,bool isClassMessage,bool isSuperMessage)1519 QualType Sema::getMessageSendResultType(const Expr *Receiver,
1520 QualType ReceiverType,
1521 ObjCMethodDecl *Method,
1522 bool isClassMessage,
1523 bool isSuperMessage) {
1524 // Produce the result type.
1525 QualType resultType = getBaseMessageSendResultType(*this, ReceiverType,
1526 Method,
1527 isClassMessage,
1528 isSuperMessage);
1529
1530 // If this is a class message, ignore the nullability of the receiver.
1531 if (isClassMessage) {
1532 // In a class method, class messages to 'self' that return instancetype can
1533 // be typed as the current class. We can safely do this in ARC because self
1534 // can't be reassigned, and we do it unsafely outside of ARC because in
1535 // practice people never reassign self in class methods and there's some
1536 // virtue in not being aggressively pedantic.
1537 if (Receiver && Receiver->isObjCSelfExpr()) {
1538 assert(ReceiverType->isObjCClassType() && "expected a Class self");
1539 QualType T = Method->getSendResultType(ReceiverType);
1540 AttributedType::stripOuterNullability(T);
1541 if (T == Context.getObjCInstanceType()) {
1542 const ObjCMethodDecl *MD = cast<ObjCMethodDecl>(
1543 cast<ImplicitParamDecl>(
1544 cast<DeclRefExpr>(Receiver->IgnoreParenImpCasts())->getDecl())
1545 ->getDeclContext());
1546 assert(MD->isClassMethod() && "expected a class method");
1547 QualType NewResultType = Context.getObjCObjectPointerType(
1548 Context.getObjCInterfaceType(MD->getClassInterface()));
1549 if (auto Nullability = resultType->getNullability(Context))
1550 NewResultType = Context.getAttributedType(
1551 AttributedType::getNullabilityAttrKind(*Nullability),
1552 NewResultType, NewResultType);
1553 return NewResultType;
1554 }
1555 }
1556 return resultType;
1557 }
1558
1559 // There is nothing left to do if the result type cannot have a nullability
1560 // specifier.
1561 if (!resultType->canHaveNullability())
1562 return resultType;
1563
1564 // Map the nullability of the result into a table index.
1565 unsigned receiverNullabilityIdx = 0;
1566 if (Optional<NullabilityKind> nullability =
1567 ReceiverType->getNullability(Context)) {
1568 if (*nullability == NullabilityKind::NullableResult)
1569 nullability = NullabilityKind::Nullable;
1570 receiverNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
1571 }
1572
1573 unsigned resultNullabilityIdx = 0;
1574 if (Optional<NullabilityKind> nullability =
1575 resultType->getNullability(Context)) {
1576 if (*nullability == NullabilityKind::NullableResult)
1577 nullability = NullabilityKind::Nullable;
1578 resultNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
1579 }
1580
1581 // The table of nullability mappings, indexed by the receiver's nullability
1582 // and then the result type's nullability.
1583 static const uint8_t None = 0;
1584 static const uint8_t NonNull = 1;
1585 static const uint8_t Nullable = 2;
1586 static const uint8_t Unspecified = 3;
1587 static const uint8_t nullabilityMap[4][4] = {
1588 // None NonNull Nullable Unspecified
1589 /* None */ { None, None, Nullable, None },
1590 /* NonNull */ { None, NonNull, Nullable, Unspecified },
1591 /* Nullable */ { Nullable, Nullable, Nullable, Nullable },
1592 /* Unspecified */ { None, Unspecified, Nullable, Unspecified }
1593 };
1594
1595 unsigned newResultNullabilityIdx
1596 = nullabilityMap[receiverNullabilityIdx][resultNullabilityIdx];
1597 if (newResultNullabilityIdx == resultNullabilityIdx)
1598 return resultType;
1599
1600 // Strip off the existing nullability. This removes as little type sugar as
1601 // possible.
1602 do {
1603 if (auto attributed = dyn_cast<AttributedType>(resultType.getTypePtr())) {
1604 resultType = attributed->getModifiedType();
1605 } else {
1606 resultType = resultType.getDesugaredType(Context);
1607 }
1608 } while (resultType->getNullability(Context));
1609
1610 // Add nullability back if needed.
1611 if (newResultNullabilityIdx > 0) {
1612 auto newNullability
1613 = static_cast<NullabilityKind>(newResultNullabilityIdx-1);
1614 return Context.getAttributedType(
1615 AttributedType::getNullabilityAttrKind(newNullability),
1616 resultType, resultType);
1617 }
1618
1619 return resultType;
1620 }
1621
1622 /// Look for an ObjC method whose result type exactly matches the given type.
1623 static const ObjCMethodDecl *
findExplicitInstancetypeDeclarer(const ObjCMethodDecl * MD,QualType instancetype)1624 findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD,
1625 QualType instancetype) {
1626 if (MD->getReturnType() == instancetype)
1627 return MD;
1628
1629 // For these purposes, a method in an @implementation overrides a
1630 // declaration in the @interface.
1631 if (const ObjCImplDecl *impl =
1632 dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
1633 const ObjCContainerDecl *iface;
1634 if (const ObjCCategoryImplDecl *catImpl =
1635 dyn_cast<ObjCCategoryImplDecl>(impl)) {
1636 iface = catImpl->getCategoryDecl();
1637 } else {
1638 iface = impl->getClassInterface();
1639 }
1640
1641 const ObjCMethodDecl *ifaceMD =
1642 iface->getMethod(MD->getSelector(), MD->isInstanceMethod());
1643 if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype);
1644 }
1645
1646 SmallVector<const ObjCMethodDecl *, 4> overrides;
1647 MD->getOverriddenMethods(overrides);
1648 for (unsigned i = 0, e = overrides.size(); i != e; ++i) {
1649 if (const ObjCMethodDecl *result =
1650 findExplicitInstancetypeDeclarer(overrides[i], instancetype))
1651 return result;
1652 }
1653
1654 return nullptr;
1655 }
1656
EmitRelatedResultTypeNoteForReturn(QualType destType)1657 void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
1658 // Only complain if we're in an ObjC method and the required return
1659 // type doesn't match the method's declared return type.
1660 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext);
1661 if (!MD || !MD->hasRelatedResultType() ||
1662 Context.hasSameUnqualifiedType(destType, MD->getReturnType()))
1663 return;
1664
1665 // Look for a method overridden by this method which explicitly uses
1666 // 'instancetype'.
1667 if (const ObjCMethodDecl *overridden =
1668 findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) {
1669 SourceRange range = overridden->getReturnTypeSourceRange();
1670 SourceLocation loc = range.getBegin();
1671 if (loc.isInvalid())
1672 loc = overridden->getLocation();
1673 Diag(loc, diag::note_related_result_type_explicit)
1674 << /*current method*/ 1 << range;
1675 return;
1676 }
1677
1678 // Otherwise, if we have an interesting method family, note that.
1679 // This should always trigger if the above didn't.
1680 if (ObjCMethodFamily family = MD->getMethodFamily())
1681 Diag(MD->getLocation(), diag::note_related_result_type_family)
1682 << /*current method*/ 1
1683 << family;
1684 }
1685
EmitRelatedResultTypeNote(const Expr * E)1686 void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1687 E = E->IgnoreParenImpCasts();
1688 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1689 if (!MsgSend)
1690 return;
1691
1692 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1693 if (!Method)
1694 return;
1695
1696 if (!Method->hasRelatedResultType())
1697 return;
1698
1699 if (Context.hasSameUnqualifiedType(
1700 Method->getReturnType().getNonReferenceType(), MsgSend->getType()))
1701 return;
1702
1703 if (!Context.hasSameUnqualifiedType(Method->getReturnType(),
1704 Context.getObjCInstanceType()))
1705 return;
1706
1707 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1708 << Method->isInstanceMethod() << Method->getSelector()
1709 << MsgSend->getType();
1710 }
1711
CheckMessageArgumentTypes(const Expr * Receiver,QualType ReceiverType,MultiExprArg Args,Selector Sel,ArrayRef<SourceLocation> SelectorLocs,ObjCMethodDecl * Method,bool isClassMessage,bool isSuperMessage,SourceLocation lbrac,SourceLocation rbrac,SourceRange RecRange,QualType & ReturnType,ExprValueKind & VK)1712 bool Sema::CheckMessageArgumentTypes(
1713 const Expr *Receiver, QualType ReceiverType, MultiExprArg Args,
1714 Selector Sel, ArrayRef<SourceLocation> SelectorLocs, ObjCMethodDecl *Method,
1715 bool isClassMessage, bool isSuperMessage, SourceLocation lbrac,
1716 SourceLocation rbrac, SourceRange RecRange, QualType &ReturnType,
1717 ExprValueKind &VK) {
1718 SourceLocation SelLoc;
1719 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
1720 SelLoc = SelectorLocs.front();
1721 else
1722 SelLoc = lbrac;
1723
1724 if (!Method) {
1725 // Apply default argument promotion as for (C99 6.5.2.2p6).
1726 for (unsigned i = 0, e = Args.size(); i != e; i++) {
1727 if (Args[i]->isTypeDependent())
1728 continue;
1729
1730 ExprResult result;
1731 if (getLangOpts().DebuggerSupport) {
1732 QualType paramTy; // ignored
1733 result = checkUnknownAnyArg(SelLoc, Args[i], paramTy);
1734 } else {
1735 result = DefaultArgumentPromotion(Args[i]);
1736 }
1737 if (result.isInvalid())
1738 return true;
1739 Args[i] = result.get();
1740 }
1741
1742 unsigned DiagID;
1743 if (getLangOpts().ObjCAutoRefCount)
1744 DiagID = diag::err_arc_method_not_found;
1745 else
1746 DiagID = isClassMessage ? diag::warn_class_method_not_found
1747 : diag::warn_inst_method_not_found;
1748 if (!getLangOpts().DebuggerSupport) {
1749 const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType);
1750 if (OMD && !OMD->isInvalidDecl()) {
1751 if (getLangOpts().ObjCAutoRefCount)
1752 DiagID = diag::err_method_not_found_with_typo;
1753 else
1754 DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo
1755 : diag::warn_instance_method_not_found_with_typo;
1756 Selector MatchedSel = OMD->getSelector();
1757 SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back());
1758 if (MatchedSel.isUnarySelector())
1759 Diag(SelLoc, DiagID)
1760 << Sel<< isClassMessage << MatchedSel
1761 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1762 else
1763 Diag(SelLoc, DiagID) << Sel<< isClassMessage << MatchedSel;
1764 }
1765 else
1766 Diag(SelLoc, DiagID)
1767 << Sel << isClassMessage << SourceRange(SelectorLocs.front(),
1768 SelectorLocs.back());
1769 // Find the class to which we are sending this message.
1770 if (auto *ObjPT = ReceiverType->getAs<ObjCObjectPointerType>()) {
1771 if (ObjCInterfaceDecl *ThisClass = ObjPT->getInterfaceDecl()) {
1772 Diag(ThisClass->getLocation(), diag::note_receiver_class_declared);
1773 if (!RecRange.isInvalid())
1774 if (ThisClass->lookupClassMethod(Sel))
1775 Diag(RecRange.getBegin(), diag::note_receiver_expr_here)
1776 << FixItHint::CreateReplacement(RecRange,
1777 ThisClass->getNameAsString());
1778 }
1779 }
1780 }
1781
1782 // In debuggers, we want to use __unknown_anytype for these
1783 // results so that clients can cast them.
1784 if (getLangOpts().DebuggerSupport) {
1785 ReturnType = Context.UnknownAnyTy;
1786 } else {
1787 ReturnType = Context.getObjCIdType();
1788 }
1789 VK = VK_RValue;
1790 return false;
1791 }
1792
1793 ReturnType = getMessageSendResultType(Receiver, ReceiverType, Method,
1794 isClassMessage, isSuperMessage);
1795 VK = Expr::getValueKindForType(Method->getReturnType());
1796
1797 unsigned NumNamedArgs = Sel.getNumArgs();
1798 // Method might have more arguments than selector indicates. This is due
1799 // to addition of c-style arguments in method.
1800 if (Method->param_size() > Sel.getNumArgs())
1801 NumNamedArgs = Method->param_size();
1802 // FIXME. This need be cleaned up.
1803 if (Args.size() < NumNamedArgs) {
1804 Diag(SelLoc, diag::err_typecheck_call_too_few_args)
1805 << 2 << NumNamedArgs << static_cast<unsigned>(Args.size());
1806 return false;
1807 }
1808
1809 // Compute the set of type arguments to be substituted into each parameter
1810 // type.
1811 Optional<ArrayRef<QualType>> typeArgs
1812 = ReceiverType->getObjCSubstitutions(Method->getDeclContext());
1813 bool IsError = false;
1814 for (unsigned i = 0; i < NumNamedArgs; i++) {
1815 // We can't do any type-checking on a type-dependent argument.
1816 if (Args[i]->isTypeDependent())
1817 continue;
1818
1819 Expr *argExpr = Args[i];
1820
1821 ParmVarDecl *param = Method->parameters()[i];
1822 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
1823
1824 if (param->hasAttr<NoEscapeAttr>())
1825 if (auto *BE = dyn_cast<BlockExpr>(
1826 argExpr->IgnoreParenNoopCasts(Context)))
1827 BE->getBlockDecl()->setDoesNotEscape();
1828
1829 // Strip the unbridged-cast placeholder expression off unless it's
1830 // a consumed argument.
1831 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1832 !param->hasAttr<CFConsumedAttr>())
1833 argExpr = stripARCUnbridgedCast(argExpr);
1834
1835 // If the parameter is __unknown_anytype, infer its type
1836 // from the argument.
1837 if (param->getType() == Context.UnknownAnyTy) {
1838 QualType paramType;
1839 ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType);
1840 if (argE.isInvalid()) {
1841 IsError = true;
1842 } else {
1843 Args[i] = argE.get();
1844
1845 // Update the parameter type in-place.
1846 param->setType(paramType);
1847 }
1848 continue;
1849 }
1850
1851 QualType origParamType = param->getType();
1852 QualType paramType = param->getType();
1853 if (typeArgs)
1854 paramType = paramType.substObjCTypeArgs(
1855 Context,
1856 *typeArgs,
1857 ObjCSubstitutionContext::Parameter);
1858
1859 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
1860 paramType,
1861 diag::err_call_incomplete_argument, argExpr))
1862 return true;
1863
1864 InitializedEntity Entity
1865 = InitializedEntity::InitializeParameter(Context, param, paramType);
1866 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), argExpr);
1867 if (ArgE.isInvalid())
1868 IsError = true;
1869 else {
1870 Args[i] = ArgE.getAs<Expr>();
1871
1872 // If we are type-erasing a block to a block-compatible
1873 // Objective-C pointer type, we may need to extend the lifetime
1874 // of the block object.
1875 if (typeArgs && Args[i]->isRValue() && paramType->isBlockPointerType() &&
1876 Args[i]->getType()->isBlockPointerType() &&
1877 origParamType->isObjCObjectPointerType()) {
1878 ExprResult arg = Args[i];
1879 maybeExtendBlockObject(arg);
1880 Args[i] = arg.get();
1881 }
1882 }
1883 }
1884
1885 // Promote additional arguments to variadic methods.
1886 if (Method->isVariadic()) {
1887 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
1888 if (Args[i]->isTypeDependent())
1889 continue;
1890
1891 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
1892 nullptr);
1893 IsError |= Arg.isInvalid();
1894 Args[i] = Arg.get();
1895 }
1896 } else {
1897 // Check for extra arguments to non-variadic methods.
1898 if (Args.size() != NumNamedArgs) {
1899 Diag(Args[NumNamedArgs]->getBeginLoc(),
1900 diag::err_typecheck_call_too_many_args)
1901 << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size())
1902 << Method->getSourceRange()
1903 << SourceRange(Args[NumNamedArgs]->getBeginLoc(),
1904 Args.back()->getEndLoc());
1905 }
1906 }
1907
1908 DiagnoseSentinelCalls(Method, SelLoc, Args);
1909
1910 // Do additional checkings on method.
1911 IsError |= CheckObjCMethodCall(
1912 Method, SelLoc, makeArrayRef(Args.data(), Args.size()));
1913
1914 return IsError;
1915 }
1916
isSelfExpr(Expr * RExpr)1917 bool Sema::isSelfExpr(Expr *RExpr) {
1918 // 'self' is objc 'self' in an objc method only.
1919 ObjCMethodDecl *Method =
1920 dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1921 return isSelfExpr(RExpr, Method);
1922 }
1923
isSelfExpr(Expr * receiver,const ObjCMethodDecl * method)1924 bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) {
1925 if (!method) return false;
1926
1927 receiver = receiver->IgnoreParenLValueCasts();
1928 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
1929 if (DRE->getDecl() == method->getSelfDecl())
1930 return true;
1931 return false;
1932 }
1933
1934 /// LookupMethodInType - Look up a method in an ObjCObjectType.
LookupMethodInObjectType(Selector sel,QualType type,bool isInstance)1935 ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1936 bool isInstance) {
1937 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1938 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1939 // Look it up in the main interface (and categories, etc.)
1940 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1941 return method;
1942
1943 // Okay, look for "private" methods declared in any
1944 // @implementations we've seen.
1945 if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
1946 return method;
1947 }
1948
1949 // Check qualifiers.
1950 for (const auto *I : objType->quals())
1951 if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance))
1952 return method;
1953
1954 return nullptr;
1955 }
1956
1957 /// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1958 /// list of a qualified objective pointer type.
LookupMethodInQualifiedType(Selector Sel,const ObjCObjectPointerType * OPT,bool Instance)1959 ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1960 const ObjCObjectPointerType *OPT,
1961 bool Instance)
1962 {
1963 ObjCMethodDecl *MD = nullptr;
1964 for (const auto *PROTO : OPT->quals()) {
1965 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1966 return MD;
1967 }
1968 }
1969 return nullptr;
1970 }
1971
1972 /// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1973 /// objective C interface. This is a property reference expression.
1974 ExprResult Sema::
HandleExprPropertyRefExpr(const ObjCObjectPointerType * OPT,Expr * BaseExpr,SourceLocation OpLoc,DeclarationName MemberName,SourceLocation MemberLoc,SourceLocation SuperLoc,QualType SuperType,bool Super)1975 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
1976 Expr *BaseExpr, SourceLocation OpLoc,
1977 DeclarationName MemberName,
1978 SourceLocation MemberLoc,
1979 SourceLocation SuperLoc, QualType SuperType,
1980 bool Super) {
1981 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1982 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
1983
1984 if (!MemberName.isIdentifier()) {
1985 Diag(MemberLoc, diag::err_invalid_property_name)
1986 << MemberName << QualType(OPT, 0);
1987 return ExprError();
1988 }
1989
1990 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1991
1992 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1993 : BaseExpr->getSourceRange();
1994 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
1995 diag::err_property_not_found_forward_class,
1996 MemberName, BaseRange))
1997 return ExprError();
1998
1999 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(
2000 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
2001 // Check whether we can reference this property.
2002 if (DiagnoseUseOfDecl(PD, MemberLoc))
2003 return ExprError();
2004 if (Super)
2005 return new (Context)
2006 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
2007 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
2008 else
2009 return new (Context)
2010 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
2011 OK_ObjCProperty, MemberLoc, BaseExpr);
2012 }
2013 // Check protocols on qualified interfaces.
2014 for (const auto *I : OPT->quals())
2015 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(
2016 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
2017 // Check whether we can reference this property.
2018 if (DiagnoseUseOfDecl(PD, MemberLoc))
2019 return ExprError();
2020
2021 if (Super)
2022 return new (Context) ObjCPropertyRefExpr(
2023 PD, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc,
2024 SuperLoc, SuperType);
2025 else
2026 return new (Context)
2027 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
2028 OK_ObjCProperty, MemberLoc, BaseExpr);
2029 }
2030 // If that failed, look for an "implicit" property by seeing if the nullary
2031 // selector is implemented.
2032
2033 // FIXME: The logic for looking up nullary and unary selectors should be
2034 // shared with the code in ActOnInstanceMessage.
2035
2036 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2037 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
2038
2039 // May be found in property's qualified list.
2040 if (!Getter)
2041 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
2042
2043 // If this reference is in an @implementation, check for 'private' methods.
2044 if (!Getter)
2045 Getter = IFace->lookupPrivateMethod(Sel);
2046
2047 if (Getter) {
2048 // Check if we can reference this property.
2049 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2050 return ExprError();
2051 }
2052 // If we found a getter then this may be a valid dot-reference, we
2053 // will look for the matching setter, in case it is needed.
2054 Selector SetterSel =
2055 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
2056 PP.getSelectorTable(), Member);
2057 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
2058
2059 // May be found in property's qualified list.
2060 if (!Setter)
2061 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
2062
2063 if (!Setter) {
2064 // If this reference is in an @implementation, also check for 'private'
2065 // methods.
2066 Setter = IFace->lookupPrivateMethod(SetterSel);
2067 }
2068
2069 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2070 return ExprError();
2071
2072 // Special warning if member name used in a property-dot for a setter accessor
2073 // does not use a property with same name; e.g. obj.X = ... for a property with
2074 // name 'x'.
2075 if (Setter && Setter->isImplicit() && Setter->isPropertyAccessor() &&
2076 !IFace->FindPropertyDeclaration(
2077 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
2078 if (const ObjCPropertyDecl *PDecl = Setter->findPropertyDecl()) {
2079 // Do not warn if user is using property-dot syntax to make call to
2080 // user named setter.
2081 if (!(PDecl->getPropertyAttributes() &
2082 ObjCPropertyAttribute::kind_setter))
2083 Diag(MemberLoc,
2084 diag::warn_property_access_suggest)
2085 << MemberName << QualType(OPT, 0) << PDecl->getName()
2086 << FixItHint::CreateReplacement(MemberLoc, PDecl->getName());
2087 }
2088 }
2089
2090 if (Getter || Setter) {
2091 if (Super)
2092 return new (Context)
2093 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
2094 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
2095 else
2096 return new (Context)
2097 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
2098 OK_ObjCProperty, MemberLoc, BaseExpr);
2099
2100 }
2101
2102 // Attempt to correct for typos in property names.
2103 DeclFilterCCC<ObjCPropertyDecl> CCC{};
2104 if (TypoCorrection Corrected = CorrectTypo(
2105 DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName,
2106 nullptr, nullptr, CCC, CTK_ErrorRecovery, IFace, false, OPT)) {
2107 DeclarationName TypoResult = Corrected.getCorrection();
2108 if (TypoResult.isIdentifier() &&
2109 TypoResult.getAsIdentifierInfo() == Member) {
2110 // There is no need to try the correction if it is the same.
2111 NamedDecl *ChosenDecl =
2112 Corrected.isKeyword() ? nullptr : Corrected.getFoundDecl();
2113 if (ChosenDecl && isa<ObjCPropertyDecl>(ChosenDecl))
2114 if (cast<ObjCPropertyDecl>(ChosenDecl)->isClassProperty()) {
2115 // This is a class property, we should not use the instance to
2116 // access it.
2117 Diag(MemberLoc, diag::err_class_property_found) << MemberName
2118 << OPT->getInterfaceDecl()->getName()
2119 << FixItHint::CreateReplacement(BaseExpr->getSourceRange(),
2120 OPT->getInterfaceDecl()->getName());
2121 return ExprError();
2122 }
2123 } else {
2124 diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest)
2125 << MemberName << QualType(OPT, 0));
2126 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
2127 TypoResult, MemberLoc,
2128 SuperLoc, SuperType, Super);
2129 }
2130 }
2131 ObjCInterfaceDecl *ClassDeclared;
2132 if (ObjCIvarDecl *Ivar =
2133 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
2134 QualType T = Ivar->getType();
2135 if (const ObjCObjectPointerType * OBJPT =
2136 T->getAsObjCInterfacePointerType()) {
2137 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
2138 diag::err_property_not_as_forward_class,
2139 MemberName, BaseExpr))
2140 return ExprError();
2141 }
2142 Diag(MemberLoc,
2143 diag::err_ivar_access_using_property_syntax_suggest)
2144 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
2145 << FixItHint::CreateReplacement(OpLoc, "->");
2146 return ExprError();
2147 }
2148
2149 Diag(MemberLoc, diag::err_property_not_found)
2150 << MemberName << QualType(OPT, 0);
2151 if (Setter)
2152 Diag(Setter->getLocation(), diag::note_getter_unavailable)
2153 << MemberName << BaseExpr->getSourceRange();
2154 return ExprError();
2155 }
2156
2157 ExprResult Sema::
ActOnClassPropertyRefExpr(IdentifierInfo & receiverName,IdentifierInfo & propertyName,SourceLocation receiverNameLoc,SourceLocation propertyNameLoc)2158 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
2159 IdentifierInfo &propertyName,
2160 SourceLocation receiverNameLoc,
2161 SourceLocation propertyNameLoc) {
2162
2163 IdentifierInfo *receiverNamePtr = &receiverName;
2164 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
2165 receiverNameLoc);
2166
2167 QualType SuperType;
2168 if (!IFace) {
2169 // If the "receiver" is 'super' in a method, handle it as an expression-like
2170 // property reference.
2171 if (receiverNamePtr->isStr("super")) {
2172 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
2173 if (auto classDecl = CurMethod->getClassInterface()) {
2174 SuperType = QualType(classDecl->getSuperClassType(), 0);
2175 if (CurMethod->isInstanceMethod()) {
2176 if (SuperType.isNull()) {
2177 // The current class does not have a superclass.
2178 Diag(receiverNameLoc, diag::err_root_class_cannot_use_super)
2179 << CurMethod->getClassInterface()->getIdentifier();
2180 return ExprError();
2181 }
2182 QualType T = Context.getObjCObjectPointerType(SuperType);
2183
2184 return HandleExprPropertyRefExpr(T->castAs<ObjCObjectPointerType>(),
2185 /*BaseExpr*/nullptr,
2186 SourceLocation()/*OpLoc*/,
2187 &propertyName,
2188 propertyNameLoc,
2189 receiverNameLoc, T, true);
2190 }
2191
2192 // Otherwise, if this is a class method, try dispatching to our
2193 // superclass.
2194 IFace = CurMethod->getClassInterface()->getSuperClass();
2195 }
2196 }
2197 }
2198
2199 if (!IFace) {
2200 Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier
2201 << tok::l_paren;
2202 return ExprError();
2203 }
2204 }
2205
2206 Selector GetterSel;
2207 Selector SetterSel;
2208 if (auto PD = IFace->FindPropertyDeclaration(
2209 &propertyName, ObjCPropertyQueryKind::OBJC_PR_query_class)) {
2210 GetterSel = PD->getGetterName();
2211 SetterSel = PD->getSetterName();
2212 } else {
2213 GetterSel = PP.getSelectorTable().getNullarySelector(&propertyName);
2214 SetterSel = SelectorTable::constructSetterSelector(
2215 PP.getIdentifierTable(), PP.getSelectorTable(), &propertyName);
2216 }
2217
2218 // Search for a declared property first.
2219 ObjCMethodDecl *Getter = IFace->lookupClassMethod(GetterSel);
2220
2221 // If this reference is in an @implementation, check for 'private' methods.
2222 if (!Getter)
2223 Getter = IFace->lookupPrivateClassMethod(GetterSel);
2224
2225 if (Getter) {
2226 // FIXME: refactor/share with ActOnMemberReference().
2227 // Check if we can reference this property.
2228 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
2229 return ExprError();
2230 }
2231
2232 // Look for the matching setter, in case it is needed.
2233 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2234 if (!Setter) {
2235 // If this reference is in an @implementation, also check for 'private'
2236 // methods.
2237 Setter = IFace->lookupPrivateClassMethod(SetterSel);
2238 }
2239 // Look through local category implementations associated with the class.
2240 if (!Setter)
2241 Setter = IFace->getCategoryClassMethod(SetterSel);
2242
2243 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
2244 return ExprError();
2245
2246 if (Getter || Setter) {
2247 if (!SuperType.isNull())
2248 return new (Context)
2249 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
2250 OK_ObjCProperty, propertyNameLoc, receiverNameLoc,
2251 SuperType);
2252
2253 return new (Context) ObjCPropertyRefExpr(
2254 Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty,
2255 propertyNameLoc, receiverNameLoc, IFace);
2256 }
2257 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
2258 << &propertyName << Context.getObjCInterfaceType(IFace));
2259 }
2260
2261 namespace {
2262
2263 class ObjCInterfaceOrSuperCCC final : public CorrectionCandidateCallback {
2264 public:
ObjCInterfaceOrSuperCCC(ObjCMethodDecl * Method)2265 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
2266 // Determine whether "super" is acceptable in the current context.
2267 if (Method && Method->getClassInterface())
2268 WantObjCSuper = Method->getClassInterface()->getSuperClass();
2269 }
2270
ValidateCandidate(const TypoCorrection & candidate)2271 bool ValidateCandidate(const TypoCorrection &candidate) override {
2272 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
2273 candidate.isKeyword("super");
2274 }
2275
clone()2276 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2277 return std::make_unique<ObjCInterfaceOrSuperCCC>(*this);
2278 }
2279 };
2280
2281 } // end anonymous namespace
2282
getObjCMessageKind(Scope * S,IdentifierInfo * Name,SourceLocation NameLoc,bool IsSuper,bool HasTrailingDot,ParsedType & ReceiverType)2283 Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
2284 IdentifierInfo *Name,
2285 SourceLocation NameLoc,
2286 bool IsSuper,
2287 bool HasTrailingDot,
2288 ParsedType &ReceiverType) {
2289 ReceiverType = nullptr;
2290
2291 // If the identifier is "super" and there is no trailing dot, we're
2292 // messaging super. If the identifier is "super" and there is a
2293 // trailing dot, it's an instance message.
2294 if (IsSuper && S->isInObjcMethodScope())
2295 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
2296
2297 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
2298 LookupName(Result, S);
2299
2300 switch (Result.getResultKind()) {
2301 case LookupResult::NotFound:
2302 // Normal name lookup didn't find anything. If we're in an
2303 // Objective-C method, look for ivars. If we find one, we're done!
2304 // FIXME: This is a hack. Ivar lookup should be part of normal
2305 // lookup.
2306 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
2307 if (!Method->getClassInterface()) {
2308 // Fall back: let the parser try to parse it as an instance message.
2309 return ObjCInstanceMessage;
2310 }
2311
2312 ObjCInterfaceDecl *ClassDeclared;
2313 if (Method->getClassInterface()->lookupInstanceVariable(Name,
2314 ClassDeclared))
2315 return ObjCInstanceMessage;
2316 }
2317
2318 // Break out; we'll perform typo correction below.
2319 break;
2320
2321 case LookupResult::NotFoundInCurrentInstantiation:
2322 case LookupResult::FoundOverloaded:
2323 case LookupResult::FoundUnresolvedValue:
2324 case LookupResult::Ambiguous:
2325 Result.suppressDiagnostics();
2326 return ObjCInstanceMessage;
2327
2328 case LookupResult::Found: {
2329 // If the identifier is a class or not, and there is a trailing dot,
2330 // it's an instance message.
2331 if (HasTrailingDot)
2332 return ObjCInstanceMessage;
2333 // We found something. If it's a type, then we have a class
2334 // message. Otherwise, it's an instance message.
2335 NamedDecl *ND = Result.getFoundDecl();
2336 QualType T;
2337 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
2338 T = Context.getObjCInterfaceType(Class);
2339 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
2340 T = Context.getTypeDeclType(Type);
2341 DiagnoseUseOfDecl(Type, NameLoc);
2342 }
2343 else
2344 return ObjCInstanceMessage;
2345
2346 // We have a class message, and T is the type we're
2347 // messaging. Build source-location information for it.
2348 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
2349 ReceiverType = CreateParsedType(T, TSInfo);
2350 return ObjCClassMessage;
2351 }
2352 }
2353
2354 ObjCInterfaceOrSuperCCC CCC(getCurMethodDecl());
2355 if (TypoCorrection Corrected = CorrectTypo(
2356 Result.getLookupNameInfo(), Result.getLookupKind(), S, nullptr, CCC,
2357 CTK_ErrorRecovery, nullptr, false, nullptr, false)) {
2358 if (Corrected.isKeyword()) {
2359 // If we've found the keyword "super" (the only keyword that would be
2360 // returned by CorrectTypo), this is a send to super.
2361 diagnoseTypo(Corrected,
2362 PDiag(diag::err_unknown_receiver_suggest) << Name);
2363 return ObjCSuperMessage;
2364 } else if (ObjCInterfaceDecl *Class =
2365 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
2366 // If we found a declaration, correct when it refers to an Objective-C
2367 // class.
2368 diagnoseTypo(Corrected,
2369 PDiag(diag::err_unknown_receiver_suggest) << Name);
2370 QualType T = Context.getObjCInterfaceType(Class);
2371 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
2372 ReceiverType = CreateParsedType(T, TSInfo);
2373 return ObjCClassMessage;
2374 }
2375 }
2376
2377 // Fall back: let the parser try to parse it as an instance message.
2378 return ObjCInstanceMessage;
2379 }
2380
ActOnSuperMessage(Scope * S,SourceLocation SuperLoc,Selector Sel,SourceLocation LBracLoc,ArrayRef<SourceLocation> SelectorLocs,SourceLocation RBracLoc,MultiExprArg Args)2381 ExprResult Sema::ActOnSuperMessage(Scope *S,
2382 SourceLocation SuperLoc,
2383 Selector Sel,
2384 SourceLocation LBracLoc,
2385 ArrayRef<SourceLocation> SelectorLocs,
2386 SourceLocation RBracLoc,
2387 MultiExprArg Args) {
2388 // Determine whether we are inside a method or not.
2389 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
2390 if (!Method) {
2391 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
2392 return ExprError();
2393 }
2394
2395 ObjCInterfaceDecl *Class = Method->getClassInterface();
2396 if (!Class) {
2397 Diag(SuperLoc, diag::err_no_super_class_message)
2398 << Method->getDeclName();
2399 return ExprError();
2400 }
2401
2402 QualType SuperTy(Class->getSuperClassType(), 0);
2403 if (SuperTy.isNull()) {
2404 // The current class does not have a superclass.
2405 Diag(SuperLoc, diag::err_root_class_cannot_use_super)
2406 << Class->getIdentifier();
2407 return ExprError();
2408 }
2409
2410 // We are in a method whose class has a superclass, so 'super'
2411 // is acting as a keyword.
2412 if (Method->getSelector() == Sel)
2413 getCurFunction()->ObjCShouldCallSuper = false;
2414
2415 if (Method->isInstanceMethod()) {
2416 // Since we are in an instance method, this is an instance
2417 // message to the superclass instance.
2418 SuperTy = Context.getObjCObjectPointerType(SuperTy);
2419 return BuildInstanceMessage(nullptr, SuperTy, SuperLoc,
2420 Sel, /*Method=*/nullptr,
2421 LBracLoc, SelectorLocs, RBracLoc, Args);
2422 }
2423
2424 // Since we are in a class method, this is a class message to
2425 // the superclass.
2426 return BuildClassMessage(/*ReceiverTypeInfo=*/nullptr,
2427 SuperTy,
2428 SuperLoc, Sel, /*Method=*/nullptr,
2429 LBracLoc, SelectorLocs, RBracLoc, Args);
2430 }
2431
BuildClassMessageImplicit(QualType ReceiverType,bool isSuperReceiver,SourceLocation Loc,Selector Sel,ObjCMethodDecl * Method,MultiExprArg Args)2432 ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
2433 bool isSuperReceiver,
2434 SourceLocation Loc,
2435 Selector Sel,
2436 ObjCMethodDecl *Method,
2437 MultiExprArg Args) {
2438 TypeSourceInfo *receiverTypeInfo = nullptr;
2439 if (!ReceiverType.isNull())
2440 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
2441
2442 return BuildClassMessage(receiverTypeInfo, ReceiverType,
2443 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
2444 Sel, Method, Loc, Loc, Loc, Args,
2445 /*isImplicit=*/true);
2446 }
2447
applyCocoaAPICheck(Sema & S,const ObjCMessageExpr * Msg,unsigned DiagID,bool (* refactor)(const ObjCMessageExpr *,const NSAPI &,edit::Commit &))2448 static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
2449 unsigned DiagID,
2450 bool (*refactor)(const ObjCMessageExpr *,
2451 const NSAPI &, edit::Commit &)) {
2452 SourceLocation MsgLoc = Msg->getExprLoc();
2453 if (S.Diags.isIgnored(DiagID, MsgLoc))
2454 return;
2455
2456 SourceManager &SM = S.SourceMgr;
2457 edit::Commit ECommit(SM, S.LangOpts);
2458 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
2459 auto Builder = S.Diag(MsgLoc, DiagID)
2460 << Msg->getSelector() << Msg->getSourceRange();
2461 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
2462 if (!ECommit.isCommitable())
2463 return;
2464 for (edit::Commit::edit_iterator
2465 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
2466 const edit::Commit::Edit &Edit = *I;
2467 switch (Edit.Kind) {
2468 case edit::Commit::Act_Insert:
2469 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
2470 Edit.Text,
2471 Edit.BeforePrev));
2472 break;
2473 case edit::Commit::Act_InsertFromRange:
2474 Builder.AddFixItHint(
2475 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
2476 Edit.getInsertFromRange(SM),
2477 Edit.BeforePrev));
2478 break;
2479 case edit::Commit::Act_Remove:
2480 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
2481 break;
2482 }
2483 }
2484 }
2485 }
2486
checkCocoaAPI(Sema & S,const ObjCMessageExpr * Msg)2487 static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
2488 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
2489 edit::rewriteObjCRedundantCallWithLiteral);
2490 }
2491
checkFoundationAPI(Sema & S,SourceLocation Loc,const ObjCMethodDecl * Method,ArrayRef<Expr * > Args,QualType ReceiverType,bool IsClassObjectCall)2492 static void checkFoundationAPI(Sema &S, SourceLocation Loc,
2493 const ObjCMethodDecl *Method,
2494 ArrayRef<Expr *> Args, QualType ReceiverType,
2495 bool IsClassObjectCall) {
2496 // Check if this is a performSelector method that uses a selector that returns
2497 // a record or a vector type.
2498 if (Method->getSelector().getMethodFamily() != OMF_performSelector ||
2499 Args.empty())
2500 return;
2501 const auto *SE = dyn_cast<ObjCSelectorExpr>(Args[0]->IgnoreParens());
2502 if (!SE)
2503 return;
2504 ObjCMethodDecl *ImpliedMethod;
2505 if (!IsClassObjectCall) {
2506 const auto *OPT = ReceiverType->getAs<ObjCObjectPointerType>();
2507 if (!OPT || !OPT->getInterfaceDecl())
2508 return;
2509 ImpliedMethod =
2510 OPT->getInterfaceDecl()->lookupInstanceMethod(SE->getSelector());
2511 if (!ImpliedMethod)
2512 ImpliedMethod =
2513 OPT->getInterfaceDecl()->lookupPrivateMethod(SE->getSelector());
2514 } else {
2515 const auto *IT = ReceiverType->getAs<ObjCInterfaceType>();
2516 if (!IT)
2517 return;
2518 ImpliedMethod = IT->getDecl()->lookupClassMethod(SE->getSelector());
2519 if (!ImpliedMethod)
2520 ImpliedMethod =
2521 IT->getDecl()->lookupPrivateClassMethod(SE->getSelector());
2522 }
2523 if (!ImpliedMethod)
2524 return;
2525 QualType Ret = ImpliedMethod->getReturnType();
2526 if (Ret->isRecordType() || Ret->isVectorType() || Ret->isExtVectorType()) {
2527 S.Diag(Loc, diag::warn_objc_unsafe_perform_selector)
2528 << Method->getSelector()
2529 << (!Ret->isRecordType()
2530 ? /*Vector*/ 2
2531 : Ret->isUnionType() ? /*Union*/ 1 : /*Struct*/ 0);
2532 S.Diag(ImpliedMethod->getBeginLoc(),
2533 diag::note_objc_unsafe_perform_selector_method_declared_here)
2534 << ImpliedMethod->getSelector() << Ret;
2535 }
2536 }
2537
2538 /// Diagnose use of %s directive in an NSString which is being passed
2539 /// as formatting string to formatting method.
2540 static void
DiagnoseCStringFormatDirectiveInObjCAPI(Sema & S,ObjCMethodDecl * Method,Selector Sel,Expr ** Args,unsigned NumArgs)2541 DiagnoseCStringFormatDirectiveInObjCAPI(Sema &S,
2542 ObjCMethodDecl *Method,
2543 Selector Sel,
2544 Expr **Args, unsigned NumArgs) {
2545 unsigned Idx = 0;
2546 bool Format = false;
2547 ObjCStringFormatFamily SFFamily = Sel.getStringFormatFamily();
2548 if (SFFamily == ObjCStringFormatFamily::SFF_NSString) {
2549 Idx = 0;
2550 Format = true;
2551 }
2552 else if (Method) {
2553 for (const auto *I : Method->specific_attrs<FormatAttr>()) {
2554 if (S.GetFormatNSStringIdx(I, Idx)) {
2555 Format = true;
2556 break;
2557 }
2558 }
2559 }
2560 if (!Format || NumArgs <= Idx)
2561 return;
2562
2563 Expr *FormatExpr = Args[Idx];
2564 if (ObjCStringLiteral *OSL =
2565 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) {
2566 StringLiteral *FormatString = OSL->getString();
2567 if (S.FormatStringHasSArg(FormatString)) {
2568 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2569 << "%s" << 0 << 0;
2570 if (Method)
2571 S.Diag(Method->getLocation(), diag::note_method_declared_at)
2572 << Method->getDeclName();
2573 }
2574 }
2575 }
2576
2577 /// Build an Objective-C class message expression.
2578 ///
2579 /// This routine takes care of both normal class messages and
2580 /// class messages to the superclass.
2581 ///
2582 /// \param ReceiverTypeInfo Type source information that describes the
2583 /// receiver of this message. This may be NULL, in which case we are
2584 /// sending to the superclass and \p SuperLoc must be a valid source
2585 /// location.
2586
2587 /// \param ReceiverType The type of the object receiving the
2588 /// message. When \p ReceiverTypeInfo is non-NULL, this is the same
2589 /// type as that refers to. For a superclass send, this is the type of
2590 /// the superclass.
2591 ///
2592 /// \param SuperLoc The location of the "super" keyword in a
2593 /// superclass message.
2594 ///
2595 /// \param Sel The selector to which the message is being sent.
2596 ///
2597 /// \param Method The method that this class message is invoking, if
2598 /// already known.
2599 ///
2600 /// \param LBracLoc The location of the opening square bracket ']'.
2601 ///
2602 /// \param RBracLoc The location of the closing square bracket ']'.
2603 ///
2604 /// \param ArgsIn The message arguments.
BuildClassMessage(TypeSourceInfo * ReceiverTypeInfo,QualType ReceiverType,SourceLocation SuperLoc,Selector Sel,ObjCMethodDecl * Method,SourceLocation LBracLoc,ArrayRef<SourceLocation> SelectorLocs,SourceLocation RBracLoc,MultiExprArg ArgsIn,bool isImplicit)2605 ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
2606 QualType ReceiverType,
2607 SourceLocation SuperLoc,
2608 Selector Sel,
2609 ObjCMethodDecl *Method,
2610 SourceLocation LBracLoc,
2611 ArrayRef<SourceLocation> SelectorLocs,
2612 SourceLocation RBracLoc,
2613 MultiExprArg ArgsIn,
2614 bool isImplicit) {
2615 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
2616 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
2617 if (LBracLoc.isInvalid()) {
2618 Diag(Loc, diag::err_missing_open_square_message_send)
2619 << FixItHint::CreateInsertion(Loc, "[");
2620 LBracLoc = Loc;
2621 }
2622 ArrayRef<SourceLocation> SelectorSlotLocs;
2623 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2624 SelectorSlotLocs = SelectorLocs;
2625 else
2626 SelectorSlotLocs = Loc;
2627 SourceLocation SelLoc = SelectorSlotLocs.front();
2628
2629 if (ReceiverType->isDependentType()) {
2630 // If the receiver type is dependent, we can't type-check anything
2631 // at this point. Build a dependent expression.
2632 unsigned NumArgs = ArgsIn.size();
2633 Expr **Args = ArgsIn.data();
2634 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2635 return ObjCMessageExpr::Create(
2636 Context, ReceiverType, VK_RValue, LBracLoc, ReceiverTypeInfo, Sel,
2637 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs), RBracLoc,
2638 isImplicit);
2639 }
2640
2641 // Find the class to which we are sending this message.
2642 ObjCInterfaceDecl *Class = nullptr;
2643 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
2644 if (!ClassType || !(Class = ClassType->getInterface())) {
2645 Diag(Loc, diag::err_invalid_receiver_class_message)
2646 << ReceiverType;
2647 return ExprError();
2648 }
2649 assert(Class && "We don't know which class we're messaging?");
2650 // objc++ diagnoses during typename annotation.
2651 if (!getLangOpts().CPlusPlus)
2652 (void)DiagnoseUseOfDecl(Class, SelectorSlotLocs);
2653 // Find the method we are messaging.
2654 if (!Method) {
2655 SourceRange TypeRange
2656 = SuperLoc.isValid()? SourceRange(SuperLoc)
2657 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
2658 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
2659 (getLangOpts().ObjCAutoRefCount
2660 ? diag::err_arc_receiver_forward_class
2661 : diag::warn_receiver_forward_class),
2662 TypeRange)) {
2663 // A forward class used in messaging is treated as a 'Class'
2664 Method = LookupFactoryMethodInGlobalPool(Sel,
2665 SourceRange(LBracLoc, RBracLoc));
2666 if (Method && !getLangOpts().ObjCAutoRefCount)
2667 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
2668 << Method->getDeclName();
2669 }
2670 if (!Method)
2671 Method = Class->lookupClassMethod(Sel);
2672
2673 // If we have an implementation in scope, check "private" methods.
2674 if (!Method)
2675 Method = Class->lookupPrivateClassMethod(Sel);
2676
2677 if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs,
2678 nullptr, false, false, Class))
2679 return ExprError();
2680 }
2681
2682 // Check the argument types and determine the result type.
2683 QualType ReturnType;
2684 ExprValueKind VK = VK_RValue;
2685
2686 unsigned NumArgs = ArgsIn.size();
2687 Expr **Args = ArgsIn.data();
2688 if (CheckMessageArgumentTypes(/*Receiver=*/nullptr, ReceiverType,
2689 MultiExprArg(Args, NumArgs), Sel, SelectorLocs,
2690 Method, true, SuperLoc.isValid(), LBracLoc,
2691 RBracLoc, SourceRange(), ReturnType, VK))
2692 return ExprError();
2693
2694 if (Method && !Method->getReturnType()->isVoidType() &&
2695 RequireCompleteType(LBracLoc, Method->getReturnType(),
2696 diag::err_illegal_message_expr_incomplete_type))
2697 return ExprError();
2698
2699 if (Method && Method->isDirectMethod() && SuperLoc.isValid()) {
2700 Diag(SuperLoc, diag::err_messaging_super_with_direct_method)
2701 << FixItHint::CreateReplacement(
2702 SuperLoc, getLangOpts().ObjCAutoRefCount
2703 ? "self"
2704 : Method->getClassInterface()->getName());
2705 Diag(Method->getLocation(), diag::note_direct_method_declared_at)
2706 << Method->getDeclName();
2707 }
2708
2709 // Warn about explicit call of +initialize on its own class. But not on 'super'.
2710 if (Method && Method->getMethodFamily() == OMF_initialize) {
2711 if (!SuperLoc.isValid()) {
2712 const ObjCInterfaceDecl *ID =
2713 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext());
2714 if (ID == Class) {
2715 Diag(Loc, diag::warn_direct_initialize_call);
2716 Diag(Method->getLocation(), diag::note_method_declared_at)
2717 << Method->getDeclName();
2718 }
2719 }
2720 else if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2721 // [super initialize] is allowed only within an +initialize implementation
2722 if (CurMeth->getMethodFamily() != OMF_initialize) {
2723 Diag(Loc, diag::warn_direct_super_initialize_call);
2724 Diag(Method->getLocation(), diag::note_method_declared_at)
2725 << Method->getDeclName();
2726 Diag(CurMeth->getLocation(), diag::note_method_declared_at)
2727 << CurMeth->getDeclName();
2728 }
2729 }
2730 }
2731
2732 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
2733
2734 // Construct the appropriate ObjCMessageExpr.
2735 ObjCMessageExpr *Result;
2736 if (SuperLoc.isValid())
2737 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2738 SuperLoc, /*IsInstanceSuper=*/false,
2739 ReceiverType, Sel, SelectorLocs,
2740 Method, makeArrayRef(Args, NumArgs),
2741 RBracLoc, isImplicit);
2742 else {
2743 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2744 ReceiverTypeInfo, Sel, SelectorLocs,
2745 Method, makeArrayRef(Args, NumArgs),
2746 RBracLoc, isImplicit);
2747 if (!isImplicit)
2748 checkCocoaAPI(*this, Result);
2749 }
2750 if (Method)
2751 checkFoundationAPI(*this, SelLoc, Method, makeArrayRef(Args, NumArgs),
2752 ReceiverType, /*IsClassObjectCall=*/true);
2753 return MaybeBindToTemporary(Result);
2754 }
2755
2756 // ActOnClassMessage - used for both unary and keyword messages.
2757 // ArgExprs is optional - if it is present, the number of expressions
2758 // is obtained from Sel.getNumArgs().
ActOnClassMessage(Scope * S,ParsedType Receiver,Selector Sel,SourceLocation LBracLoc,ArrayRef<SourceLocation> SelectorLocs,SourceLocation RBracLoc,MultiExprArg Args)2759 ExprResult Sema::ActOnClassMessage(Scope *S,
2760 ParsedType Receiver,
2761 Selector Sel,
2762 SourceLocation LBracLoc,
2763 ArrayRef<SourceLocation> SelectorLocs,
2764 SourceLocation RBracLoc,
2765 MultiExprArg Args) {
2766 TypeSourceInfo *ReceiverTypeInfo;
2767 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2768 if (ReceiverType.isNull())
2769 return ExprError();
2770
2771 if (!ReceiverTypeInfo)
2772 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2773
2774 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
2775 /*SuperLoc=*/SourceLocation(), Sel,
2776 /*Method=*/nullptr, LBracLoc, SelectorLocs, RBracLoc,
2777 Args);
2778 }
2779
BuildInstanceMessageImplicit(Expr * Receiver,QualType ReceiverType,SourceLocation Loc,Selector Sel,ObjCMethodDecl * Method,MultiExprArg Args)2780 ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2781 QualType ReceiverType,
2782 SourceLocation Loc,
2783 Selector Sel,
2784 ObjCMethodDecl *Method,
2785 MultiExprArg Args) {
2786 return BuildInstanceMessage(Receiver, ReceiverType,
2787 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2788 Sel, Method, Loc, Loc, Loc, Args,
2789 /*isImplicit=*/true);
2790 }
2791
isMethodDeclaredInRootProtocol(Sema & S,const ObjCMethodDecl * M)2792 static bool isMethodDeclaredInRootProtocol(Sema &S, const ObjCMethodDecl *M) {
2793 if (!S.NSAPIObj)
2794 return false;
2795 const auto *Protocol = dyn_cast<ObjCProtocolDecl>(M->getDeclContext());
2796 if (!Protocol)
2797 return false;
2798 const IdentifierInfo *II = S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
2799 if (const auto *RootClass = dyn_cast_or_null<ObjCInterfaceDecl>(
2800 S.LookupSingleName(S.TUScope, II, Protocol->getBeginLoc(),
2801 Sema::LookupOrdinaryName))) {
2802 for (const ObjCProtocolDecl *P : RootClass->all_referenced_protocols()) {
2803 if (P->getCanonicalDecl() == Protocol->getCanonicalDecl())
2804 return true;
2805 }
2806 }
2807 return false;
2808 }
2809
2810 /// Build an Objective-C instance message expression.
2811 ///
2812 /// This routine takes care of both normal instance messages and
2813 /// instance messages to the superclass instance.
2814 ///
2815 /// \param Receiver The expression that computes the object that will
2816 /// receive this message. This may be empty, in which case we are
2817 /// sending to the superclass instance and \p SuperLoc must be a valid
2818 /// source location.
2819 ///
2820 /// \param ReceiverType The (static) type of the object receiving the
2821 /// message. When a \p Receiver expression is provided, this is the
2822 /// same type as that expression. For a superclass instance send, this
2823 /// is a pointer to the type of the superclass.
2824 ///
2825 /// \param SuperLoc The location of the "super" keyword in a
2826 /// superclass instance message.
2827 ///
2828 /// \param Sel The selector to which the message is being sent.
2829 ///
2830 /// \param Method The method that this instance message is invoking, if
2831 /// already known.
2832 ///
2833 /// \param LBracLoc The location of the opening square bracket ']'.
2834 ///
2835 /// \param RBracLoc The location of the closing square bracket ']'.
2836 ///
2837 /// \param ArgsIn The message arguments.
BuildInstanceMessage(Expr * Receiver,QualType ReceiverType,SourceLocation SuperLoc,Selector Sel,ObjCMethodDecl * Method,SourceLocation LBracLoc,ArrayRef<SourceLocation> SelectorLocs,SourceLocation RBracLoc,MultiExprArg ArgsIn,bool isImplicit)2838 ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
2839 QualType ReceiverType,
2840 SourceLocation SuperLoc,
2841 Selector Sel,
2842 ObjCMethodDecl *Method,
2843 SourceLocation LBracLoc,
2844 ArrayRef<SourceLocation> SelectorLocs,
2845 SourceLocation RBracLoc,
2846 MultiExprArg ArgsIn,
2847 bool isImplicit) {
2848 assert((Receiver || SuperLoc.isValid()) && "If the Receiver is null, the "
2849 "SuperLoc must be valid so we can "
2850 "use it instead.");
2851
2852 // The location of the receiver.
2853 SourceLocation Loc = SuperLoc.isValid() ? SuperLoc : Receiver->getBeginLoc();
2854 SourceRange RecRange =
2855 SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange();
2856 ArrayRef<SourceLocation> SelectorSlotLocs;
2857 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2858 SelectorSlotLocs = SelectorLocs;
2859 else
2860 SelectorSlotLocs = Loc;
2861 SourceLocation SelLoc = SelectorSlotLocs.front();
2862
2863 if (LBracLoc.isInvalid()) {
2864 Diag(Loc, diag::err_missing_open_square_message_send)
2865 << FixItHint::CreateInsertion(Loc, "[");
2866 LBracLoc = Loc;
2867 }
2868
2869 // If we have a receiver expression, perform appropriate promotions
2870 // and determine receiver type.
2871 if (Receiver) {
2872 if (Receiver->hasPlaceholderType()) {
2873 ExprResult Result;
2874 if (Receiver->getType() == Context.UnknownAnyTy)
2875 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2876 else
2877 Result = CheckPlaceholderExpr(Receiver);
2878 if (Result.isInvalid()) return ExprError();
2879 Receiver = Result.get();
2880 }
2881
2882 if (Receiver->isTypeDependent()) {
2883 // If the receiver is type-dependent, we can't type-check anything
2884 // at this point. Build a dependent expression.
2885 unsigned NumArgs = ArgsIn.size();
2886 Expr **Args = ArgsIn.data();
2887 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2888 return ObjCMessageExpr::Create(
2889 Context, Context.DependentTy, VK_RValue, LBracLoc, Receiver, Sel,
2890 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs),
2891 RBracLoc, isImplicit);
2892 }
2893
2894 // If necessary, apply function/array conversion to the receiver.
2895 // C99 6.7.5.3p[7,8].
2896 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2897 if (Result.isInvalid())
2898 return ExprError();
2899 Receiver = Result.get();
2900 ReceiverType = Receiver->getType();
2901
2902 // If the receiver is an ObjC pointer, a block pointer, or an
2903 // __attribute__((NSObject)) pointer, we don't need to do any
2904 // special conversion in order to look up a receiver.
2905 if (ReceiverType->isObjCRetainableType()) {
2906 // do nothing
2907 } else if (!getLangOpts().ObjCAutoRefCount &&
2908 !Context.getObjCIdType().isNull() &&
2909 (ReceiverType->isPointerType() ||
2910 ReceiverType->isIntegerType())) {
2911 // Implicitly convert integers and pointers to 'id' but emit a warning.
2912 // But not in ARC.
2913 Diag(Loc, diag::warn_bad_receiver_type) << ReceiverType << RecRange;
2914 if (ReceiverType->isPointerType()) {
2915 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2916 CK_CPointerToObjCPointerCast).get();
2917 } else {
2918 // TODO: specialized warning on null receivers?
2919 bool IsNull = Receiver->isNullPointerConstant(Context,
2920 Expr::NPC_ValueDependentIsNull);
2921 CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
2922 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2923 Kind).get();
2924 }
2925 ReceiverType = Receiver->getType();
2926 } else if (getLangOpts().CPlusPlus) {
2927 // The receiver must be a complete type.
2928 if (RequireCompleteType(Loc, Receiver->getType(),
2929 diag::err_incomplete_receiver_type))
2930 return ExprError();
2931
2932 ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
2933 if (result.isUsable()) {
2934 Receiver = result.get();
2935 ReceiverType = Receiver->getType();
2936 }
2937 }
2938 }
2939
2940 // There's a somewhat weird interaction here where we assume that we
2941 // won't actually have a method unless we also don't need to do some
2942 // of the more detailed type-checking on the receiver.
2943
2944 if (!Method) {
2945 // Handle messages to id and __kindof types (where we use the
2946 // global method pool).
2947 const ObjCObjectType *typeBound = nullptr;
2948 bool receiverIsIdLike = ReceiverType->isObjCIdOrObjectKindOfType(Context,
2949 typeBound);
2950 if (receiverIsIdLike || ReceiverType->isBlockPointerType() ||
2951 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
2952 SmallVector<ObjCMethodDecl*, 4> Methods;
2953 // If we have a type bound, further filter the methods.
2954 CollectMultipleMethodsInGlobalPool(Sel, Methods, true/*InstanceFirst*/,
2955 true/*CheckTheOther*/, typeBound);
2956 if (!Methods.empty()) {
2957 // We choose the first method as the initial candidate, then try to
2958 // select a better one.
2959 Method = Methods[0];
2960
2961 if (ObjCMethodDecl *BestMethod =
2962 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(), Methods))
2963 Method = BestMethod;
2964
2965 if (!AreMultipleMethodsInGlobalPool(Sel, Method,
2966 SourceRange(LBracLoc, RBracLoc),
2967 receiverIsIdLike, Methods))
2968 DiagnoseUseOfDecl(Method, SelectorSlotLocs);
2969 }
2970 } else if (ReceiverType->isObjCClassOrClassKindOfType() ||
2971 ReceiverType->isObjCQualifiedClassType()) {
2972 // Handle messages to Class.
2973 // We allow sending a message to a qualified Class ("Class<foo>"), which
2974 // is ok as long as one of the protocols implements the selector (if not,
2975 // warn).
2976 if (!ReceiverType->isObjCClassOrClassKindOfType()) {
2977 const ObjCObjectPointerType *QClassTy
2978 = ReceiverType->getAsObjCQualifiedClassType();
2979 // Search protocols for class methods.
2980 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2981 if (!Method) {
2982 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2983 // warn if instance method found for a Class message.
2984 if (Method && !isMethodDeclaredInRootProtocol(*this, Method)) {
2985 Diag(SelLoc, diag::warn_instance_method_on_class_found)
2986 << Method->getSelector() << Sel;
2987 Diag(Method->getLocation(), diag::note_method_declared_at)
2988 << Method->getDeclName();
2989 }
2990 }
2991 } else {
2992 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2993 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2994 // As a guess, try looking for the method in the current interface.
2995 // This very well may not produce the "right" method.
2996
2997 // First check the public methods in the class interface.
2998 Method = ClassDecl->lookupClassMethod(Sel);
2999
3000 if (!Method)
3001 Method = ClassDecl->lookupPrivateClassMethod(Sel);
3002
3003 if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs))
3004 return ExprError();
3005 }
3006 }
3007 if (!Method) {
3008 // If not messaging 'self', look for any factory method named 'Sel'.
3009 if (!Receiver || !isSelfExpr(Receiver)) {
3010 // If no class (factory) method was found, check if an _instance_
3011 // method of the same name exists in the root class only.
3012 SmallVector<ObjCMethodDecl*, 4> Methods;
3013 CollectMultipleMethodsInGlobalPool(Sel, Methods,
3014 false/*InstanceFirst*/,
3015 true/*CheckTheOther*/);
3016 if (!Methods.empty()) {
3017 // We choose the first method as the initial candidate, then try
3018 // to select a better one.
3019 Method = Methods[0];
3020
3021 // If we find an instance method, emit warning.
3022 if (Method->isInstanceMethod()) {
3023 if (const ObjCInterfaceDecl *ID =
3024 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
3025 if (ID->getSuperClass())
3026 Diag(SelLoc, diag::warn_root_inst_method_not_found)
3027 << Sel << SourceRange(LBracLoc, RBracLoc);
3028 }
3029 }
3030
3031 if (ObjCMethodDecl *BestMethod =
3032 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(),
3033 Methods))
3034 Method = BestMethod;
3035 }
3036 }
3037 }
3038 }
3039 } else {
3040 ObjCInterfaceDecl *ClassDecl = nullptr;
3041
3042 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
3043 // long as one of the protocols implements the selector (if not, warn).
3044 // And as long as message is not deprecated/unavailable (warn if it is).
3045 if (const ObjCObjectPointerType *QIdTy
3046 = ReceiverType->getAsObjCQualifiedIdType()) {
3047 // Search protocols for instance methods.
3048 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
3049 if (!Method)
3050 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
3051 if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs))
3052 return ExprError();
3053 } else if (const ObjCObjectPointerType *OCIType
3054 = ReceiverType->getAsObjCInterfacePointerType()) {
3055 // We allow sending a message to a pointer to an interface (an object).
3056 ClassDecl = OCIType->getInterfaceDecl();
3057
3058 // Try to complete the type. Under ARC, this is a hard error from which
3059 // we don't try to recover.
3060 // FIXME: In the non-ARC case, this will still be a hard error if the
3061 // definition is found in a module that's not visible.
3062 const ObjCInterfaceDecl *forwardClass = nullptr;
3063 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
3064 getLangOpts().ObjCAutoRefCount
3065 ? diag::err_arc_receiver_forward_instance
3066 : diag::warn_receiver_forward_instance,
3067 RecRange)) {
3068 if (getLangOpts().ObjCAutoRefCount)
3069 return ExprError();
3070
3071 forwardClass = OCIType->getInterfaceDecl();
3072 Diag(Receiver ? Receiver->getBeginLoc() : SuperLoc,
3073 diag::note_receiver_is_id);
3074 Method = nullptr;
3075 } else {
3076 Method = ClassDecl->lookupInstanceMethod(Sel);
3077 }
3078
3079 if (!Method)
3080 // Search protocol qualifiers.
3081 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
3082
3083 if (!Method) {
3084 // If we have implementations in scope, check "private" methods.
3085 Method = ClassDecl->lookupPrivateMethod(Sel);
3086
3087 if (!Method && getLangOpts().ObjCAutoRefCount) {
3088 Diag(SelLoc, diag::err_arc_may_not_respond)
3089 << OCIType->getPointeeType() << Sel << RecRange
3090 << SourceRange(SelectorLocs.front(), SelectorLocs.back());
3091 return ExprError();
3092 }
3093
3094 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
3095 // If we still haven't found a method, look in the global pool. This
3096 // behavior isn't very desirable, however we need it for GCC
3097 // compatibility. FIXME: should we deviate??
3098 if (OCIType->qual_empty()) {
3099 SmallVector<ObjCMethodDecl*, 4> Methods;
3100 CollectMultipleMethodsInGlobalPool(Sel, Methods,
3101 true/*InstanceFirst*/,
3102 false/*CheckTheOther*/);
3103 if (!Methods.empty()) {
3104 // We choose the first method as the initial candidate, then try
3105 // to select a better one.
3106 Method = Methods[0];
3107
3108 if (ObjCMethodDecl *BestMethod =
3109 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(),
3110 Methods))
3111 Method = BestMethod;
3112
3113 AreMultipleMethodsInGlobalPool(Sel, Method,
3114 SourceRange(LBracLoc, RBracLoc),
3115 true/*receiverIdOrClass*/,
3116 Methods);
3117 }
3118 if (Method && !forwardClass)
3119 Diag(SelLoc, diag::warn_maynot_respond)
3120 << OCIType->getInterfaceDecl()->getIdentifier()
3121 << Sel << RecRange;
3122 }
3123 }
3124 }
3125 if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs, forwardClass))
3126 return ExprError();
3127 } else {
3128 // Reject other random receiver types (e.g. structs).
3129 Diag(Loc, diag::err_bad_receiver_type) << ReceiverType << RecRange;
3130 return ExprError();
3131 }
3132 }
3133 }
3134
3135 FunctionScopeInfo *DIFunctionScopeInfo =
3136 (Method && Method->getMethodFamily() == OMF_init)
3137 ? getEnclosingFunction() : nullptr;
3138
3139 if (Method && Method->isDirectMethod()) {
3140 if (ReceiverType->isObjCIdType() && !isImplicit) {
3141 Diag(Receiver->getExprLoc(),
3142 diag::err_messaging_unqualified_id_with_direct_method);
3143 Diag(Method->getLocation(), diag::note_direct_method_declared_at)
3144 << Method->getDeclName();
3145 }
3146
3147 // Under ARC, self can't be assigned, and doing a direct call to `self`
3148 // when it's a Class is hence safe. For other cases, we can't trust `self`
3149 // is what we think it is, so we reject it.
3150 if (ReceiverType->isObjCClassType() && !isImplicit &&
3151 !(Receiver->isObjCSelfExpr() && getLangOpts().ObjCAutoRefCount)) {
3152 {
3153 auto Builder = Diag(Receiver->getExprLoc(),
3154 diag::err_messaging_class_with_direct_method);
3155 if (Receiver->isObjCSelfExpr()) {
3156 Builder.AddFixItHint(FixItHint::CreateReplacement(
3157 RecRange, Method->getClassInterface()->getName()));
3158 }
3159 }
3160 Diag(Method->getLocation(), diag::note_direct_method_declared_at)
3161 << Method->getDeclName();
3162 }
3163
3164 if (SuperLoc.isValid()) {
3165 {
3166 auto Builder =
3167 Diag(SuperLoc, diag::err_messaging_super_with_direct_method);
3168 if (ReceiverType->isObjCClassType()) {
3169 Builder.AddFixItHint(FixItHint::CreateReplacement(
3170 SuperLoc, Method->getClassInterface()->getName()));
3171 } else {
3172 Builder.AddFixItHint(FixItHint::CreateReplacement(SuperLoc, "self"));
3173 }
3174 }
3175 Diag(Method->getLocation(), diag::note_direct_method_declared_at)
3176 << Method->getDeclName();
3177 }
3178 } else if (ReceiverType->isObjCIdType() && !isImplicit) {
3179 Diag(Receiver->getExprLoc(), diag::warn_messaging_unqualified_id);
3180 }
3181
3182 if (DIFunctionScopeInfo &&
3183 DIFunctionScopeInfo->ObjCIsDesignatedInit &&
3184 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
3185 bool isDesignatedInitChain = false;
3186 if (SuperLoc.isValid()) {
3187 if (const ObjCObjectPointerType *
3188 OCIType = ReceiverType->getAsObjCInterfacePointerType()) {
3189 if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) {
3190 // Either we know this is a designated initializer or we
3191 // conservatively assume it because we don't know for sure.
3192 if (!ID->declaresOrInheritsDesignatedInitializers() ||
3193 ID->isDesignatedInitializer(Sel)) {
3194 isDesignatedInitChain = true;
3195 DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false;
3196 }
3197 }
3198 }
3199 }
3200 if (!isDesignatedInitChain) {
3201 const ObjCMethodDecl *InitMethod = nullptr;
3202 bool isDesignated =
3203 getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod);
3204 assert(isDesignated && InitMethod);
3205 (void)isDesignated;
3206 Diag(SelLoc, SuperLoc.isValid() ?
3207 diag::warn_objc_designated_init_non_designated_init_call :
3208 diag::warn_objc_designated_init_non_super_designated_init_call);
3209 Diag(InitMethod->getLocation(),
3210 diag::note_objc_designated_init_marked_here);
3211 }
3212 }
3213
3214 if (DIFunctionScopeInfo &&
3215 DIFunctionScopeInfo->ObjCIsSecondaryInit &&
3216 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
3217 if (SuperLoc.isValid()) {
3218 Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call);
3219 } else {
3220 DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false;
3221 }
3222 }
3223
3224 // Check the message arguments.
3225 unsigned NumArgs = ArgsIn.size();
3226 Expr **Args = ArgsIn.data();
3227 QualType ReturnType;
3228 ExprValueKind VK = VK_RValue;
3229 bool ClassMessage = (ReceiverType->isObjCClassType() ||
3230 ReceiverType->isObjCQualifiedClassType());
3231 if (CheckMessageArgumentTypes(Receiver, ReceiverType,
3232 MultiExprArg(Args, NumArgs), Sel, SelectorLocs,
3233 Method, ClassMessage, SuperLoc.isValid(),
3234 LBracLoc, RBracLoc, RecRange, ReturnType, VK))
3235 return ExprError();
3236
3237 if (Method && !Method->getReturnType()->isVoidType() &&
3238 RequireCompleteType(LBracLoc, Method->getReturnType(),
3239 diag::err_illegal_message_expr_incomplete_type))
3240 return ExprError();
3241
3242 // In ARC, forbid the user from sending messages to
3243 // retain/release/autorelease/dealloc/retainCount explicitly.
3244 if (getLangOpts().ObjCAutoRefCount) {
3245 ObjCMethodFamily family =
3246 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
3247 switch (family) {
3248 case OMF_init:
3249 if (Method)
3250 checkInitMethod(Method, ReceiverType);
3251 break;
3252
3253 case OMF_None:
3254 case OMF_alloc:
3255 case OMF_copy:
3256 case OMF_finalize:
3257 case OMF_mutableCopy:
3258 case OMF_new:
3259 case OMF_self:
3260 case OMF_initialize:
3261 break;
3262
3263 case OMF_dealloc:
3264 case OMF_retain:
3265 case OMF_release:
3266 case OMF_autorelease:
3267 case OMF_retainCount:
3268 Diag(SelLoc, diag::err_arc_illegal_explicit_message)
3269 << Sel << RecRange;
3270 break;
3271
3272 case OMF_performSelector:
3273 if (Method && NumArgs >= 1) {
3274 if (const auto *SelExp =
3275 dyn_cast<ObjCSelectorExpr>(Args[0]->IgnoreParens())) {
3276 Selector ArgSel = SelExp->getSelector();
3277 ObjCMethodDecl *SelMethod =
3278 LookupInstanceMethodInGlobalPool(ArgSel,
3279 SelExp->getSourceRange());
3280 if (!SelMethod)
3281 SelMethod =
3282 LookupFactoryMethodInGlobalPool(ArgSel,
3283 SelExp->getSourceRange());
3284 if (SelMethod) {
3285 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
3286 switch (SelFamily) {
3287 case OMF_alloc:
3288 case OMF_copy:
3289 case OMF_mutableCopy:
3290 case OMF_new:
3291 case OMF_init:
3292 // Issue error, unless ns_returns_not_retained.
3293 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
3294 // selector names a +1 method
3295 Diag(SelLoc,
3296 diag::err_arc_perform_selector_retains);
3297 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
3298 << SelMethod->getDeclName();
3299 }
3300 break;
3301 default:
3302 // +0 call. OK. unless ns_returns_retained.
3303 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
3304 // selector names a +1 method
3305 Diag(SelLoc,
3306 diag::err_arc_perform_selector_retains);
3307 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
3308 << SelMethod->getDeclName();
3309 }
3310 break;
3311 }
3312 }
3313 } else {
3314 // error (may leak).
3315 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
3316 Diag(Args[0]->getExprLoc(), diag::note_used_here);
3317 }
3318 }
3319 break;
3320 }
3321 }
3322
3323 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
3324
3325 // Construct the appropriate ObjCMessageExpr instance.
3326 ObjCMessageExpr *Result;
3327 if (SuperLoc.isValid())
3328 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
3329 SuperLoc, /*IsInstanceSuper=*/true,
3330 ReceiverType, Sel, SelectorLocs, Method,
3331 makeArrayRef(Args, NumArgs), RBracLoc,
3332 isImplicit);
3333 else {
3334 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
3335 Receiver, Sel, SelectorLocs, Method,
3336 makeArrayRef(Args, NumArgs), RBracLoc,
3337 isImplicit);
3338 if (!isImplicit)
3339 checkCocoaAPI(*this, Result);
3340 }
3341 if (Method) {
3342 bool IsClassObjectCall = ClassMessage;
3343 // 'self' message receivers in class methods should be treated as message
3344 // sends to the class object in order for the semantic checks to be
3345 // performed correctly. Messages to 'super' already count as class messages,
3346 // so they don't need to be handled here.
3347 if (Receiver && isSelfExpr(Receiver)) {
3348 if (const auto *OPT = ReceiverType->getAs<ObjCObjectPointerType>()) {
3349 if (OPT->getObjectType()->isObjCClass()) {
3350 if (const auto *CurMeth = getCurMethodDecl()) {
3351 IsClassObjectCall = true;
3352 ReceiverType =
3353 Context.getObjCInterfaceType(CurMeth->getClassInterface());
3354 }
3355 }
3356 }
3357 }
3358 checkFoundationAPI(*this, SelLoc, Method, makeArrayRef(Args, NumArgs),
3359 ReceiverType, IsClassObjectCall);
3360 }
3361
3362 if (getLangOpts().ObjCAutoRefCount) {
3363 // In ARC, annotate delegate init calls.
3364 if (Result->getMethodFamily() == OMF_init &&
3365 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
3366 // Only consider init calls *directly* in init implementations,
3367 // not within blocks.
3368 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
3369 if (method && method->getMethodFamily() == OMF_init) {
3370 // The implicit assignment to self means we also don't want to
3371 // consume the result.
3372 Result->setDelegateInitCall(true);
3373 return Result;
3374 }
3375 }
3376
3377 // In ARC, check for message sends which are likely to introduce
3378 // retain cycles.
3379 checkRetainCycles(Result);
3380 }
3381
3382 if (getLangOpts().ObjCWeak) {
3383 if (!isImplicit && Method) {
3384 if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
3385 bool IsWeak =
3386 Prop->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak;
3387 if (!IsWeak && Sel.isUnarySelector())
3388 IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
3389 if (IsWeak && !isUnevaluatedContext() &&
3390 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, LBracLoc))
3391 getCurFunction()->recordUseOfWeak(Result, Prop);
3392 }
3393 }
3394 }
3395
3396 CheckObjCCircularContainer(Result);
3397
3398 return MaybeBindToTemporary(Result);
3399 }
3400
RemoveSelectorFromWarningCache(Sema & S,Expr * Arg)3401 static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
3402 if (ObjCSelectorExpr *OSE =
3403 dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
3404 Selector Sel = OSE->getSelector();
3405 SourceLocation Loc = OSE->getAtLoc();
3406 auto Pos = S.ReferencedSelectors.find(Sel);
3407 if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
3408 S.ReferencedSelectors.erase(Pos);
3409 }
3410 }
3411
3412 // ActOnInstanceMessage - used for both unary and keyword messages.
3413 // ArgExprs is optional - if it is present, the number of expressions
3414 // is obtained from Sel.getNumArgs().
ActOnInstanceMessage(Scope * S,Expr * Receiver,Selector Sel,SourceLocation LBracLoc,ArrayRef<SourceLocation> SelectorLocs,SourceLocation RBracLoc,MultiExprArg Args)3415 ExprResult Sema::ActOnInstanceMessage(Scope *S,
3416 Expr *Receiver,
3417 Selector Sel,
3418 SourceLocation LBracLoc,
3419 ArrayRef<SourceLocation> SelectorLocs,
3420 SourceLocation RBracLoc,
3421 MultiExprArg Args) {
3422 if (!Receiver)
3423 return ExprError();
3424
3425 // A ParenListExpr can show up while doing error recovery with invalid code.
3426 if (isa<ParenListExpr>(Receiver)) {
3427 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
3428 if (Result.isInvalid()) return ExprError();
3429 Receiver = Result.get();
3430 }
3431
3432 if (RespondsToSelectorSel.isNull()) {
3433 IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
3434 RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
3435 }
3436 if (Sel == RespondsToSelectorSel)
3437 RemoveSelectorFromWarningCache(*this, Args[0]);
3438
3439 return BuildInstanceMessage(Receiver, Receiver->getType(),
3440 /*SuperLoc=*/SourceLocation(), Sel,
3441 /*Method=*/nullptr, LBracLoc, SelectorLocs,
3442 RBracLoc, Args);
3443 }
3444
3445 enum ARCConversionTypeClass {
3446 /// int, void, struct A
3447 ACTC_none,
3448
3449 /// id, void (^)()
3450 ACTC_retainable,
3451
3452 /// id*, id***, void (^*)(),
3453 ACTC_indirectRetainable,
3454
3455 /// void* might be a normal C type, or it might a CF type.
3456 ACTC_voidPtr,
3457
3458 /// struct A*
3459 ACTC_coreFoundation
3460 };
3461
isAnyRetainable(ARCConversionTypeClass ACTC)3462 static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
3463 return (ACTC == ACTC_retainable ||
3464 ACTC == ACTC_coreFoundation ||
3465 ACTC == ACTC_voidPtr);
3466 }
3467
isAnyCLike(ARCConversionTypeClass ACTC)3468 static bool isAnyCLike(ARCConversionTypeClass ACTC) {
3469 return ACTC == ACTC_none ||
3470 ACTC == ACTC_voidPtr ||
3471 ACTC == ACTC_coreFoundation;
3472 }
3473
classifyTypeForARCConversion(QualType type)3474 static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
3475 bool isIndirect = false;
3476
3477 // Ignore an outermost reference type.
3478 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
3479 type = ref->getPointeeType();
3480 isIndirect = true;
3481 }
3482
3483 // Drill through pointers and arrays recursively.
3484 while (true) {
3485 if (const PointerType *ptr = type->getAs<PointerType>()) {
3486 type = ptr->getPointeeType();
3487
3488 // The first level of pointer may be the innermost pointer on a CF type.
3489 if (!isIndirect) {
3490 if (type->isVoidType()) return ACTC_voidPtr;
3491 if (type->isRecordType()) return ACTC_coreFoundation;
3492 }
3493 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
3494 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
3495 } else {
3496 break;
3497 }
3498 isIndirect = true;
3499 }
3500
3501 if (isIndirect) {
3502 if (type->isObjCARCBridgableType())
3503 return ACTC_indirectRetainable;
3504 return ACTC_none;
3505 }
3506
3507 if (type->isObjCARCBridgableType())
3508 return ACTC_retainable;
3509
3510 return ACTC_none;
3511 }
3512
3513 namespace {
3514 /// A result from the cast checker.
3515 enum ACCResult {
3516 /// Cannot be casted.
3517 ACC_invalid,
3518
3519 /// Can be safely retained or not retained.
3520 ACC_bottom,
3521
3522 /// Can be casted at +0.
3523 ACC_plusZero,
3524
3525 /// Can be casted at +1.
3526 ACC_plusOne
3527 };
merge(ACCResult left,ACCResult right)3528 ACCResult merge(ACCResult left, ACCResult right) {
3529 if (left == right) return left;
3530 if (left == ACC_bottom) return right;
3531 if (right == ACC_bottom) return left;
3532 return ACC_invalid;
3533 }
3534
3535 /// A checker which white-lists certain expressions whose conversion
3536 /// to or from retainable type would otherwise be forbidden in ARC.
3537 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
3538 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
3539
3540 ASTContext &Context;
3541 ARCConversionTypeClass SourceClass;
3542 ARCConversionTypeClass TargetClass;
3543 bool Diagnose;
3544
isCFType(QualType type)3545 static bool isCFType(QualType type) {
3546 // Someday this can use ns_bridged. For now, it has to do this.
3547 return type->isCARCBridgableType();
3548 }
3549
3550 public:
ARCCastChecker(ASTContext & Context,ARCConversionTypeClass source,ARCConversionTypeClass target,bool diagnose)3551 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
3552 ARCConversionTypeClass target, bool diagnose)
3553 : Context(Context), SourceClass(source), TargetClass(target),
3554 Diagnose(diagnose) {}
3555
3556 using super::Visit;
Visit(Expr * e)3557 ACCResult Visit(Expr *e) {
3558 return super::Visit(e->IgnoreParens());
3559 }
3560
VisitStmt(Stmt * s)3561 ACCResult VisitStmt(Stmt *s) {
3562 return ACC_invalid;
3563 }
3564
3565 /// Null pointer constants can be casted however you please.
VisitExpr(Expr * e)3566 ACCResult VisitExpr(Expr *e) {
3567 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
3568 return ACC_bottom;
3569 return ACC_invalid;
3570 }
3571
3572 /// Objective-C string literals can be safely casted.
VisitObjCStringLiteral(ObjCStringLiteral * e)3573 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
3574 // If we're casting to any retainable type, go ahead. Global
3575 // strings are immune to retains, so this is bottom.
3576 if (isAnyRetainable(TargetClass)) return ACC_bottom;
3577
3578 return ACC_invalid;
3579 }
3580
3581 /// Look through certain implicit and explicit casts.
VisitCastExpr(CastExpr * e)3582 ACCResult VisitCastExpr(CastExpr *e) {
3583 switch (e->getCastKind()) {
3584 case CK_NullToPointer:
3585 return ACC_bottom;
3586
3587 case CK_NoOp:
3588 case CK_LValueToRValue:
3589 case CK_BitCast:
3590 case CK_CPointerToObjCPointerCast:
3591 case CK_BlockPointerToObjCPointerCast:
3592 case CK_AnyPointerToBlockPointerCast:
3593 return Visit(e->getSubExpr());
3594
3595 default:
3596 return ACC_invalid;
3597 }
3598 }
3599
3600 /// Look through unary extension.
VisitUnaryExtension(UnaryOperator * e)3601 ACCResult VisitUnaryExtension(UnaryOperator *e) {
3602 return Visit(e->getSubExpr());
3603 }
3604
3605 /// Ignore the LHS of a comma operator.
VisitBinComma(BinaryOperator * e)3606 ACCResult VisitBinComma(BinaryOperator *e) {
3607 return Visit(e->getRHS());
3608 }
3609
3610 /// Conditional operators are okay if both sides are okay.
VisitConditionalOperator(ConditionalOperator * e)3611 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
3612 ACCResult left = Visit(e->getTrueExpr());
3613 if (left == ACC_invalid) return ACC_invalid;
3614 return merge(left, Visit(e->getFalseExpr()));
3615 }
3616
3617 /// Look through pseudo-objects.
VisitPseudoObjectExpr(PseudoObjectExpr * e)3618 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
3619 // If we're getting here, we should always have a result.
3620 return Visit(e->getResultExpr());
3621 }
3622
3623 /// Statement expressions are okay if their result expression is okay.
VisitStmtExpr(StmtExpr * e)3624 ACCResult VisitStmtExpr(StmtExpr *e) {
3625 return Visit(e->getSubStmt()->body_back());
3626 }
3627
3628 /// Some declaration references are okay.
VisitDeclRefExpr(DeclRefExpr * e)3629 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
3630 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
3631 // References to global constants are okay.
3632 if (isAnyRetainable(TargetClass) &&
3633 isAnyRetainable(SourceClass) &&
3634 var &&
3635 !var->hasDefinition(Context) &&
3636 var->getType().isConstQualified()) {
3637
3638 // In system headers, they can also be assumed to be immune to retains.
3639 // These are things like 'kCFStringTransformToLatin'.
3640 if (Context.getSourceManager().isInSystemHeader(var->getLocation()))
3641 return ACC_bottom;
3642
3643 return ACC_plusZero;
3644 }
3645
3646 // Nothing else.
3647 return ACC_invalid;
3648 }
3649
3650 /// Some calls are okay.
VisitCallExpr(CallExpr * e)3651 ACCResult VisitCallExpr(CallExpr *e) {
3652 if (FunctionDecl *fn = e->getDirectCallee())
3653 if (ACCResult result = checkCallToFunction(fn))
3654 return result;
3655
3656 return super::VisitCallExpr(e);
3657 }
3658
checkCallToFunction(FunctionDecl * fn)3659 ACCResult checkCallToFunction(FunctionDecl *fn) {
3660 // Require a CF*Ref return type.
3661 if (!isCFType(fn->getReturnType()))
3662 return ACC_invalid;
3663
3664 if (!isAnyRetainable(TargetClass))
3665 return ACC_invalid;
3666
3667 // Honor an explicit 'not retained' attribute.
3668 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
3669 return ACC_plusZero;
3670
3671 // Honor an explicit 'retained' attribute, except that for
3672 // now we're not going to permit implicit handling of +1 results,
3673 // because it's a bit frightening.
3674 if (fn->hasAttr<CFReturnsRetainedAttr>())
3675 return Diagnose ? ACC_plusOne
3676 : ACC_invalid; // ACC_plusOne if we start accepting this
3677
3678 // Recognize this specific builtin function, which is used by CFSTR.
3679 unsigned builtinID = fn->getBuiltinID();
3680 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
3681 return ACC_bottom;
3682
3683 // Otherwise, don't do anything implicit with an unaudited function.
3684 if (!fn->hasAttr<CFAuditedTransferAttr>())
3685 return ACC_invalid;
3686
3687 // Otherwise, it's +0 unless it follows the create convention.
3688 if (ento::coreFoundation::followsCreateRule(fn))
3689 return Diagnose ? ACC_plusOne
3690 : ACC_invalid; // ACC_plusOne if we start accepting this
3691
3692 return ACC_plusZero;
3693 }
3694
VisitObjCMessageExpr(ObjCMessageExpr * e)3695 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
3696 return checkCallToMethod(e->getMethodDecl());
3697 }
3698
VisitObjCPropertyRefExpr(ObjCPropertyRefExpr * e)3699 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
3700 ObjCMethodDecl *method;
3701 if (e->isExplicitProperty())
3702 method = e->getExplicitProperty()->getGetterMethodDecl();
3703 else
3704 method = e->getImplicitPropertyGetter();
3705 return checkCallToMethod(method);
3706 }
3707
checkCallToMethod(ObjCMethodDecl * method)3708 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
3709 if (!method) return ACC_invalid;
3710
3711 // Check for message sends to functions returning CF types. We
3712 // just obey the Cocoa conventions with these, even though the
3713 // return type is CF.
3714 if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType()))
3715 return ACC_invalid;
3716
3717 // If the method is explicitly marked not-retained, it's +0.
3718 if (method->hasAttr<CFReturnsNotRetainedAttr>())
3719 return ACC_plusZero;
3720
3721 // If the method is explicitly marked as returning retained, or its
3722 // selector follows a +1 Cocoa convention, treat it as +1.
3723 if (method->hasAttr<CFReturnsRetainedAttr>())
3724 return ACC_plusOne;
3725
3726 switch (method->getSelector().getMethodFamily()) {
3727 case OMF_alloc:
3728 case OMF_copy:
3729 case OMF_mutableCopy:
3730 case OMF_new:
3731 return ACC_plusOne;
3732
3733 default:
3734 // Otherwise, treat it as +0.
3735 return ACC_plusZero;
3736 }
3737 }
3738 };
3739 } // end anonymous namespace
3740
isKnownName(StringRef name)3741 bool Sema::isKnownName(StringRef name) {
3742 if (name.empty())
3743 return false;
3744 LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
3745 Sema::LookupOrdinaryName);
3746 return LookupName(R, TUScope, false);
3747 }
3748
3749 template <typename DiagBuilderT>
addFixitForObjCARCConversion(Sema & S,DiagBuilderT & DiagB,Sema::CheckedConversionKind CCK,SourceLocation afterLParen,QualType castType,Expr * castExpr,Expr * realCast,const char * bridgeKeyword,const char * CFBridgeName)3750 static void addFixitForObjCARCConversion(
3751 Sema &S, DiagBuilderT &DiagB, Sema::CheckedConversionKind CCK,
3752 SourceLocation afterLParen, QualType castType, Expr *castExpr,
3753 Expr *realCast, const char *bridgeKeyword, const char *CFBridgeName) {
3754 // We handle C-style and implicit casts here.
3755 switch (CCK) {
3756 case Sema::CCK_ImplicitConversion:
3757 case Sema::CCK_ForBuiltinOverloadedOp:
3758 case Sema::CCK_CStyleCast:
3759 case Sema::CCK_OtherCast:
3760 break;
3761 case Sema::CCK_FunctionalCast:
3762 return;
3763 }
3764
3765 if (CFBridgeName) {
3766 if (CCK == Sema::CCK_OtherCast) {
3767 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3768 SourceRange range(NCE->getOperatorLoc(),
3769 NCE->getAngleBrackets().getEnd());
3770 SmallString<32> BridgeCall;
3771
3772 SourceManager &SM = S.getSourceManager();
3773 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3774 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3775 BridgeCall += ' ';
3776
3777 BridgeCall += CFBridgeName;
3778 DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
3779 }
3780 return;
3781 }
3782 Expr *castedE = castExpr;
3783 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
3784 castedE = CCE->getSubExpr();
3785 castedE = castedE->IgnoreImpCasts();
3786 SourceRange range = castedE->getSourceRange();
3787
3788 SmallString<32> BridgeCall;
3789
3790 SourceManager &SM = S.getSourceManager();
3791 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3792 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3793 BridgeCall += ' ';
3794
3795 BridgeCall += CFBridgeName;
3796
3797 if (isa<ParenExpr>(castedE)) {
3798 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3799 BridgeCall));
3800 } else {
3801 BridgeCall += '(';
3802 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3803 BridgeCall));
3804 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3805 S.getLocForEndOfToken(range.getEnd()),
3806 ")"));
3807 }
3808 return;
3809 }
3810
3811 if (CCK == Sema::CCK_CStyleCast) {
3812 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
3813 } else if (CCK == Sema::CCK_OtherCast) {
3814 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3815 std::string castCode = "(";
3816 castCode += bridgeKeyword;
3817 castCode += castType.getAsString();
3818 castCode += ")";
3819 SourceRange Range(NCE->getOperatorLoc(),
3820 NCE->getAngleBrackets().getEnd());
3821 DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
3822 }
3823 } else {
3824 std::string castCode = "(";
3825 castCode += bridgeKeyword;
3826 castCode += castType.getAsString();
3827 castCode += ")";
3828 Expr *castedE = castExpr->IgnoreImpCasts();
3829 SourceRange range = castedE->getSourceRange();
3830 if (isa<ParenExpr>(castedE)) {
3831 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3832 castCode));
3833 } else {
3834 castCode += "(";
3835 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3836 castCode));
3837 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3838 S.getLocForEndOfToken(range.getEnd()),
3839 ")"));
3840 }
3841 }
3842 }
3843
3844 template <typename T>
getObjCBridgeAttr(const TypedefType * TD)3845 static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3846 TypedefNameDecl *TDNDecl = TD->getDecl();
3847 QualType QT = TDNDecl->getUnderlyingType();
3848 if (QT->isPointerType()) {
3849 QT = QT->getPointeeType();
3850 if (const RecordType *RT = QT->getAs<RecordType>())
3851 if (RecordDecl *RD = RT->getDecl()->getMostRecentDecl())
3852 return RD->getAttr<T>();
3853 }
3854 return nullptr;
3855 }
3856
ObjCBridgeRelatedAttrFromType(QualType T,TypedefNameDecl * & TDNDecl)3857 static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T,
3858 TypedefNameDecl *&TDNDecl) {
3859 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3860 TDNDecl = TD->getDecl();
3861 if (ObjCBridgeRelatedAttr *ObjCBAttr =
3862 getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD))
3863 return ObjCBAttr;
3864 T = TDNDecl->getUnderlyingType();
3865 }
3866 return nullptr;
3867 }
3868
3869 static void
diagnoseObjCARCConversion(Sema & S,SourceRange castRange,QualType castType,ARCConversionTypeClass castACTC,Expr * castExpr,Expr * realCast,ARCConversionTypeClass exprACTC,Sema::CheckedConversionKind CCK)3870 diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
3871 QualType castType, ARCConversionTypeClass castACTC,
3872 Expr *castExpr, Expr *realCast,
3873 ARCConversionTypeClass exprACTC,
3874 Sema::CheckedConversionKind CCK) {
3875 SourceLocation loc =
3876 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
3877
3878 if (S.makeUnavailableInSystemHeader(loc,
3879 UnavailableAttr::IR_ARCForbiddenConversion))
3880 return;
3881
3882 QualType castExprType = castExpr->getType();
3883 // Defer emitting a diagnostic for bridge-related casts; that will be
3884 // handled by CheckObjCBridgeRelatedConversions.
3885 TypedefNameDecl *TDNDecl = nullptr;
3886 if ((castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable &&
3887 ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) ||
3888 (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable &&
3889 ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl)))
3890 return;
3891
3892 unsigned srcKind = 0;
3893 switch (exprACTC) {
3894 case ACTC_none:
3895 case ACTC_coreFoundation:
3896 case ACTC_voidPtr:
3897 srcKind = (castExprType->isPointerType() ? 1 : 0);
3898 break;
3899 case ACTC_retainable:
3900 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
3901 break;
3902 case ACTC_indirectRetainable:
3903 srcKind = 4;
3904 break;
3905 }
3906
3907 // Check whether this could be fixed with a bridge cast.
3908 SourceLocation afterLParen = S.getLocForEndOfToken(castRange.getBegin());
3909 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
3910
3911 unsigned convKindForDiag = Sema::isCast(CCK) ? 0 : 1;
3912
3913 // Bridge from an ARC type to a CF type.
3914 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
3915
3916 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3917 << convKindForDiag
3918 << 2 // of C pointer type
3919 << castExprType
3920 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
3921 << castType
3922 << castRange
3923 << castExpr->getSourceRange();
3924 bool br = S.isKnownName("CFBridgingRelease");
3925 ACCResult CreateRule =
3926 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
3927 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
3928 if (CreateRule != ACC_plusOne)
3929 {
3930 auto DiagB = (CCK != Sema::CCK_OtherCast)
3931 ? S.Diag(noteLoc, diag::note_arc_bridge)
3932 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
3933
3934 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3935 castType, castExpr, realCast, "__bridge ",
3936 nullptr);
3937 }
3938 if (CreateRule != ACC_plusZero)
3939 {
3940 auto DiagB = (CCK == Sema::CCK_OtherCast && !br)
3941 ? S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer)
3942 << castExprType
3943 : S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3944 diag::note_arc_bridge_transfer)
3945 << castExprType << br;
3946
3947 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3948 castType, castExpr, realCast, "__bridge_transfer ",
3949 br ? "CFBridgingRelease" : nullptr);
3950 }
3951
3952 return;
3953 }
3954
3955 // Bridge from a CF type to an ARC type.
3956 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
3957 bool br = S.isKnownName("CFBridgingRetain");
3958 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3959 << convKindForDiag
3960 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
3961 << castExprType
3962 << 2 // to C pointer type
3963 << castType
3964 << castRange
3965 << castExpr->getSourceRange();
3966 ACCResult CreateRule =
3967 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
3968 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
3969 if (CreateRule != ACC_plusOne)
3970 {
3971 auto DiagB = (CCK != Sema::CCK_OtherCast)
3972 ? S.Diag(noteLoc, diag::note_arc_bridge)
3973 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
3974 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3975 castType, castExpr, realCast, "__bridge ",
3976 nullptr);
3977 }
3978 if (CreateRule != ACC_plusZero)
3979 {
3980 auto DiagB = (CCK == Sema::CCK_OtherCast && !br)
3981 ? S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained)
3982 << castType
3983 : S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3984 diag::note_arc_bridge_retained)
3985 << castType << br;
3986
3987 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3988 castType, castExpr, realCast, "__bridge_retained ",
3989 br ? "CFBridgingRetain" : nullptr);
3990 }
3991
3992 return;
3993 }
3994
3995 S.Diag(loc, diag::err_arc_mismatched_cast)
3996 << !convKindForDiag
3997 << srcKind << castExprType << castType
3998 << castRange << castExpr->getSourceRange();
3999 }
4000
4001 template <typename TB>
CheckObjCBridgeNSCast(Sema & S,QualType castType,Expr * castExpr,bool & HadTheAttribute,bool warn)4002 static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr,
4003 bool &HadTheAttribute, bool warn) {
4004 QualType T = castExpr->getType();
4005 HadTheAttribute = false;
4006 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
4007 TypedefNameDecl *TDNDecl = TD->getDecl();
4008 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
4009 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
4010 HadTheAttribute = true;
4011 if (Parm->isStr("id"))
4012 return true;
4013
4014 NamedDecl *Target = nullptr;
4015 // Check for an existing type with this name.
4016 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
4017 Sema::LookupOrdinaryName);
4018 if (S.LookupName(R, S.TUScope)) {
4019 Target = R.getFoundDecl();
4020 if (Target && isa<ObjCInterfaceDecl>(Target)) {
4021 ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
4022 if (const ObjCObjectPointerType *InterfacePointerType =
4023 castType->getAsObjCInterfacePointerType()) {
4024 ObjCInterfaceDecl *CastClass
4025 = InterfacePointerType->getObjectType()->getInterface();
4026 if ((CastClass == ExprClass) ||
4027 (CastClass && CastClass->isSuperClassOf(ExprClass)))
4028 return true;
4029 if (warn)
4030 S.Diag(castExpr->getBeginLoc(), diag::warn_objc_invalid_bridge)
4031 << T << Target->getName() << castType->getPointeeType();
4032 return false;
4033 } else if (castType->isObjCIdType() ||
4034 (S.Context.ObjCObjectAdoptsQTypeProtocols(
4035 castType, ExprClass)))
4036 // ok to cast to 'id'.
4037 // casting to id<p-list> is ok if bridge type adopts all of
4038 // p-list protocols.
4039 return true;
4040 else {
4041 if (warn) {
4042 S.Diag(castExpr->getBeginLoc(), diag::warn_objc_invalid_bridge)
4043 << T << Target->getName() << castType;
4044 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4045 S.Diag(Target->getBeginLoc(), diag::note_declared_at);
4046 }
4047 return false;
4048 }
4049 }
4050 } else if (!castType->isObjCIdType()) {
4051 S.Diag(castExpr->getBeginLoc(),
4052 diag::err_objc_cf_bridged_not_interface)
4053 << castExpr->getType() << Parm;
4054 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4055 if (Target)
4056 S.Diag(Target->getBeginLoc(), diag::note_declared_at);
4057 }
4058 return true;
4059 }
4060 return false;
4061 }
4062 T = TDNDecl->getUnderlyingType();
4063 }
4064 return true;
4065 }
4066
4067 template <typename TB>
CheckObjCBridgeCFCast(Sema & S,QualType castType,Expr * castExpr,bool & HadTheAttribute,bool warn)4068 static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr,
4069 bool &HadTheAttribute, bool warn) {
4070 QualType T = castType;
4071 HadTheAttribute = false;
4072 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
4073 TypedefNameDecl *TDNDecl = TD->getDecl();
4074 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
4075 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
4076 HadTheAttribute = true;
4077 if (Parm->isStr("id"))
4078 return true;
4079
4080 NamedDecl *Target = nullptr;
4081 // Check for an existing type with this name.
4082 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
4083 Sema::LookupOrdinaryName);
4084 if (S.LookupName(R, S.TUScope)) {
4085 Target = R.getFoundDecl();
4086 if (Target && isa<ObjCInterfaceDecl>(Target)) {
4087 ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
4088 if (const ObjCObjectPointerType *InterfacePointerType =
4089 castExpr->getType()->getAsObjCInterfacePointerType()) {
4090 ObjCInterfaceDecl *ExprClass
4091 = InterfacePointerType->getObjectType()->getInterface();
4092 if ((CastClass == ExprClass) ||
4093 (ExprClass && CastClass->isSuperClassOf(ExprClass)))
4094 return true;
4095 if (warn) {
4096 S.Diag(castExpr->getBeginLoc(),
4097 diag::warn_objc_invalid_bridge_to_cf)
4098 << castExpr->getType()->getPointeeType() << T;
4099 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4100 }
4101 return false;
4102 } else if (castExpr->getType()->isObjCIdType() ||
4103 (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
4104 castExpr->getType(), CastClass)))
4105 // ok to cast an 'id' expression to a CFtype.
4106 // ok to cast an 'id<plist>' expression to CFtype provided plist
4107 // adopts all of CFtype's ObjetiveC's class plist.
4108 return true;
4109 else {
4110 if (warn) {
4111 S.Diag(castExpr->getBeginLoc(),
4112 diag::warn_objc_invalid_bridge_to_cf)
4113 << castExpr->getType() << castType;
4114 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4115 S.Diag(Target->getBeginLoc(), diag::note_declared_at);
4116 }
4117 return false;
4118 }
4119 }
4120 }
4121 S.Diag(castExpr->getBeginLoc(),
4122 diag::err_objc_ns_bridged_invalid_cfobject)
4123 << castExpr->getType() << castType;
4124 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4125 if (Target)
4126 S.Diag(Target->getBeginLoc(), diag::note_declared_at);
4127 return true;
4128 }
4129 return false;
4130 }
4131 T = TDNDecl->getUnderlyingType();
4132 }
4133 return true;
4134 }
4135
CheckTollFreeBridgeCast(QualType castType,Expr * castExpr)4136 void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) {
4137 if (!getLangOpts().ObjC)
4138 return;
4139 // warn in presence of __bridge casting to or from a toll free bridge cast.
4140 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType());
4141 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
4142 if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) {
4143 bool HasObjCBridgeAttr;
4144 bool ObjCBridgeAttrWillNotWarn =
4145 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
4146 false);
4147 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
4148 return;
4149 bool HasObjCBridgeMutableAttr;
4150 bool ObjCBridgeMutableAttrWillNotWarn =
4151 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
4152 HasObjCBridgeMutableAttr, false);
4153 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
4154 return;
4155
4156 if (HasObjCBridgeAttr)
4157 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
4158 true);
4159 else if (HasObjCBridgeMutableAttr)
4160 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
4161 HasObjCBridgeMutableAttr, true);
4162 }
4163 else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) {
4164 bool HasObjCBridgeAttr;
4165 bool ObjCBridgeAttrWillNotWarn =
4166 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
4167 false);
4168 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
4169 return;
4170 bool HasObjCBridgeMutableAttr;
4171 bool ObjCBridgeMutableAttrWillNotWarn =
4172 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
4173 HasObjCBridgeMutableAttr, false);
4174 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
4175 return;
4176
4177 if (HasObjCBridgeAttr)
4178 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
4179 true);
4180 else if (HasObjCBridgeMutableAttr)
4181 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
4182 HasObjCBridgeMutableAttr, true);
4183 }
4184 }
4185
CheckObjCBridgeRelatedCast(QualType castType,Expr * castExpr)4186 void Sema::CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr) {
4187 QualType SrcType = castExpr->getType();
4188 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(castExpr)) {
4189 if (PRE->isExplicitProperty()) {
4190 if (ObjCPropertyDecl *PDecl = PRE->getExplicitProperty())
4191 SrcType = PDecl->getType();
4192 }
4193 else if (PRE->isImplicitProperty()) {
4194 if (ObjCMethodDecl *Getter = PRE->getImplicitPropertyGetter())
4195 SrcType = Getter->getReturnType();
4196 }
4197 }
4198
4199 ARCConversionTypeClass srcExprACTC = classifyTypeForARCConversion(SrcType);
4200 ARCConversionTypeClass castExprACTC = classifyTypeForARCConversion(castType);
4201 if (srcExprACTC != ACTC_retainable || castExprACTC != ACTC_coreFoundation)
4202 return;
4203 CheckObjCBridgeRelatedConversions(castExpr->getBeginLoc(), castType, SrcType,
4204 castExpr);
4205 }
4206
CheckTollFreeBridgeStaticCast(QualType castType,Expr * castExpr,CastKind & Kind)4207 bool Sema::CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
4208 CastKind &Kind) {
4209 if (!getLangOpts().ObjC)
4210 return false;
4211 ARCConversionTypeClass exprACTC =
4212 classifyTypeForARCConversion(castExpr->getType());
4213 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
4214 if ((castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) ||
4215 (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable)) {
4216 CheckTollFreeBridgeCast(castType, castExpr);
4217 Kind = (castACTC == ACTC_coreFoundation) ? CK_BitCast
4218 : CK_CPointerToObjCPointerCast;
4219 return true;
4220 }
4221 return false;
4222 }
4223
checkObjCBridgeRelatedComponents(SourceLocation Loc,QualType DestType,QualType SrcType,ObjCInterfaceDecl * & RelatedClass,ObjCMethodDecl * & ClassMethod,ObjCMethodDecl * & InstanceMethod,TypedefNameDecl * & TDNDecl,bool CfToNs,bool Diagnose)4224 bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc,
4225 QualType DestType, QualType SrcType,
4226 ObjCInterfaceDecl *&RelatedClass,
4227 ObjCMethodDecl *&ClassMethod,
4228 ObjCMethodDecl *&InstanceMethod,
4229 TypedefNameDecl *&TDNDecl,
4230 bool CfToNs, bool Diagnose) {
4231 QualType T = CfToNs ? SrcType : DestType;
4232 ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl);
4233 if (!ObjCBAttr)
4234 return false;
4235
4236 IdentifierInfo *RCId = ObjCBAttr->getRelatedClass();
4237 IdentifierInfo *CMId = ObjCBAttr->getClassMethod();
4238 IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod();
4239 if (!RCId)
4240 return false;
4241 NamedDecl *Target = nullptr;
4242 // Check for an existing type with this name.
4243 LookupResult R(*this, DeclarationName(RCId), SourceLocation(),
4244 Sema::LookupOrdinaryName);
4245 if (!LookupName(R, TUScope)) {
4246 if (Diagnose) {
4247 Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId
4248 << SrcType << DestType;
4249 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4250 }
4251 return false;
4252 }
4253 Target = R.getFoundDecl();
4254 if (Target && isa<ObjCInterfaceDecl>(Target))
4255 RelatedClass = cast<ObjCInterfaceDecl>(Target);
4256 else {
4257 if (Diagnose) {
4258 Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId
4259 << SrcType << DestType;
4260 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4261 if (Target)
4262 Diag(Target->getBeginLoc(), diag::note_declared_at);
4263 }
4264 return false;
4265 }
4266
4267 // Check for an existing class method with the given selector name.
4268 if (CfToNs && CMId) {
4269 Selector Sel = Context.Selectors.getUnarySelector(CMId);
4270 ClassMethod = RelatedClass->lookupMethod(Sel, false);
4271 if (!ClassMethod) {
4272 if (Diagnose) {
4273 Diag(Loc, diag::err_objc_bridged_related_known_method)
4274 << SrcType << DestType << Sel << false;
4275 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4276 }
4277 return false;
4278 }
4279 }
4280
4281 // Check for an existing instance method with the given selector name.
4282 if (!CfToNs && IMId) {
4283 Selector Sel = Context.Selectors.getNullarySelector(IMId);
4284 InstanceMethod = RelatedClass->lookupMethod(Sel, true);
4285 if (!InstanceMethod) {
4286 if (Diagnose) {
4287 Diag(Loc, diag::err_objc_bridged_related_known_method)
4288 << SrcType << DestType << Sel << true;
4289 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4290 }
4291 return false;
4292 }
4293 }
4294 return true;
4295 }
4296
4297 bool
CheckObjCBridgeRelatedConversions(SourceLocation Loc,QualType DestType,QualType SrcType,Expr * & SrcExpr,bool Diagnose)4298 Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc,
4299 QualType DestType, QualType SrcType,
4300 Expr *&SrcExpr, bool Diagnose) {
4301 ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType);
4302 ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType);
4303 bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable);
4304 bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation);
4305 if (!CfToNs && !NsToCf)
4306 return false;
4307
4308 ObjCInterfaceDecl *RelatedClass;
4309 ObjCMethodDecl *ClassMethod = nullptr;
4310 ObjCMethodDecl *InstanceMethod = nullptr;
4311 TypedefNameDecl *TDNDecl = nullptr;
4312 if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass,
4313 ClassMethod, InstanceMethod, TDNDecl,
4314 CfToNs, Diagnose))
4315 return false;
4316
4317 if (CfToNs) {
4318 // Implicit conversion from CF to ObjC object is needed.
4319 if (ClassMethod) {
4320 if (Diagnose) {
4321 std::string ExpressionString = "[";
4322 ExpressionString += RelatedClass->getNameAsString();
4323 ExpressionString += " ";
4324 ExpressionString += ClassMethod->getSelector().getAsString();
4325 SourceLocation SrcExprEndLoc =
4326 getLocForEndOfToken(SrcExpr->getEndLoc());
4327 // Provide a fixit: [RelatedClass ClassMethod SrcExpr]
4328 Diag(Loc, diag::err_objc_bridged_related_known_method)
4329 << SrcType << DestType << ClassMethod->getSelector() << false
4330 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(),
4331 ExpressionString)
4332 << FixItHint::CreateInsertion(SrcExprEndLoc, "]");
4333 Diag(RelatedClass->getBeginLoc(), diag::note_declared_at);
4334 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4335
4336 QualType receiverType = Context.getObjCInterfaceType(RelatedClass);
4337 // Argument.
4338 Expr *args[] = { SrcExpr };
4339 ExprResult msg = BuildClassMessageImplicit(receiverType, false,
4340 ClassMethod->getLocation(),
4341 ClassMethod->getSelector(), ClassMethod,
4342 MultiExprArg(args, 1));
4343 SrcExpr = msg.get();
4344 }
4345 return true;
4346 }
4347 }
4348 else {
4349 // Implicit conversion from ObjC type to CF object is needed.
4350 if (InstanceMethod) {
4351 if (Diagnose) {
4352 std::string ExpressionString;
4353 SourceLocation SrcExprEndLoc =
4354 getLocForEndOfToken(SrcExpr->getEndLoc());
4355 if (InstanceMethod->isPropertyAccessor())
4356 if (const ObjCPropertyDecl *PDecl =
4357 InstanceMethod->findPropertyDecl()) {
4358 // fixit: ObjectExpr.propertyname when it is aproperty accessor.
4359 ExpressionString = ".";
4360 ExpressionString += PDecl->getNameAsString();
4361 Diag(Loc, diag::err_objc_bridged_related_known_method)
4362 << SrcType << DestType << InstanceMethod->getSelector() << true
4363 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
4364 }
4365 if (ExpressionString.empty()) {
4366 // Provide a fixit: [ObjectExpr InstanceMethod]
4367 ExpressionString = " ";
4368 ExpressionString += InstanceMethod->getSelector().getAsString();
4369 ExpressionString += "]";
4370
4371 Diag(Loc, diag::err_objc_bridged_related_known_method)
4372 << SrcType << DestType << InstanceMethod->getSelector() << true
4373 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "[")
4374 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
4375 }
4376 Diag(RelatedClass->getBeginLoc(), diag::note_declared_at);
4377 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4378
4379 ExprResult msg =
4380 BuildInstanceMessageImplicit(SrcExpr, SrcType,
4381 InstanceMethod->getLocation(),
4382 InstanceMethod->getSelector(),
4383 InstanceMethod, None);
4384 SrcExpr = msg.get();
4385 }
4386 return true;
4387 }
4388 }
4389 return false;
4390 }
4391
4392 Sema::ARCConversionResult
CheckObjCConversion(SourceRange castRange,QualType castType,Expr * & castExpr,CheckedConversionKind CCK,bool Diagnose,bool DiagnoseCFAudited,BinaryOperatorKind Opc)4393 Sema::CheckObjCConversion(SourceRange castRange, QualType castType,
4394 Expr *&castExpr, CheckedConversionKind CCK,
4395 bool Diagnose, bool DiagnoseCFAudited,
4396 BinaryOperatorKind Opc) {
4397 QualType castExprType = castExpr->getType();
4398
4399 // For the purposes of the classification, we assume reference types
4400 // will bind to temporaries.
4401 QualType effCastType = castType;
4402 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
4403 effCastType = ref->getPointeeType();
4404
4405 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
4406 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
4407 if (exprACTC == castACTC) {
4408 // Check for viability and report error if casting an rvalue to a
4409 // life-time qualifier.
4410 if (castACTC == ACTC_retainable &&
4411 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
4412 castType != castExprType) {
4413 const Type *DT = castType.getTypePtr();
4414 QualType QDT = castType;
4415 // We desugar some types but not others. We ignore those
4416 // that cannot happen in a cast; i.e. auto, and those which
4417 // should not be de-sugared; i.e typedef.
4418 if (const ParenType *PT = dyn_cast<ParenType>(DT))
4419 QDT = PT->desugar();
4420 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
4421 QDT = TP->desugar();
4422 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
4423 QDT = AT->desugar();
4424 if (QDT != castType &&
4425 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
4426 if (Diagnose) {
4427 SourceLocation loc = (castRange.isValid() ? castRange.getBegin()
4428 : castExpr->getExprLoc());
4429 Diag(loc, diag::err_arc_nolifetime_behavior);
4430 }
4431 return ACR_error;
4432 }
4433 }
4434 return ACR_okay;
4435 }
4436
4437 // The life-time qualifier cast check above is all we need for ObjCWeak.
4438 // ObjCAutoRefCount has more restrictions on what is legal.
4439 if (!getLangOpts().ObjCAutoRefCount)
4440 return ACR_okay;
4441
4442 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
4443
4444 // Allow all of these types to be cast to integer types (but not
4445 // vice-versa).
4446 if (castACTC == ACTC_none && castType->isIntegralType(Context))
4447 return ACR_okay;
4448
4449 // Allow casts between pointers to lifetime types (e.g., __strong id*)
4450 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
4451 // must be explicit.
4452 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
4453 return ACR_okay;
4454 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
4455 isCast(CCK))
4456 return ACR_okay;
4457
4458 switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
4459 // For invalid casts, fall through.
4460 case ACC_invalid:
4461 break;
4462
4463 // Do nothing for both bottom and +0.
4464 case ACC_bottom:
4465 case ACC_plusZero:
4466 return ACR_okay;
4467
4468 // If the result is +1, consume it here.
4469 case ACC_plusOne:
4470 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
4471 CK_ARCConsumeObject, castExpr, nullptr,
4472 VK_RValue, FPOptionsOverride());
4473 Cleanup.setExprNeedsCleanups(true);
4474 return ACR_okay;
4475 }
4476
4477 // If this is a non-implicit cast from id or block type to a
4478 // CoreFoundation type, delay complaining in case the cast is used
4479 // in an acceptable context.
4480 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) && isCast(CCK))
4481 return ACR_unbridged;
4482
4483 // Issue a diagnostic about a missing @-sign when implicit casting a cstring
4484 // to 'NSString *', instead of falling through to report a "bridge cast"
4485 // diagnostic.
4486 if (castACTC == ACTC_retainable && exprACTC == ACTC_none &&
4487 CheckConversionToObjCLiteral(castType, castExpr, Diagnose))
4488 return ACR_error;
4489
4490 // Do not issue "bridge cast" diagnostic when implicit casting
4491 // a retainable object to a CF type parameter belonging to an audited
4492 // CF API function. Let caller issue a normal type mismatched diagnostic
4493 // instead.
4494 if ((!DiagnoseCFAudited || exprACTC != ACTC_retainable ||
4495 castACTC != ACTC_coreFoundation) &&
4496 !(exprACTC == ACTC_voidPtr && castACTC == ACTC_retainable &&
4497 (Opc == BO_NE || Opc == BO_EQ))) {
4498 if (Diagnose)
4499 diagnoseObjCARCConversion(*this, castRange, castType, castACTC, castExpr,
4500 castExpr, exprACTC, CCK);
4501 return ACR_error;
4502 }
4503 return ACR_okay;
4504 }
4505
4506 /// Given that we saw an expression with the ARCUnbridgedCastTy
4507 /// placeholder type, complain bitterly.
diagnoseARCUnbridgedCast(Expr * e)4508 void Sema::diagnoseARCUnbridgedCast(Expr *e) {
4509 // We expect the spurious ImplicitCastExpr to already have been stripped.
4510 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
4511 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
4512
4513 SourceRange castRange;
4514 QualType castType;
4515 CheckedConversionKind CCK;
4516
4517 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
4518 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
4519 castType = cast->getTypeAsWritten();
4520 CCK = CCK_CStyleCast;
4521 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
4522 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
4523 castType = cast->getTypeAsWritten();
4524 CCK = CCK_OtherCast;
4525 } else {
4526 llvm_unreachable("Unexpected ImplicitCastExpr");
4527 }
4528
4529 ARCConversionTypeClass castACTC =
4530 classifyTypeForARCConversion(castType.getNonReferenceType());
4531
4532 Expr *castExpr = realCast->getSubExpr();
4533 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
4534
4535 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
4536 castExpr, realCast, ACTC_retainable, CCK);
4537 }
4538
4539 /// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
4540 /// type, remove the placeholder cast.
stripARCUnbridgedCast(Expr * e)4541 Expr *Sema::stripARCUnbridgedCast(Expr *e) {
4542 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
4543
4544 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
4545 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
4546 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
4547 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
4548 assert(uo->getOpcode() == UO_Extension);
4549 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
4550 return UnaryOperator::Create(Context, sub, UO_Extension, sub->getType(),
4551 sub->getValueKind(), sub->getObjectKind(),
4552 uo->getOperatorLoc(), false,
4553 CurFPFeatureOverrides());
4554 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
4555 assert(!gse->isResultDependent());
4556
4557 unsigned n = gse->getNumAssocs();
4558 SmallVector<Expr *, 4> subExprs;
4559 SmallVector<TypeSourceInfo *, 4> subTypes;
4560 subExprs.reserve(n);
4561 subTypes.reserve(n);
4562 for (const GenericSelectionExpr::Association assoc : gse->associations()) {
4563 subTypes.push_back(assoc.getTypeSourceInfo());
4564 Expr *sub = assoc.getAssociationExpr();
4565 if (assoc.isSelected())
4566 sub = stripARCUnbridgedCast(sub);
4567 subExprs.push_back(sub);
4568 }
4569
4570 return GenericSelectionExpr::Create(
4571 Context, gse->getGenericLoc(), gse->getControllingExpr(), subTypes,
4572 subExprs, gse->getDefaultLoc(), gse->getRParenLoc(),
4573 gse->containsUnexpandedParameterPack(), gse->getResultIndex());
4574 } else {
4575 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
4576 return cast<ImplicitCastExpr>(e)->getSubExpr();
4577 }
4578 }
4579
CheckObjCARCUnavailableWeakConversion(QualType castType,QualType exprType)4580 bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
4581 QualType exprType) {
4582 QualType canCastType =
4583 Context.getCanonicalType(castType).getUnqualifiedType();
4584 QualType canExprType =
4585 Context.getCanonicalType(exprType).getUnqualifiedType();
4586 if (isa<ObjCObjectPointerType>(canCastType) &&
4587 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
4588 canExprType->isObjCObjectPointerType()) {
4589 if (const ObjCObjectPointerType *ObjT =
4590 canExprType->getAs<ObjCObjectPointerType>())
4591 if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
4592 return !ObjI->isArcWeakrefUnavailable();
4593 }
4594 return true;
4595 }
4596
4597 /// Look for an ObjCReclaimReturnedObject cast and destroy it.
maybeUndoReclaimObject(Expr * e)4598 static Expr *maybeUndoReclaimObject(Expr *e) {
4599 Expr *curExpr = e, *prevExpr = nullptr;
4600
4601 // Walk down the expression until we hit an implicit cast of kind
4602 // ARCReclaimReturnedObject or an Expr that is neither a Paren nor a Cast.
4603 while (true) {
4604 if (auto *pe = dyn_cast<ParenExpr>(curExpr)) {
4605 prevExpr = curExpr;
4606 curExpr = pe->getSubExpr();
4607 continue;
4608 }
4609
4610 if (auto *ce = dyn_cast<CastExpr>(curExpr)) {
4611 if (auto *ice = dyn_cast<ImplicitCastExpr>(ce))
4612 if (ice->getCastKind() == CK_ARCReclaimReturnedObject) {
4613 if (!prevExpr)
4614 return ice->getSubExpr();
4615 if (auto *pe = dyn_cast<ParenExpr>(prevExpr))
4616 pe->setSubExpr(ice->getSubExpr());
4617 else
4618 cast<CastExpr>(prevExpr)->setSubExpr(ice->getSubExpr());
4619 return e;
4620 }
4621
4622 prevExpr = curExpr;
4623 curExpr = ce->getSubExpr();
4624 continue;
4625 }
4626
4627 // Break out of the loop if curExpr is neither a Paren nor a Cast.
4628 break;
4629 }
4630
4631 return e;
4632 }
4633
BuildObjCBridgedCast(SourceLocation LParenLoc,ObjCBridgeCastKind Kind,SourceLocation BridgeKeywordLoc,TypeSourceInfo * TSInfo,Expr * SubExpr)4634 ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
4635 ObjCBridgeCastKind Kind,
4636 SourceLocation BridgeKeywordLoc,
4637 TypeSourceInfo *TSInfo,
4638 Expr *SubExpr) {
4639 ExprResult SubResult = UsualUnaryConversions(SubExpr);
4640 if (SubResult.isInvalid()) return ExprError();
4641 SubExpr = SubResult.get();
4642
4643 QualType T = TSInfo->getType();
4644 QualType FromType = SubExpr->getType();
4645
4646 CastKind CK;
4647
4648 bool MustConsume = false;
4649 if (T->isDependentType() || SubExpr->isTypeDependent()) {
4650 // Okay: we'll build a dependent expression type.
4651 CK = CK_Dependent;
4652 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
4653 // Casting CF -> id
4654 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
4655 : CK_CPointerToObjCPointerCast);
4656 switch (Kind) {
4657 case OBC_Bridge:
4658 break;
4659
4660 case OBC_BridgeRetained: {
4661 bool br = isKnownName("CFBridgingRelease");
4662 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4663 << 2
4664 << FromType
4665 << (T->isBlockPointerType()? 1 : 0)
4666 << T
4667 << SubExpr->getSourceRange()
4668 << Kind;
4669 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4670 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
4671 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
4672 << FromType << br
4673 << FixItHint::CreateReplacement(BridgeKeywordLoc,
4674 br ? "CFBridgingRelease "
4675 : "__bridge_transfer ");
4676
4677 Kind = OBC_Bridge;
4678 break;
4679 }
4680
4681 case OBC_BridgeTransfer:
4682 // We must consume the Objective-C object produced by the cast.
4683 MustConsume = true;
4684 break;
4685 }
4686 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
4687 // Okay: id -> CF
4688 CK = CK_BitCast;
4689 switch (Kind) {
4690 case OBC_Bridge:
4691 // Reclaiming a value that's going to be __bridge-casted to CF
4692 // is very dangerous, so we don't do it.
4693 SubExpr = maybeUndoReclaimObject(SubExpr);
4694 break;
4695
4696 case OBC_BridgeRetained:
4697 // Produce the object before casting it.
4698 SubExpr = ImplicitCastExpr::Create(Context, FromType, CK_ARCProduceObject,
4699 SubExpr, nullptr, VK_RValue,
4700 FPOptionsOverride());
4701 break;
4702
4703 case OBC_BridgeTransfer: {
4704 bool br = isKnownName("CFBridgingRetain");
4705 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4706 << (FromType->isBlockPointerType()? 1 : 0)
4707 << FromType
4708 << 2
4709 << T
4710 << SubExpr->getSourceRange()
4711 << Kind;
4712
4713 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4714 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
4715 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
4716 << T << br
4717 << FixItHint::CreateReplacement(BridgeKeywordLoc,
4718 br ? "CFBridgingRetain " : "__bridge_retained");
4719
4720 Kind = OBC_Bridge;
4721 break;
4722 }
4723 }
4724 } else {
4725 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
4726 << FromType << T << Kind
4727 << SubExpr->getSourceRange()
4728 << TSInfo->getTypeLoc().getSourceRange();
4729 return ExprError();
4730 }
4731
4732 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
4733 BridgeKeywordLoc,
4734 TSInfo, SubExpr);
4735
4736 if (MustConsume) {
4737 Cleanup.setExprNeedsCleanups(true);
4738 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
4739 nullptr, VK_RValue, FPOptionsOverride());
4740 }
4741
4742 return Result;
4743 }
4744
ActOnObjCBridgedCast(Scope * S,SourceLocation LParenLoc,ObjCBridgeCastKind Kind,SourceLocation BridgeKeywordLoc,ParsedType Type,SourceLocation RParenLoc,Expr * SubExpr)4745 ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
4746 SourceLocation LParenLoc,
4747 ObjCBridgeCastKind Kind,
4748 SourceLocation BridgeKeywordLoc,
4749 ParsedType Type,
4750 SourceLocation RParenLoc,
4751 Expr *SubExpr) {
4752 TypeSourceInfo *TSInfo = nullptr;
4753 QualType T = GetTypeFromParser(Type, &TSInfo);
4754 if (Kind == OBC_Bridge)
4755 CheckTollFreeBridgeCast(T, SubExpr);
4756 if (!TSInfo)
4757 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
4758 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
4759 SubExpr);
4760 }
4761