Coverage Report

Created: 2020-09-19 12:23

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