Coverage Report

Created: 2020-02-25 14:32

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