Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/lib/Sema/SemaOverload.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
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 provides Sema routines for C++ overloading.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/Sema/Overload.h"
14
#include "clang/AST/ASTContext.h"
15
#include "clang/AST/CXXInheritance.h"
16
#include "clang/AST/DeclObjC.h"
17
#include "clang/AST/Expr.h"
18
#include "clang/AST/ExprCXX.h"
19
#include "clang/AST/ExprObjC.h"
20
#include "clang/AST/TypeOrdering.h"
21
#include "clang/Basic/Diagnostic.h"
22
#include "clang/Basic/DiagnosticOptions.h"
23
#include "clang/Basic/PartialDiagnostic.h"
24
#include "clang/Basic/TargetInfo.h"
25
#include "clang/Sema/Initialization.h"
26
#include "clang/Sema/Lookup.h"
27
#include "clang/Sema/SemaInternal.h"
28
#include "clang/Sema/Template.h"
29
#include "clang/Sema/TemplateDeduction.h"
30
#include "llvm/ADT/DenseSet.h"
31
#include "llvm/ADT/Optional.h"
32
#include "llvm/ADT/STLExtras.h"
33
#include "llvm/ADT/SmallPtrSet.h"
34
#include "llvm/ADT/SmallString.h"
35
#include <algorithm>
36
#include <cstdlib>
37
38
using namespace clang;
39
using namespace sema;
40
41
1.44M
static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
42
2.63M
  return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
43
2.63M
    return P->hasAttr<PassObjectSizeAttr>();
44
2.63M
  });
45
1.44M
}
46
47
/// A convenience routine for creating a decayed reference to a function.
48
static ExprResult
49
CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
50
                      const Expr *Base, bool HadMultipleCandidates,
51
                      SourceLocation Loc = SourceLocation(),
52
147k
                      const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
53
147k
  if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
54
5
    return ExprError();
55
147k
  // If FoundDecl is different from Fn (such as if one is a template
56
147k
  // and the other a specialization), make sure DiagnoseUseOfDecl is
57
147k
  // called on both.
58
147k
  // FIXME: This would be more comprehensively addressed by modifying
59
147k
  // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
60
147k
  // being used.
61
147k
  if (FoundDecl != Fn && 
S.DiagnoseUseOfDecl(Fn, Loc)15.8k
)
62
5
    return ExprError();
63
147k
  if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
64
147k
    S.ResolveExceptionSpec(Loc, FPT);
65
147k
  DeclRefExpr *DRE = new (S.Context)
66
147k
      DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
67
147k
  if (HadMultipleCandidates)
68
107k
    DRE->setHadMultipleCandidates(true);
69
147k
70
147k
  S.MarkDeclRefReferenced(DRE, Base);
71
147k
  return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
72
147k
                             CK_FunctionToPointerDecay);
73
147k
}
74
75
static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
76
                                 bool InOverloadResolution,
77
                                 StandardConversionSequence &SCS,
78
                                 bool CStyle,
79
                                 bool AllowObjCWritebackConversion);
80
81
static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
82
                                                 QualType &ToType,
83
                                                 bool InOverloadResolution,
84
                                                 StandardConversionSequence &SCS,
85
                                                 bool CStyle);
86
static OverloadingResult
87
IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
88
                        UserDefinedConversionSequence& User,
89
                        OverloadCandidateSet& Conversions,
90
                        bool AllowExplicit,
91
                        bool AllowObjCConversionOnExplicit);
92
93
94
static ImplicitConversionSequence::CompareKind
95
CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
96
                                   const StandardConversionSequence& SCS1,
97
                                   const StandardConversionSequence& SCS2);
98
99
static ImplicitConversionSequence::CompareKind
100
CompareQualificationConversions(Sema &S,
101
                                const StandardConversionSequence& SCS1,
102
                                const StandardConversionSequence& SCS2);
103
104
static ImplicitConversionSequence::CompareKind
105
CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
106
                                const StandardConversionSequence& SCS1,
107
                                const StandardConversionSequence& SCS2);
108
109
/// GetConversionRank - Retrieve the implicit conversion rank
110
/// corresponding to the given implicit conversion kind.
111
58.7M
ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
112
58.7M
  static const ImplicitConversionRank
113
58.7M
    Rank[(int)ICK_Num_Conversion_Kinds] = {
114
58.7M
    ICR_Exact_Match,
115
58.7M
    ICR_Exact_Match,
116
58.7M
    ICR_Exact_Match,
117
58.7M
    ICR_Exact_Match,
118
58.7M
    ICR_Exact_Match,
119
58.7M
    ICR_Exact_Match,
120
58.7M
    ICR_Promotion,
121
58.7M
    ICR_Promotion,
122
58.7M
    ICR_Promotion,
123
58.7M
    ICR_Conversion,
124
58.7M
    ICR_Conversion,
125
58.7M
    ICR_Conversion,
126
58.7M
    ICR_Conversion,
127
58.7M
    ICR_Conversion,
128
58.7M
    ICR_Conversion,
129
58.7M
    ICR_Conversion,
130
58.7M
    ICR_Conversion,
131
58.7M
    ICR_Conversion,
132
58.7M
    ICR_Conversion,
133
58.7M
    ICR_OCL_Scalar_Widening,
134
58.7M
    ICR_Complex_Real_Conversion,
135
58.7M
    ICR_Conversion,
136
58.7M
    ICR_Conversion,
137
58.7M
    ICR_Writeback_Conversion,
138
58.7M
    ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
139
58.7M
                     // it was omitted by the patch that added
140
58.7M
                     // ICK_Zero_Event_Conversion
141
58.7M
    ICR_C_Conversion,
142
58.7M
    ICR_C_Conversion_Extension
143
58.7M
  };
144
58.7M
  return Rank[(int)Kind];
145
58.7M
}
146
147
/// GetImplicitConversionName - Return the name of this kind of
148
/// implicit conversion.
149
0
static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
150
0
  static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
151
0
    "No conversion",
152
0
    "Lvalue-to-rvalue",
153
0
    "Array-to-pointer",
154
0
    "Function-to-pointer",
155
0
    "Function pointer conversion",
156
0
    "Qualification",
157
0
    "Integral promotion",
158
0
    "Floating point promotion",
159
0
    "Complex promotion",
160
0
    "Integral conversion",
161
0
    "Floating conversion",
162
0
    "Complex conversion",
163
0
    "Floating-integral conversion",
164
0
    "Pointer conversion",
165
0
    "Pointer-to-member conversion",
166
0
    "Boolean conversion",
167
0
    "Compatible-types conversion",
168
0
    "Derived-to-base conversion",
169
0
    "Vector conversion",
170
0
    "Vector splat",
171
0
    "Complex-real conversion",
172
0
    "Block Pointer conversion",
173
0
    "Transparent Union Conversion",
174
0
    "Writeback conversion",
175
0
    "OpenCL Zero Event Conversion",
176
0
    "C specific type conversion",
177
0
    "Incompatible pointer conversion"
178
0
  };
179
0
  return Name[Kind];
180
0
}
181
182
/// StandardConversionSequence - Set the standard conversion
183
/// sequence to the identity conversion.
184
131M
void StandardConversionSequence::setAsIdentityConversion() {
185
131M
  First = ICK_Identity;
186
131M
  Second = ICK_Identity;
187
131M
  Third = ICK_Identity;
188
131M
  DeprecatedStringLiteralToCharPtr = false;
189
131M
  QualificationIncludesObjCLifetime = false;
190
131M
  ReferenceBinding = false;
191
131M
  DirectBinding = false;
192
131M
  IsLvalueReference = true;
193
131M
  BindsToFunctionLvalue = false;
194
131M
  BindsToRvalue = false;
195
131M
  BindsImplicitObjectArgumentWithoutRefQualifier = false;
196
131M
  ObjCLifetimeConversionBinding = false;
197
131M
  CopyConstructor = nullptr;
198
131M
}
199
200
/// getRank - Retrieve the rank of this standard conversion sequence
201
/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
202
/// implicit conversions.
203
15.5M
ImplicitConversionRank StandardConversionSequence::getRank() const {
204
15.5M
  ImplicitConversionRank Rank = ICR_Exact_Match;
205
15.5M
  if  (GetConversionRank(First) > Rank)
206
0
    Rank = GetConversionRank(First);
207
15.5M
  if  (GetConversionRank(Second) > Rank)
208
11.9M
    Rank = GetConversionRank(Second);
209
15.5M
  if  (GetConversionRank(Third) > Rank)
210
0
    Rank = GetConversionRank(Third);
211
15.5M
  return Rank;
212
15.5M
}
213
214
/// isPointerConversionToBool - Determines whether this conversion is
215
/// a conversion of a pointer or pointer-to-member to bool. This is
216
/// used as part of the ranking of standard conversion sequences
217
/// (C++ 13.3.3.2p4).
218
7.64M
bool StandardConversionSequence::isPointerConversionToBool() const {
219
7.64M
  // Note that FromType has not necessarily been transformed by the
220
7.64M
  // array-to-pointer or function-to-pointer implicit conversions, so
221
7.64M
  // check for their presence as well as checking whether FromType is
222
7.64M
  // a pointer.
223
7.64M
  if (getToType(1)->isBooleanType() &&
224
7.64M
      
(9.24k
getFromType()->isPointerType()9.24k
||
225
9.24k
       
getFromType()->isMemberPointerType()9.08k
||
226
9.24k
       
getFromType()->isObjCObjectPointerType()9.07k
||
227
9.24k
       
getFromType()->isBlockPointerType()9.06k
||
228
9.24k
       
getFromType()->isNullPtrType()9.06k
||
229
9.24k
       
First == ICK_Array_To_Pointer9.05k
||
First == ICK_Function_To_Pointer6.15k
))
230
3.08k
    return true;
231
7.64M
232
7.64M
  return false;
233
7.64M
}
234
235
/// isPointerConversionToVoidPointer - Determines whether this
236
/// conversion is a conversion of a pointer to a void pointer. This is
237
/// used as part of the ranking of standard conversion sequences (C++
238
/// 13.3.3.2p4).
239
bool
240
StandardConversionSequence::
241
7.63M
isPointerConversionToVoidPointer(ASTContext& Context) const {
242
7.63M
  QualType FromType = getFromType();
243
7.63M
  QualType ToType = getToType(1);
244
7.63M
245
7.63M
  // Note that FromType has not necessarily been transformed by the
246
7.63M
  // array-to-pointer implicit conversion, so check for its presence
247
7.63M
  // and redo the conversion to get a pointer.
248
7.63M
  if (First == ICK_Array_To_Pointer)
249
21.5k
    FromType = Context.getArrayDecayedType(FromType);
250
7.63M
251
7.63M
  if (Second == ICK_Pointer_Conversion && 
FromType->isAnyPointerType()12.6k
)
252
7.84k
    if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
253
7.72k
      return ToPtrType->getPointeeType()->isVoidType();
254
7.63M
255
7.63M
  return false;
256
7.63M
}
257
258
/// Skip any implicit casts which could be either part of a narrowing conversion
259
/// or after one in an implicit conversion.
260
267k
static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
261
534k
  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
262
267k
    switch (ICE->getCastKind()) {
263
267k
    case CK_NoOp:
264
267k
    case CK_IntegralCast:
265
267k
    case CK_IntegralToBoolean:
266
267k
    case CK_IntegralToFloating:
267
267k
    case CK_BooleanToSignedIntegral:
268
267k
    case CK_FloatingToIntegral:
269
267k
    case CK_FloatingToBoolean:
270
267k
    case CK_FloatingCast:
271
267k
      Converted = ICE->getSubExpr();
272
267k
      continue;
273
267k
274
267k
    default:
275
311
      return Converted;
276
267k
    }
277
267k
  }
278
267k
279
267k
  
return Converted267k
;
280
267k
}
281
282
/// Check if this standard conversion sequence represents a narrowing
283
/// conversion, according to C++11 [dcl.init.list]p7.
284
///
285
/// \param Ctx  The AST context.
286
/// \param Converted  The result of applying this standard conversion sequence.
287
/// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
288
///        value of the expression prior to the narrowing conversion.
289
/// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
290
///        type of the expression prior to the narrowing conversion.
291
/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
292
///        from floating point types to integral types should be ignored.
293
NarrowingKind StandardConversionSequence::getNarrowingKind(
294
    ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
295
2.69M
    QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
296
2.69M
  assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
297
2.69M
298
2.69M
  // C++11 [dcl.init.list]p7:
299
2.69M
  //   A narrowing conversion is an implicit conversion ...
300
2.69M
  QualType FromType = getToType(0);
301
2.69M
  QualType ToType = getToType(1);
302
2.69M
303
2.69M
  // A conversion to an enumeration type is narrowing if the conversion to
304
2.69M
  // the underlying type is narrowing. This only arises for expressions of
305
2.69M
  // the form 'Enum{init}'.
306
2.69M
  if (auto *ET = ToType->getAs<EnumType>())
307
3.29k
    ToType = ET->getDecl()->getIntegerType();
308
2.69M
309
2.69M
  switch (Second) {
310
2.69M
  // 'bool' is an integral type; dispatch to the right place to handle it.
311
2.69M
  case ICK_Boolean_Conversion:
312
510
    if (FromType->isRealFloatingType())
313
2
      goto FloatingIntegralConversion;
314
508
    if (FromType->isIntegralOrUnscopedEnumerationType())
315
505
      goto IntegralConversion;
316
3
    // Boolean conversions can be from pointers and pointers to members
317
3
    // [conv.bool], and those aren't considered narrowing conversions.
318
3
    return NK_Not_Narrowing;
319
1.14k
320
1.14k
  // -- from a floating-point type to an integer type, or
321
1.14k
  //
322
1.14k
  // -- from an integer type or unscoped enumeration type to a floating-point
323
1.14k
  //    type, except where the source is a constant expression and the actual
324
1.14k
  //    value after conversion will fit into the target type and will produce
325
1.14k
  //    the original value when converted back to the original type, or
326
1.14k
  case ICK_Floating_Integral:
327
1.14k
  FloatingIntegralConversion:
328
1.14k
    if (FromType->isRealFloatingType() && 
ToType->isIntegralType(Ctx)73
) {
329
73
      return NK_Type_Narrowing;
330
1.07k
    } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
331
1.07k
               ToType->isRealFloatingType()) {
332
1.07k
      if (IgnoreFloatToIntegralConversion)
333
6
        return NK_Not_Narrowing;
334
1.06k
      llvm::APSInt IntConstantValue;
335
1.06k
      const Expr *Initializer = IgnoreNarrowingConversion(Converted);
336
1.06k
      assert(Initializer && "Unknown conversion expression");
337
1.06k
338
1.06k
      // If it's value-dependent, we can't tell whether it's narrowing.
339
1.06k
      if (Initializer->isValueDependent())
340
0
        return NK_Dependent_Narrowing;
341
1.06k
342
1.06k
      if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
343
1.04k
        // Convert the integer to the floating type.
344
1.04k
        llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
345
1.04k
        Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
346
1.04k
                                llvm::APFloat::rmNearestTiesToEven);
347
1.04k
        // And back.
348
1.04k
        llvm::APSInt ConvertedValue = IntConstantValue;
349
1.04k
        bool ignored;
350
1.04k
        Result.convertToInteger(ConvertedValue,
351
1.04k
                                llvm::APFloat::rmTowardZero, &ignored);
352
1.04k
        // If the resulting value is different, this was a narrowing conversion.
353
1.04k
        if (IntConstantValue != ConvertedValue) {
354
6
          ConstantValue = APValue(IntConstantValue);
355
6
          ConstantType = Initializer->getType();
356
6
          return NK_Constant_Narrowing;
357
6
        }
358
24
      } else {
359
24
        // Variables are always narrowings.
360
24
        return NK_Variable_Narrowing;
361
24
      }
362
1.03k
    }
363
1.03k
    return NK_Not_Narrowing;
364
1.03k
365
1.03k
  // -- from long double to double or float, or from double to float, except
366
1.03k
  //    where the source is a constant expression and the actual value after
367
1.03k
  //    conversion is within the range of values that can be represented (even
368
1.03k
  //    if it cannot be represented exactly), or
369
1.03k
  case ICK_Floating_Conversion:
370
840
    if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
371
840
        Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
372
839
      // FromType is larger than ToType.
373
839
      const Expr *Initializer = IgnoreNarrowingConversion(Converted);
374
839
375
839
      // If it's value-dependent, we can't tell whether it's narrowing.
376
839
      if (Initializer->isValueDependent())
377
0
        return NK_Dependent_Narrowing;
378
839
379
839
      if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
380
823
        // Constant!
381
823
        assert(ConstantValue.isFloat());
382
823
        llvm::APFloat FloatVal = ConstantValue.getFloat();
383
823
        // Convert the source value into the target type.
384
823
        bool ignored;
385
823
        llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
386
823
          Ctx.getFloatTypeSemantics(ToType),
387
823
          llvm::APFloat::rmNearestTiesToEven, &ignored);
388
823
        // If there was no overflow, the source value is within the range of
389
823
        // values that can be represented.
390
823
        if (ConvertStatus & llvm::APFloat::opOverflow) {
391
13
          ConstantType = Initializer->getType();
392
13
          return NK_Constant_Narrowing;
393
13
        }
394
16
      } else {
395
16
        return NK_Variable_Narrowing;
396
16
      }
397
811
    }
398
811
    return NK_Not_Narrowing;
399
286k
400
286k
  // -- from an integer type or unscoped enumeration type to an integer type
401
286k
  //    that cannot represent all the values of the original type, except where
402
286k
  //    the source is a constant expression and the actual value after
403
286k
  //    conversion will fit into the target type and will produce the original
404
286k
  //    value when converted back to the original type.
405
286k
  case ICK_Integral_Conversion:
406
286k
  IntegralConversion: {
407
286k
    assert(FromType->isIntegralOrUnscopedEnumerationType());
408
286k
    assert(ToType->isIntegralOrUnscopedEnumerationType());
409
286k
    const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
410
286k
    const unsigned FromWidth = Ctx.getIntWidth(FromType);
411
286k
    const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
412
286k
    const unsigned ToWidth = Ctx.getIntWidth(ToType);
413
286k
414
286k
    if (FromWidth > ToWidth ||
415
286k
        
(157k
FromWidth == ToWidth157k
&&
FromSigned != ToSigned46.7k
) ||
416
286k
        
(120k
FromSigned120k
&&
!ToSigned117k
)) {
417
265k
      // Not all values of FromType can be represented in ToType.
418
265k
      llvm::APSInt InitializerValue;
419
265k
      const Expr *Initializer = IgnoreNarrowingConversion(Converted);
420
265k
421
265k
      // If it's value-dependent, we can't tell whether it's narrowing.
422
265k
      if (Initializer->isValueDependent())
423
283
        return NK_Dependent_Narrowing;
424
265k
425
265k
      if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
426
1.31k
        // Such conversions on variables are always narrowing.
427
1.31k
        return NK_Variable_Narrowing;
428
1.31k
      }
429
263k
      bool Narrowing = false;
430
263k
      if (FromWidth < ToWidth) {
431
99.2k
        // Negative -> unsigned is narrowing. Otherwise, more bits is never
432
99.2k
        // narrowing.
433
99.2k
        if (InitializerValue.isSigned() && InitializerValue.isNegative())
434
5
          Narrowing = true;
435
164k
      } else {
436
164k
        // Add a bit to the InitializerValue so we don't have to worry about
437
164k
        // signed vs. unsigned comparisons.
438
164k
        InitializerValue = InitializerValue.extend(
439
164k
          InitializerValue.getBitWidth() + 1);
440
164k
        // Convert the initializer to and from the target width and signed-ness.
441
164k
        llvm::APSInt ConvertedValue = InitializerValue;
442
164k
        ConvertedValue = ConvertedValue.trunc(ToWidth);
443
164k
        ConvertedValue.setIsSigned(ToSigned);
444
164k
        ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
445
164k
        ConvertedValue.setIsSigned(InitializerValue.isSigned());
446
164k
        // If the result is different, this was a narrowing conversion.
447
164k
        if (ConvertedValue != InitializerValue)
448
98
          Narrowing = true;
449
164k
      }
450
263k
      if (Narrowing) {
451
103
        ConstantType = Initializer->getType();
452
103
        ConstantValue = APValue(InitializerValue);
453
103
        return NK_Constant_Narrowing;
454
103
      }
455
285k
    }
456
285k
    return NK_Not_Narrowing;
457
285k
  }
458
285k
459
2.40M
  default:
460
2.40M
    // Other kinds of conversions are not narrowings.
461
2.40M
    return NK_Not_Narrowing;
462
2.69M
  }
463
2.69M
}
464
465
/// dump - Print this standard conversion sequence to standard
466
/// error. Useful for debugging overloading issues.
467
0
LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
468
0
  raw_ostream &OS = llvm::errs();
469
0
  bool PrintedSomething = false;
470
0
  if (First != ICK_Identity) {
471
0
    OS << GetImplicitConversionName(First);
472
0
    PrintedSomething = true;
473
0
  }
474
0
475
0
  if (Second != ICK_Identity) {
476
0
    if (PrintedSomething) {
477
0
      OS << " -> ";
478
0
    }
479
0
    OS << GetImplicitConversionName(Second);
480
0
481
0
    if (CopyConstructor) {
482
0
      OS << " (by copy constructor)";
483
0
    } else if (DirectBinding) {
484
0
      OS << " (direct reference binding)";
485
0
    } else if (ReferenceBinding) {
486
0
      OS << " (reference binding)";
487
0
    }
488
0
    PrintedSomething = true;
489
0
  }
490
0
491
0
  if (Third != ICK_Identity) {
492
0
    if (PrintedSomething) {
493
0
      OS << " -> ";
494
0
    }
495
0
    OS << GetImplicitConversionName(Third);
496
0
    PrintedSomething = true;
497
0
  }
498
0
499
0
  if (!PrintedSomething) {
500
0
    OS << "No conversions required";
501
0
  }
502
0
}
503
504
/// dump - Print this user-defined conversion sequence to standard
505
/// error. Useful for debugging overloading issues.
506
0
void UserDefinedConversionSequence::dump() const {
507
0
  raw_ostream &OS = llvm::errs();
508
0
  if (Before.First || Before.Second || Before.Third) {
509
0
    Before.dump();
510
0
    OS << " -> ";
511
0
  }
512
0
  if (ConversionFunction)
513
0
    OS << '\'' << *ConversionFunction << '\'';
514
0
  else
515
0
    OS << "aggregate initialization";
516
0
  if (After.First || After.Second || After.Third) {
517
0
    OS << " -> ";
518
0
    After.dump();
519
0
  }
520
0
}
521
522
/// dump - Print this implicit conversion sequence to standard
523
/// error. Useful for debugging overloading issues.
524
0
void ImplicitConversionSequence::dump() const {
525
0
  raw_ostream &OS = llvm::errs();
526
0
  if (isStdInitializerListElement())
527
0
    OS << "Worst std::initializer_list element conversion: ";
528
0
  switch (ConversionKind) {
529
0
  case StandardConversion:
530
0
    OS << "Standard conversion: ";
531
0
    Standard.dump();
532
0
    break;
533
0
  case UserDefinedConversion:
534
0
    OS << "User-defined conversion: ";
535
0
    UserDefined.dump();
536
0
    break;
537
0
  case EllipsisConversion:
538
0
    OS << "Ellipsis conversion";
539
0
    break;
540
0
  case AmbiguousConversion:
541
0
    OS << "Ambiguous conversion";
542
0
    break;
543
0
  case BadConversion:
544
0
    OS << "Bad conversion";
545
0
    break;
546
0
  }
547
0
548
0
  OS << "\n";
549
0
}
550
551
273
void AmbiguousConversionSequence::construct() {
552
273
  new (&conversions()) ConversionSet();
553
273
}
554
555
578
void AmbiguousConversionSequence::destruct() {
556
578
  conversions().~ConversionSet();
557
578
}
558
559
void
560
305
AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
561
305
  FromTypePtr = O.FromTypePtr;
562
305
  ToTypePtr = O.ToTypePtr;
563
305
  new (&conversions()) ConversionSet(O.conversions());
564
305
}
565
566
namespace {
567
  // Structure used by DeductionFailureInfo to store
568
  // template argument information.
569
  struct DFIArguments {
570
    TemplateArgument FirstArg;
571
    TemplateArgument SecondArg;
572
  };
573
  // Structure used by DeductionFailureInfo to store
574
  // template parameter and template argument information.
575
  struct DFIParamWithArguments : DFIArguments {
576
    TemplateParameter Param;
577
  };
578
  // Structure used by DeductionFailureInfo to store template argument
579
  // information and the index of the problematic call argument.
580
  struct DFIDeducedMismatchArgs : DFIArguments {
581
    TemplateArgumentList *TemplateArgs;
582
    unsigned CallArgIndex;
583
  };
584
}
585
586
/// Convert from Sema's representation of template deduction information
587
/// to the form used in overload-candidate information.
588
DeductionFailureInfo
589
clang::MakeDeductionFailureInfo(ASTContext &Context,
590
                                Sema::TemplateDeductionResult TDK,
591
2.13M
                                TemplateDeductionInfo &Info) {
592
2.13M
  DeductionFailureInfo Result;
593
2.13M
  Result.Result = static_cast<unsigned>(TDK);
594
2.13M
  Result.HasDiagnostic = false;
595
2.13M
  switch (TDK) {
596
2.13M
  case Sema::TDK_Invalid:
597
356k
  case Sema::TDK_InstantiationDepth:
598
356k
  case Sema::TDK_TooManyArguments:
599
356k
  case Sema::TDK_TooFewArguments:
600
356k
  case Sema::TDK_MiscellaneousDeductionFailure:
601
356k
  case Sema::TDK_CUDATargetMismatch:
602
356k
    Result.Data = nullptr;
603
356k
    break;
604
356k
605
356k
  case Sema::TDK_Incomplete:
606
25.7k
  case Sema::TDK_InvalidExplicitArguments:
607
25.7k
    Result.Data = Info.Param.getOpaqueValue();
608
25.7k
    break;
609
25.7k
610
25.7k
  case Sema::TDK_DeducedMismatch:
611
1.09k
  case Sema::TDK_DeducedMismatchNested: {
612
1.09k
    // FIXME: Should allocate from normal heap so that we can free this later.
613
1.09k
    auto *Saved = new (Context) DFIDeducedMismatchArgs;
614
1.09k
    Saved->FirstArg = Info.FirstArg;
615
1.09k
    Saved->SecondArg = Info.SecondArg;
616
1.09k
    Saved->TemplateArgs = Info.take();
617
1.09k
    Saved->CallArgIndex = Info.CallArgIndex;
618
1.09k
    Result.Data = Saved;
619
1.09k
    break;
620
1.09k
  }
621
1.09k
622
1.49M
  case Sema::TDK_NonDeducedMismatch: {
623
1.49M
    // FIXME: Should allocate from normal heap so that we can free this later.
624
1.49M
    DFIArguments *Saved = new (Context) DFIArguments;
625
1.49M
    Saved->FirstArg = Info.FirstArg;
626
1.49M
    Saved->SecondArg = Info.SecondArg;
627
1.49M
    Result.Data = Saved;
628
1.49M
    break;
629
1.09k
  }
630
1.09k
631
112k
  case Sema::TDK_IncompletePack:
632
112k
    // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
633
112k
  case Sema::TDK_Inconsistent:
634
112k
  case Sema::TDK_Underqualified: {
635
112k
    // FIXME: Should allocate from normal heap so that we can free this later.
636
112k
    DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
637
112k
    Saved->Param = Info.Param;
638
112k
    Saved->FirstArg = Info.FirstArg;
639
112k
    Saved->SecondArg = Info.SecondArg;
640
112k
    Result.Data = Saved;
641
112k
    break;
642
112k
  }
643
112k
644
147k
  case Sema::TDK_SubstitutionFailure:
645
147k
    Result.Data = Info.take();
646
147k
    if (Info.hasSFINAEDiagnostic()) {
647
147k
      PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
648
147k
          SourceLocation(), PartialDiagnostic::NullDiagnostic());
649
147k
      Info.takeSFINAEDiagnostic(*Diag);
650
147k
      Result.HasDiagnostic = true;
651
147k
    }
652
147k
    break;
653
112k
654
112k
  case Sema::TDK_Success:
655
0
  case Sema::TDK_NonDependentConversionFailure:
656
0
    llvm_unreachable("not a deduction failure");
657
2.13M
  }
658
2.13M
659
2.13M
  return Result;
660
2.13M
}
661
662
2.13M
void DeductionFailureInfo::Destroy() {
663
2.13M
  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
664
2.13M
  case Sema::TDK_Success:
665
381k
  case Sema::TDK_Invalid:
666
381k
  case Sema::TDK_InstantiationDepth:
667
381k
  case Sema::TDK_Incomplete:
668
381k
  case Sema::TDK_TooManyArguments:
669
381k
  case Sema::TDK_TooFewArguments:
670
381k
  case Sema::TDK_InvalidExplicitArguments:
671
381k
  case Sema::TDK_CUDATargetMismatch:
672
381k
  case Sema::TDK_NonDependentConversionFailure:
673
381k
    break;
674
381k
675
1.61M
  case Sema::TDK_IncompletePack:
676
1.61M
  case Sema::TDK_Inconsistent:
677
1.61M
  case Sema::TDK_Underqualified:
678
1.61M
  case Sema::TDK_DeducedMismatch:
679
1.61M
  case Sema::TDK_DeducedMismatchNested:
680
1.61M
  case Sema::TDK_NonDeducedMismatch:
681
1.61M
    // FIXME: Destroy the data?
682
1.61M
    Data = nullptr;
683
1.61M
    break;
684
1.61M
685
1.61M
  case Sema::TDK_SubstitutionFailure:
686
147k
    // FIXME: Destroy the template argument list?
687
147k
    Data = nullptr;
688
147k
    if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
689
147k
      Diag->~PartialDiagnosticAt();
690
147k
      HasDiagnostic = false;
691
147k
    }
692
147k
    break;
693
1.61M
694
1.61M
  // Unhandled
695
1.61M
  case Sema::TDK_MiscellaneousDeductionFailure:
696
594
    break;
697
2.13M
  }
698
2.13M
}
699
700
147k
PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
701
147k
  if (HasDiagnostic)
702
147k
    return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
703
53
  return nullptr;
704
53
}
705
706
895
TemplateParameter DeductionFailureInfo::getTemplateParameter() {
707
895
  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
708
895
  case Sema::TDK_Success:
709
509
  case Sema::TDK_Invalid:
710
509
  case Sema::TDK_InstantiationDepth:
711
509
  case Sema::TDK_TooManyArguments:
712
509
  case Sema::TDK_TooFewArguments:
713
509
  case Sema::TDK_SubstitutionFailure:
714
509
  case Sema::TDK_DeducedMismatch:
715
509
  case Sema::TDK_DeducedMismatchNested:
716
509
  case Sema::TDK_NonDeducedMismatch:
717
509
  case Sema::TDK_CUDATargetMismatch:
718
509
  case Sema::TDK_NonDependentConversionFailure:
719
509
    return TemplateParameter();
720
509
721
509
  case Sema::TDK_Incomplete:
722
272
  case Sema::TDK_InvalidExplicitArguments:
723
272
    return TemplateParameter::getFromOpaqueValue(Data);
724
272
725
272
  case Sema::TDK_IncompletePack:
726
104
  case Sema::TDK_Inconsistent:
727
104
  case Sema::TDK_Underqualified:
728
104
    return static_cast<DFIParamWithArguments*>(Data)->Param;
729
104
730
104
  // Unhandled
731
104
  case Sema::TDK_MiscellaneousDeductionFailure:
732
10
    break;
733
10
  }
734
10
735
10
  return TemplateParameter();
736
10
}
737
738
242
TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
739
242
  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
740
242
  case Sema::TDK_Success:
741
0
  case Sema::TDK_Invalid:
742
0
  case Sema::TDK_InstantiationDepth:
743
0
  case Sema::TDK_TooManyArguments:
744
0
  case Sema::TDK_TooFewArguments:
745
0
  case Sema::TDK_Incomplete:
746
0
  case Sema::TDK_IncompletePack:
747
0
  case Sema::TDK_InvalidExplicitArguments:
748
0
  case Sema::TDK_Inconsistent:
749
0
  case Sema::TDK_Underqualified:
750
0
  case Sema::TDK_NonDeducedMismatch:
751
0
  case Sema::TDK_CUDATargetMismatch:
752
0
  case Sema::TDK_NonDependentConversionFailure:
753
0
    return nullptr;
754
0
755
8
  case Sema::TDK_DeducedMismatch:
756
8
  case Sema::TDK_DeducedMismatchNested:
757
8
    return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
758
8
759
234
  case Sema::TDK_SubstitutionFailure:
760
234
    return static_cast<TemplateArgumentList*>(Data);
761
8
762
8
  // Unhandled
763
8
  case Sema::TDK_MiscellaneousDeductionFailure:
764
0
    break;
765
0
  }
766
0
767
0
  return nullptr;
768
0
}
769
770
283
const TemplateArgument *DeductionFailureInfo::getFirstArg() {
771
283
  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
772
283
  case Sema::TDK_Success:
773
0
  case Sema::TDK_Invalid:
774
0
  case Sema::TDK_InstantiationDepth:
775
0
  case Sema::TDK_Incomplete:
776
0
  case Sema::TDK_TooManyArguments:
777
0
  case Sema::TDK_TooFewArguments:
778
0
  case Sema::TDK_InvalidExplicitArguments:
779
0
  case Sema::TDK_SubstitutionFailure:
780
0
  case Sema::TDK_CUDATargetMismatch:
781
0
  case Sema::TDK_NonDependentConversionFailure:
782
0
    return nullptr;
783
0
784
283
  case Sema::TDK_IncompletePack:
785
283
  case Sema::TDK_Inconsistent:
786
283
  case Sema::TDK_Underqualified:
787
283
  case Sema::TDK_DeducedMismatch:
788
283
  case Sema::TDK_DeducedMismatchNested:
789
283
  case Sema::TDK_NonDeducedMismatch:
790
283
    return &static_cast<DFIArguments*>(Data)->FirstArg;
791
283
792
283
  // Unhandled
793
283
  case Sema::TDK_MiscellaneousDeductionFailure:
794
0
    break;
795
0
  }
796
0
797
0
  return nullptr;
798
0
}
799
800
267
const TemplateArgument *DeductionFailureInfo::getSecondArg() {
801
267
  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
802
267
  case Sema::TDK_Success:
803
0
  case Sema::TDK_Invalid:
804
0
  case Sema::TDK_InstantiationDepth:
805
0
  case Sema::TDK_Incomplete:
806
0
  case Sema::TDK_IncompletePack:
807
0
  case Sema::TDK_TooManyArguments:
808
0
  case Sema::TDK_TooFewArguments:
809
0
  case Sema::TDK_InvalidExplicitArguments:
810
0
  case Sema::TDK_SubstitutionFailure:
811
0
  case Sema::TDK_CUDATargetMismatch:
812
0
  case Sema::TDK_NonDependentConversionFailure:
813
0
    return nullptr;
814
0
815
267
  case Sema::TDK_Inconsistent:
816
267
  case Sema::TDK_Underqualified:
817
267
  case Sema::TDK_DeducedMismatch:
818
267
  case Sema::TDK_DeducedMismatchNested:
819
267
  case Sema::TDK_NonDeducedMismatch:
820
267
    return &static_cast<DFIArguments*>(Data)->SecondArg;
821
267
822
267
  // Unhandled
823
267
  case Sema::TDK_MiscellaneousDeductionFailure:
824
0
    break;
825
0
  }
826
0
827
0
  return nullptr;
828
0
}
829
830
8
llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
831
8
  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
832
8
  case Sema::TDK_DeducedMismatch:
833
8
  case Sema::TDK_DeducedMismatchNested:
834
8
    return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
835
8
836
8
  default:
837
0
    return llvm::None;
838
8
  }
839
8
}
840
841
22.4M
void OverloadCandidateSet::destroyCandidates() {
842
45.7M
  for (iterator i = begin(), e = end(); i != e; 
++i23.3M
) {
843
23.3M
    for (auto &C : i->Conversions)
844
39.2M
      C.~ImplicitConversionSequence();
845
23.3M
    if (!i->Viable && 
i->FailureKind == ovl_fail_bad_deduction11.0M
)
846
1.46M
      i->DeductionFailure.Destroy();
847
23.3M
  }
848
22.4M
}
849
850
2.16M
void OverloadCandidateSet::clear(CandidateSetKind CSK) {
851
2.16M
  destroyCandidates();
852
2.16M
  SlabAllocator.Reset();
853
2.16M
  NumInlineBytesUsed = 0;
854
2.16M
  Candidates.clear();
855
2.16M
  Functions.clear();
856
2.16M
  Kind = CSK;
857
2.16M
}
858
859
namespace {
860
  class UnbridgedCastsSet {
861
    struct Entry {
862
      Expr **Addr;
863
      Expr *Saved;
864
    };
865
    SmallVector<Entry, 2> Entries;
866
867
  public:
868
7
    void save(Sema &S, Expr *&E) {
869
7
      assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
870
7
      Entry entry = { &E, E };
871
7
      Entries.push_back(entry);
872
7
      E = S.stripARCUnbridgedCast(E);
873
7
    }
874
875
1.46M
    void restore() {
876
1.46M
      for (SmallVectorImpl<Entry>::iterator
877
1.46M
             i = Entries.begin(), e = Entries.end(); i != e; 
++i7
)
878
7
        *i->Addr = i->Saved;
879
1.46M
    }
880
  };
881
}
882
883
/// checkPlaceholderForOverload - Do any interesting placeholder-like
884
/// preprocessing on the given expression.
885
///
886
/// \param unbridgedCasts a collection to which to add unbridged casts;
887
///   without this, they will be immediately diagnosed as errors
888
///
889
/// Return true on unrecoverable error.
890
static bool
891
checkPlaceholderForOverload(Sema &S, Expr *&E,
892
9.21M
                            UnbridgedCastsSet *unbridgedCasts = nullptr) {
893
9.21M
  if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
894
1.97k
    // We can't handle overloaded expressions here because overload
895
1.97k
    // resolution might reasonably tweak them.
896
1.97k
    if (placeholder->getKind() == BuiltinType::Overload) 
return false1.96k
;
897
9
898
9
    // If the context potentially accepts unbridged ARC casts, strip
899
9
    // the unbridged cast and add it to the collection for later restoration.
900
9
    if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
901
9
        
unbridgedCasts7
) {
902
7
      unbridgedCasts->save(S, E);
903
7
      return false;
904
7
    }
905
2
906
2
    // Go ahead and check everything else.
907
2
    ExprResult result = S.CheckPlaceholderExpr(E);
908
2
    if (result.isInvalid())
909
0
      return true;
910
2
911
2
    E = result.get();
912
2
    return false;
913
2
  }
914
9.21M
915
9.21M
  // Nothing to do.
916
9.21M
  return false;
917
9.21M
}
918
919
/// checkArgPlaceholdersForOverload - Check a set of call operands for
920
/// placeholders.
921
static bool checkArgPlaceholdersForOverload(Sema &S,
922
                                            MultiExprArg Args,
923
1.46M
                                            UnbridgedCastsSet &unbridged) {
924
3.11M
  for (unsigned i = 0, e = Args.size(); i != e; 
++i1.64M
)
925
1.64M
    if (checkPlaceholderForOverload(S, Args[i], &unbridged))
926
0
      return true;
927
1.46M
928
1.46M
  return false;
929
1.46M
}
930
931
/// Determine whether the given New declaration is an overload of the
932
/// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
933
/// New and Old cannot be overloaded, e.g., if New has the same signature as
934
/// some function in Old (C++ 1.3.10) or if the Old declarations aren't
935
/// functions (or function templates) at all. When it does return Ovl_Match or
936
/// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
937
/// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
938
/// declaration.
939
///
940
/// Example: Given the following input:
941
///
942
///   void f(int, float); // #1
943
///   void f(int, int); // #2
944
///   int f(int, int); // #3
945
///
946
/// When we process #1, there is no previous declaration of "f", so IsOverload
947
/// will not be used.
948
///
949
/// When we process #2, Old contains only the FunctionDecl for #1. By comparing
950
/// the parameter types, we see that #1 and #2 are overloaded (since they have
951
/// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
952
/// unchanged.
953
///
954
/// When we process #3, Old is an overload set containing #1 and #2. We compare
955
/// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
956
/// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
957
/// functions are not part of the signature), IsOverload returns Ovl_Match and
958
/// MatchedDecl will be set to point to the FunctionDecl for #2.
959
///
960
/// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
961
/// by a using declaration. The rules for whether to hide shadow declarations
962
/// ignore some properties which otherwise figure into a function template's
963
/// signature.
964
Sema::OverloadKind
965
Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
966
2.27M
                    NamedDecl *&Match, bool NewIsUsingDecl) {
967
2.27M
  for (LookupResult::iterator I = Old.begin(), E = Old.end();
968
14.3M
         I != E; 
++I12.1M
) {
969
12.4M
    NamedDecl *OldD = *I;
970
12.4M
971
12.4M
    bool OldIsUsingDecl = false;
972
12.4M
    if (isa<UsingShadowDecl>(OldD)) {
973
10.4k
      OldIsUsingDecl = true;
974
10.4k
975
10.4k
      // We can always introduce two using declarations into the same
976
10.4k
      // context, even if they have identical signatures.
977
10.4k
      if (NewIsUsingDecl) 
continue922
;
978
9.57k
979
9.57k
      OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
980
9.57k
    }
981
12.4M
982
12.4M
    // A using-declaration does not conflict with another declaration
983
12.4M
    // if one of them is hidden.
984
12.4M
    
if (12.4M
(12.4M
OldIsUsingDecl12.4M
||
NewIsUsingDecl12.4M
) &&
!isVisible(*I)10.3k
)
985
0
      continue;
986
12.4M
987
12.4M
    // If either declaration was introduced by a using declaration,
988
12.4M
    // we'll need to use slightly different rules for matching.
989
12.4M
    // Essentially, these rules are the normal rules, except that
990
12.4M
    // function templates hide function templates with different
991
12.4M
    // return types or template parameter lists.
992
12.4M
    bool UseMemberUsingDeclRules =
993
12.4M
      (OldIsUsingDecl || 
NewIsUsingDecl12.4M
) &&
CurContext->isRecord()10.3k
&&
994
12.4M
      
!New->getFriendObjectKind()3.57k
;
995
12.4M
996
12.4M
    if (FunctionDecl *OldF = OldD->getAsFunction()) {
997
12.4M
      if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
998
311k
        if (UseMemberUsingDeclRules && 
OldIsUsingDecl197
) {
999
174
          HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1000
174
          continue;
1001
174
        }
1002
310k
1003
310k
        if (!isa<FunctionTemplateDecl>(OldD) &&
1004
310k
            
!shouldLinkPossiblyHiddenDecl(*I, New)241k
)
1005
0
          continue;
1006
310k
1007
310k
        Match = *I;
1008
310k
        return Ovl_Match;
1009
310k
      }
1010
12.1M
1011
12.1M
      // Builtins that have custom typechecking or have a reference should
1012
12.1M
      // not be overloadable or redeclarable.
1013
12.1M
      if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1014
3
        Match = *I;
1015
3
        return Ovl_NonFunction;
1016
3
      }
1017
412
    } else if (isa<UsingDecl>(OldD) || 
isa<UsingPackDecl>(OldD)40
) {
1018
372
      // We can overload with these, which can show up when doing
1019
372
      // redeclaration checks for UsingDecls.
1020
372
      assert(Old.getLookupKind() == LookupUsingDeclName);
1021
372
    } else 
if (40
isa<TagDecl>(OldD)40
) {
1022
2
      // We can always overload with tags by hiding them.
1023
38
    } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1024
19
      // Optimistically assume that an unresolved using decl will
1025
19
      // overload; if it doesn't, we'll have to diagnose during
1026
19
      // template instantiation.
1027
19
      //
1028
19
      // Exception: if the scope is dependent and this is not a class
1029
19
      // member, the using declaration can only introduce an enumerator.
1030
19
      if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1031
5
        Match = *I;
1032
5
        return Ovl_NonFunction;
1033
5
      }
1034
19
    } else {
1035
19
      // (C++ 13p1):
1036
19
      //   Only function declarations can be overloaded; object and type
1037
19
      //   declarations cannot be overloaded.
1038
19
      Match = *I;
1039
19
      return Ovl_NonFunction;
1040
19
    }
1041
12.4M
  }
1042
2.27M
1043
2.27M
  // C++ [temp.friend]p1:
1044
2.27M
  //   For a friend function declaration that is not a template declaration:
1045
2.27M
  //    -- if the name of the friend is a qualified or unqualified template-id,
1046
2.27M
  //       [...], otherwise
1047
2.27M
  //    -- if the name of the friend is a qualified-id and a matching
1048
2.27M
  //       non-template function is found in the specified class or namespace,
1049
2.27M
  //       the friend declaration refers to that function, otherwise,
1050
2.27M
  //    -- if the name of the friend is a qualified-id and a matching function
1051
2.27M
  //       template is found in the specified class or namespace, the friend
1052
2.27M
  //       declaration refers to the deduced specialization of that function
1053
2.27M
  //       template, otherwise
1054
2.27M
  //    -- the name shall be an unqualified-id [...]
1055
2.27M
  // If we get here for a qualified friend declaration, we've just reached the
1056
2.27M
  // third bullet. If the type of the friend is dependent, skip this lookup
1057
2.27M
  // until instantiation.
1058
2.27M
  
if (1.96M
New->getFriendObjectKind()1.96M
&&
New->getQualifier()32.4k
&&
1059
1.96M
      
!New->getDescribedFunctionTemplate()107
&&
1060
1.96M
      
!New->getDependentSpecializationInfo()48
&&
1061
1.96M
      
!New->getType()->isDependentType()42
) {
1062
37
    LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1063
37
    TemplateSpecResult.addAllDecls(Old);
1064
37
    if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1065
37
                                            /*QualifiedFriend*/true)) {
1066
21
      New->setInvalidDecl();
1067
21
      return Ovl_Overload;
1068
21
    }
1069
16
1070
16
    Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1071
16
    return Ovl_Match;
1072
16
  }
1073
1.96M
1074
1.96M
  return Ovl_Overload;
1075
1.96M
}
1076
1077
bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1078
12.5M
                      bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1079
12.5M
  // C++ [basic.start.main]p2: This function shall not be overloaded.
1080
12.5M
  if (New->isMain())
1081
12
    return false;
1082
12.5M
1083
12.5M
  // MSVCRT user defined entry points cannot be overloaded.
1084
12.5M
  if (New->isMSVCRTEntryPoint())
1085
1
    return false;
1086
12.5M
1087
12.5M
  FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1088
12.5M
  FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1089
12.5M
1090
12.5M
  // C++ [temp.fct]p2:
1091
12.5M
  //   A function template can be overloaded with other function templates
1092
12.5M
  //   and with normal (non-template) functions.
1093
12.5M
  if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1094
1.53M
    return true;
1095
10.9M
1096
10.9M
  // Is the function New an overload of the function Old?
1097
10.9M
  QualType OldQType = Context.getCanonicalType(Old->getType());
1098
10.9M
  QualType NewQType = Context.getCanonicalType(New->getType());
1099
10.9M
1100
10.9M
  // Compare the signatures (C++ 1.3.10) of the two functions to
1101
10.9M
  // determine whether they are overloads. If we find any mismatch
1102
10.9M
  // in the signature, they are overloads.
1103
10.9M
1104
10.9M
  // If either of these functions is a K&R-style function (no
1105
10.9M
  // prototype), then we consider them to have matching signatures.
1106
10.9M
  if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1107
10.9M
      isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1108
0
    return false;
1109
10.9M
1110
10.9M
  const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1111
10.9M
  const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1112
10.9M
1113
10.9M
  // The signature of a function includes the types of its
1114
10.9M
  // parameters (C++ 1.3.10), which includes the presence or absence
1115
10.9M
  // of the ellipsis; see C++ DR 357).
1116
10.9M
  if (OldQType != NewQType &&
1117
10.9M
      
(10.5M
OldType->getNumParams() != NewType->getNumParams()10.5M
||
1118
10.5M
       
OldType->isVariadic() != NewType->isVariadic()9.08M
||
1119
10.5M
       
!FunctionParamTypesAreEqual(OldType, NewType)9.08M
))
1120
10.3M
    return true;
1121
610k
1122
610k
  // C++ [temp.over.link]p4:
1123
610k
  //   The signature of a function template consists of its function
1124
610k
  //   signature, its return type and its template parameter list. The names
1125
610k
  //   of the template parameters are significant only for establishing the
1126
610k
  //   relationship between the template parameters and the rest of the
1127
610k
  //   signature.
1128
610k
  //
1129
610k
  // We check the return type and template parameter lists for function
1130
610k
  // templates first; the remaining checks follow.
1131
610k
  //
1132
610k
  // However, we don't consider either of these when deciding whether
1133
610k
  // a member introduced by a shadow declaration is hidden.
1134
610k
  if (!UseMemberUsingDeclRules && 
NewTemplate610k
&&
1135
610k
      
(115k
!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1136
115k
                                       OldTemplate->getTemplateParameters(),
1137
115k
                                       false, TPL_TemplateMatch) ||
1138
115k
       !Context.hasSameType(Old->getDeclaredReturnType(),
1139
103k
                            New->getDeclaredReturnType())))
1140
45.7k
    return true;
1141
565k
1142
565k
  // If the function is a class member, its signature includes the
1143
565k
  // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1144
565k
  //
1145
565k
  // As part of this, also check whether one of the member functions
1146
565k
  // is static, in which case they are not overloads (C++
1147
565k
  // 13.1p2). While not part of the definition of the signature,
1148
565k
  // this check is important to determine whether these functions
1149
565k
  // can be overloaded.
1150
565k
  CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1151
565k
  CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1152
565k
  if (OldMethod && 
NewMethod467k
&&
1153
565k
      
!OldMethod->isStatic()467k
&&
!NewMethod->isStatic()456k
) {
1154
456k
    if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1155
69
      if (!UseMemberUsingDeclRules &&
1156
69
          (OldMethod->getRefQualifier() == RQ_None ||
1157
69
           
NewMethod->getRefQualifier() == RQ_None68
)) {
1158
11
        // C++0x [over.load]p2:
1159
11
        //   - Member function declarations with the same name and the same
1160
11
        //     parameter-type-list as well as member function template
1161
11
        //     declarations with the same name, the same parameter-type-list, and
1162
11
        //     the same template parameter lists cannot be overloaded if any of
1163
11
        //     them, but not all, have a ref-qualifier (8.3.5).
1164
11
        Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1165
11
          << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1166
11
        Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1167
11
      }
1168
69
      return true;
1169
69
    }
1170
456k
1171
456k
    // We may not have applied the implicit const for a constexpr member
1172
456k
    // function yet (because we haven't yet resolved whether this is a static
1173
456k
    // or non-static member function). Add it now, on the assumption that this
1174
456k
    // is a redeclaration of OldMethod.
1175
456k
    auto OldQuals = OldMethod->getMethodQualifiers();
1176
456k
    auto NewQuals = NewMethod->getMethodQualifiers();
1177
456k
    if (!getLangOpts().CPlusPlus14 && 
NewMethod->isConstexpr()288k
&&
1178
456k
        
!isa<CXXConstructorDecl>(NewMethod)1.88k
)
1179
379
      NewQuals.addConst();
1180
456k
    // We do not allow overloading based off of '__restrict'.
1181
456k
    OldQuals.removeRestrict();
1182
456k
    NewQuals.removeRestrict();
1183
456k
    if (OldQuals != NewQuals)
1184
148k
      return true;
1185
416k
  }
1186
416k
1187
416k
  // Though pass_object_size is placed on parameters and takes an argument, we
1188
416k
  // consider it to be a function-level modifier for the sake of function
1189
416k
  // identity. Either the function has one or more parameters with
1190
416k
  // pass_object_size or it doesn't.
1191
416k
  if (functionHasPassObjectSizeParams(New) !=
1192
416k
      functionHasPassObjectSizeParams(Old))
1193
18
    return true;
1194
416k
1195
416k
  // enable_if attributes are an order-sensitive part of the signature.
1196
416k
  for (specific_attr_iterator<EnableIfAttr>
1197
416k
         NewI = New->specific_attr_begin<EnableIfAttr>(),
1198
416k
         NewE = New->specific_attr_end<EnableIfAttr>(),
1199
416k
         OldI = Old->specific_attr_begin<EnableIfAttr>(),
1200
416k
         OldE = Old->specific_attr_end<EnableIfAttr>();
1201
416k
       NewI != NewE || 
OldI != OldE410k
;
++NewI, ++OldI11
) {
1202
5.79k
    if (NewI == NewE || 
OldI == OldE5.78k
)
1203
5.74k
      return true;
1204
46
    llvm::FoldingSetNodeID NewID, OldID;
1205
46
    NewI->getCond()->Profile(NewID, Context, true);
1206
46
    OldI->getCond()->Profile(OldID, Context, true);
1207
46
    if (NewID != OldID)
1208
35
      return true;
1209
46
  }
1210
416k
1211
416k
  
if (410k
getLangOpts().CUDA410k
&&
ConsiderCudaAttrs368
) {
1212
336
    // Don't allow overloading of destructors.  (In theory we could, but it
1213
336
    // would be a giant change to clang.)
1214
336
    if (isa<CXXDestructorDecl>(New))
1215
12
      return false;
1216
324
1217
324
    CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1218
324
                       OldTarget = IdentifyCUDATarget(Old);
1219
324
    if (NewTarget == CFT_InvalidTarget)
1220
0
      return false;
1221
324
1222
324
    assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1223
324
1224
324
    // Allow overloading of functions with same signature and different CUDA
1225
324
    // target attributes.
1226
324
    return NewTarget != OldTarget;
1227
324
  }
1228
410k
1229
410k
  // The signatures match; this is not an overload.
1230
410k
  return false;
1231
410k
}
1232
1233
/// Tries a user-defined conversion from From to ToType.
1234
///
1235
/// Produces an implicit conversion sequence for when a standard conversion
1236
/// is not an option. See TryImplicitConversion for more information.
1237
static ImplicitConversionSequence
1238
TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1239
                         bool SuppressUserConversions,
1240
                         bool AllowExplicit,
1241
                         bool InOverloadResolution,
1242
                         bool CStyle,
1243
                         bool AllowObjCWritebackConversion,
1244
2.63M
                         bool AllowObjCConversionOnExplicit) {
1245
2.63M
  ImplicitConversionSequence ICS;
1246
2.63M
1247
2.63M
  if (SuppressUserConversions) {
1248
938k
    // We're not in the case above, so there is no conversion that
1249
938k
    // we can perform.
1250
938k
    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1251
938k
    return ICS;
1252
938k
  }
1253
1.69M
1254
1.69M
  // Attempt user-defined conversion.
1255
1.69M
  OverloadCandidateSet Conversions(From->getExprLoc(),
1256
1.69M
                                   OverloadCandidateSet::CSK_Normal);
1257
1.69M
  switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1258
1.69M
                                  Conversions, AllowExplicit,
1259
1.69M
                                  AllowObjCConversionOnExplicit)) {
1260
1.69M
  case OR_Success:
1261
325k
  case OR_Deleted:
1262
325k
    ICS.setUserDefined();
1263
325k
    // C++ [over.ics.user]p4:
1264
325k
    //   A conversion of an expression of class type to the same class
1265
325k
    //   type is given Exact Match rank, and a conversion of an
1266
325k
    //   expression of class type to a base class of that type is
1267
325k
    //   given Conversion rank, in spite of the fact that a copy
1268
325k
    //   constructor (i.e., a user-defined conversion function) is
1269
325k
    //   called for those cases.
1270
325k
    if (CXXConstructorDecl *Constructor
1271
36.5k
          = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1272
36.5k
      QualType FromCanon
1273
36.5k
        = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1274
36.5k
      QualType ToCanon
1275
36.5k
        = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1276
36.5k
      if (Constructor->isCopyConstructor() &&
1277
36.5k
          
(0
FromCanon == ToCanon0
||
1278
0
           S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1279
0
        // Turn this into a "standard" conversion sequence, so that it
1280
0
        // gets ranked with standard conversion sequences.
1281
0
        DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1282
0
        ICS.setStandard();
1283
0
        ICS.Standard.setAsIdentityConversion();
1284
0
        ICS.Standard.setFromType(From->getType());
1285
0
        ICS.Standard.setAllToTypes(ToType);
1286
0
        ICS.Standard.CopyConstructor = Constructor;
1287
0
        ICS.Standard.FoundCopyConstructor = Found;
1288
0
        if (ToCanon != FromCanon)
1289
0
          ICS.Standard.Second = ICK_Derived_To_Base;
1290
0
      }
1291
36.5k
    }
1292
325k
    break;
1293
325k
1294
325k
  case OR_Ambiguous:
1295
251
    ICS.setAmbiguous();
1296
251
    ICS.Ambiguous.setFromType(From->getType());
1297
251
    ICS.Ambiguous.setToType(ToType);
1298
251
    for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1299
1.00k
         Cand != Conversions.end(); 
++Cand752
)
1300
752
      if (Cand->Viable)
1301
530
        ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1302
251
    break;
1303
325k
1304
325k
    // Fall through.
1305
1.36M
  case OR_No_Viable_Function:
1306
1.36M
    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1307
1.36M
    break;
1308
1.69M
  }
1309
1.69M
1310
1.69M
  return ICS;
1311
1.69M
}
1312
1313
/// TryImplicitConversion - Attempt to perform an implicit conversion
1314
/// from the given expression (Expr) to the given type (ToType). This
1315
/// function returns an implicit conversion sequence that can be used
1316
/// to perform the initialization. Given
1317
///
1318
///   void f(float f);
1319
///   void g(int i) { f(i); }
1320
///
1321
/// this routine would produce an implicit conversion sequence to
1322
/// describe the initialization of f from i, which will be a standard
1323
/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1324
/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1325
//
1326
/// Note that this routine only determines how the conversion can be
1327
/// performed; it does not actually perform the conversion. As such,
1328
/// it will not produce any diagnostics if no conversion is available,
1329
/// but will instead return an implicit conversion sequence of kind
1330
/// "BadConversion".
1331
///
1332
/// If @p SuppressUserConversions, then user-defined conversions are
1333
/// not permitted.
1334
/// If @p AllowExplicit, then explicit user-defined conversions are
1335
/// permitted.
1336
///
1337
/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1338
/// writeback conversion, which allows __autoreleasing id* parameters to
1339
/// be initialized with __strong id* or __weak id* arguments.
1340
static ImplicitConversionSequence
1341
TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1342
                      bool SuppressUserConversions,
1343
                      bool AllowExplicit,
1344
                      bool InOverloadResolution,
1345
                      bool CStyle,
1346
                      bool AllowObjCWritebackConversion,
1347
36.9M
                      bool AllowObjCConversionOnExplicit) {
1348
36.9M
  ImplicitConversionSequence ICS;
1349
36.9M
  if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1350
36.9M
                           ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1351
34.2M
    ICS.setStandard();
1352
34.2M
    return ICS;
1353
34.2M
  }
1354
2.75M
1355
2.75M
  if (!S.getLangOpts().CPlusPlus) {
1356
75.5k
    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1357
75.5k
    return ICS;
1358
75.5k
  }
1359
2.67M
1360
2.67M
  // C++ [over.ics.user]p4:
1361
2.67M
  //   A conversion of an expression of class type to the same class
1362
2.67M
  //   type is given Exact Match rank, and a conversion of an
1363
2.67M
  //   expression of class type to a base class of that type is
1364
2.67M
  //   given Conversion rank, in spite of the fact that a copy/move
1365
2.67M
  //   constructor (i.e., a user-defined conversion function) is
1366
2.67M
  //   called for those cases.
1367
2.67M
  QualType FromType = From->getType();
1368
2.67M
  if (ToType->getAs<RecordType>() && 
FromType->getAs<RecordType>()370k
&&
1369
2.67M
      
(201k
S.Context.hasSameUnqualifiedType(FromType, ToType)201k
||
1370
201k
       
S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType)163k
)) {
1371
43.7k
    ICS.setStandard();
1372
43.7k
    ICS.Standard.setAsIdentityConversion();
1373
43.7k
    ICS.Standard.setFromType(FromType);
1374
43.7k
    ICS.Standard.setAllToTypes(ToType);
1375
43.7k
1376
43.7k
    // We don't actually check at this point whether there is a valid
1377
43.7k
    // copy/move constructor, since overloading just assumes that it
1378
43.7k
    // exists. When we actually perform initialization, we'll find the
1379
43.7k
    // appropriate constructor to copy the returned object, if needed.
1380
43.7k
    ICS.Standard.CopyConstructor = nullptr;
1381
43.7k
1382
43.7k
    // Determine whether this is considered a derived-to-base conversion.
1383
43.7k
    if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1384
5.80k
      ICS.Standard.Second = ICK_Derived_To_Base;
1385
43.7k
1386
43.7k
    return ICS;
1387
43.7k
  }
1388
2.63M
1389
2.63M
  return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1390
2.63M
                                  AllowExplicit, InOverloadResolution, CStyle,
1391
2.63M
                                  AllowObjCWritebackConversion,
1392
2.63M
                                  AllowObjCConversionOnExplicit);
1393
2.63M
}
1394
1395
ImplicitConversionSequence
1396
Sema::TryImplicitConversion(Expr *From, QualType ToType,
1397
                            bool SuppressUserConversions,
1398
                            bool AllowExplicit,
1399
                            bool InOverloadResolution,
1400
                            bool CStyle,
1401
7.01M
                            bool AllowObjCWritebackConversion) {
1402
7.01M
  return ::TryImplicitConversion(*this, From, ToType,
1403
7.01M
                                 SuppressUserConversions, AllowExplicit,
1404
7.01M
                                 InOverloadResolution, CStyle,
1405
7.01M
                                 AllowObjCWritebackConversion,
1406
7.01M
                                 /*AllowObjCConversionOnExplicit=*/false);
1407
7.01M
}
1408
1409
/// PerformImplicitConversion - Perform an implicit conversion of the
1410
/// expression From to the type ToType. Returns the
1411
/// converted expression. Flavor is the kind of conversion we're
1412
/// performing, used in the error message. If @p AllowExplicit,
1413
/// explicit user-defined conversions are permitted.
1414
ExprResult
1415
Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1416
1.67M
                                AssignmentAction Action, bool AllowExplicit) {
1417
1.67M
  ImplicitConversionSequence ICS;
1418
1.67M
  return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1419
1.67M
}
1420
1421
ExprResult
1422
Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1423
                                AssignmentAction Action, bool AllowExplicit,
1424
1.67M
                                ImplicitConversionSequence& ICS) {
1425
1.67M
  if (checkPlaceholderForOverload(*this, From))
1426
0
    return ExprError();
1427
1.67M
1428
1.67M
  // Objective-C ARC: Determine whether we will allow the writeback conversion.
1429
1.67M
  bool AllowObjCWritebackConversion
1430
1.67M
    = getLangOpts().ObjCAutoRefCount &&
1431
1.67M
      
(538
Action == AA_Passing538
||
Action == AA_Sending538
);
1432
1.67M
  if (getLangOpts().ObjC)
1433
1.65k
    CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1434
1.65k
                                      From->getType(), From);
1435
1.67M
  ICS = ::TryImplicitConversion(*this, From, ToType,
1436
1.67M
                                /*SuppressUserConversions=*/false,
1437
1.67M
                                AllowExplicit,
1438
1.67M
                                /*InOverloadResolution=*/false,
1439
1.67M
                                /*CStyle=*/false,
1440
1.67M
                                AllowObjCWritebackConversion,
1441
1.67M
                                /*AllowObjCConversionOnExplicit=*/false);
1442
1.67M
  return PerformImplicitConversion(From, ToType, ICS, Action);
1443
1.67M
}
1444
1445
/// Determine whether the conversion from FromType to ToType is a valid
1446
/// conversion that strips "noexcept" or "noreturn" off the nested function
1447
/// type.
1448
bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1449
35.5M
                                QualType &ResultTy) {
1450
35.5M
  if (Context.hasSameUnqualifiedType(FromType, ToType))
1451
33.8M
    return false;
1452
1.67M
1453
1.67M
  // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1454
1.67M
  //                    or F(t noexcept) -> F(t)
1455
1.67M
  // where F adds one of the following at most once:
1456
1.67M
  //   - a pointer
1457
1.67M
  //   - a member pointer
1458
1.67M
  //   - a block pointer
1459
1.67M
  // Changes here need matching changes in FindCompositePointerType.
1460
1.67M
  CanQualType CanTo = Context.getCanonicalType(ToType);
1461
1.67M
  CanQualType CanFrom = Context.getCanonicalType(FromType);
1462
1.67M
  Type::TypeClass TyClass = CanTo->getTypeClass();
1463
1.67M
  if (TyClass != CanFrom->getTypeClass()) 
return false993k
;
1464
684k
  if (TyClass != Type::FunctionProto && 
TyClass != Type::FunctionNoProto681k
) {
1465
681k
    if (TyClass == Type::Pointer) {
1466
593k
      CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1467
593k
      CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1468
593k
    } else 
if (88.3k
TyClass == Type::BlockPointer88.3k
) {
1469
12
      CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1470
12
      CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1471
88.3k
    } else if (TyClass == Type::MemberPointer) {
1472
779
      auto ToMPT = CanTo.getAs<MemberPointerType>();
1473
779
      auto FromMPT = CanFrom.getAs<MemberPointerType>();
1474
779
      // A function pointer conversion cannot change the class of the function.
1475
779
      if (ToMPT->getClass() != FromMPT->getClass())
1476
219
        return false;
1477
560
      CanTo = ToMPT->getPointeeType();
1478
560
      CanFrom = FromMPT->getPointeeType();
1479
87.5k
    } else {
1480
87.5k
      return false;
1481
87.5k
    }
1482
593k
1483
593k
    TyClass = CanTo->getTypeClass();
1484
593k
    if (TyClass != CanFrom->getTypeClass()) 
return false151k
;
1485
442k
    if (TyClass != Type::FunctionProto && 
TyClass != Type::FunctionNoProto441k
)
1486
441k
      return false;
1487
4.52k
  }
1488
4.52k
1489
4.52k
  const auto *FromFn = cast<FunctionType>(CanFrom);
1490
4.52k
  FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1491
4.52k
1492
4.52k
  const auto *ToFn = cast<FunctionType>(CanTo);
1493
4.52k
  FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1494
4.52k
1495
4.52k
  bool Changed = false;
1496
4.52k
1497
4.52k
  // Drop 'noreturn' if not present in target type.
1498
4.52k
  if (FromEInfo.getNoReturn() && 
!ToEInfo.getNoReturn()126
) {
1499
117
    FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1500
117
    Changed = true;
1501
117
  }
1502
4.52k
1503
4.52k
  // Drop 'noexcept' if not present in target type.
1504
4.52k
  if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1505
4.52k
    const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1506
4.52k
    if (FromFPT->isNothrow() && 
!ToFPT->isNothrow()715
) {
1507
715
      FromFn = cast<FunctionType>(
1508
715
          Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1509
715
                                                   EST_None)
1510
715
                 .getTypePtr());
1511
715
      Changed = true;
1512
715
    }
1513
4.52k
1514
4.52k
    // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1515
4.52k
    // only if the ExtParameterInfo lists of the two function prototypes can be
1516
4.52k
    // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1517
4.52k
    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1518
4.52k
    bool CanUseToFPT, CanUseFromFPT;
1519
4.52k
    if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1520
4.52k
                                      CanUseFromFPT, NewParamInfos) &&
1521
4.52k
        
CanUseToFPT4.48k
&&
!CanUseFromFPT4.47k
) {
1522
6
      FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1523
6
      ExtInfo.ExtParameterInfos =
1524
6
          NewParamInfos.empty() ? nullptr : 
NewParamInfos.data()0
;
1525
6
      QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1526
6
                                            FromFPT->getParamTypes(), ExtInfo);
1527
6
      FromFn = QT->getAs<FunctionType>();
1528
6
      Changed = true;
1529
6
    }
1530
4.52k
  }
1531
4.52k
1532
4.52k
  if (!Changed)
1533
3.68k
    return false;
1534
838
1535
838
  assert(QualType(FromFn, 0).isCanonical());
1536
838
  if (QualType(FromFn, 0) != CanTo) 
return false91
;
1537
747
1538
747
  ResultTy = ToType;
1539
747
  return true;
1540
747
}
1541
1542
/// Determine whether the conversion from FromType to ToType is a valid
1543
/// vector conversion.
1544
///
1545
/// \param ICK Will be set to the vector conversion kind, if this is a vector
1546
/// conversion.
1547
static bool IsVectorConversion(Sema &S, QualType FromType,
1548
2.51M
                               QualType ToType, ImplicitConversionKind &ICK) {
1549
2.51M
  // We need at least one of these types to be a vector type to have a vector
1550
2.51M
  // conversion.
1551
2.51M
  if (!ToType->isVectorType() && 
!FromType->isVectorType()1.56M
)
1552
1.54M
    return false;
1553
970k
1554
970k
  // Identical types require no conversions.
1555
970k
  if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1556
0
    return false;
1557
970k
1558
970k
  // There are no conversions between extended vector types, only identity.
1559
970k
  if (ToType->isExtVectorType()) {
1560
380
    // There are no conversions between extended vector types other than the
1561
380
    // identity conversion.
1562
380
    if (FromType->isExtVectorType())
1563
87
      return false;
1564
293
1565
293
    // Vector splat from any arithmetic type to a vector.
1566
293
    if (FromType->isArithmeticType()) {
1567
247
      ICK = ICK_Vector_Splat;
1568
247
      return true;
1569
247
    }
1570
970k
  }
1571
970k
1572
970k
  // We can perform the conversion between vector types in the following cases:
1573
970k
  // 1)vector types are equivalent AltiVec and GCC vector types
1574
970k
  // 2)lax vector conversions are permitted and the vector types are of the
1575
970k
  //   same size
1576
970k
  if (ToType->isVectorType() && 
FromType->isVectorType()954k
) {
1577
953k
    if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1578
953k
        
S.isLaxVectorConversion(FromType, ToType)915k
) {
1579
867k
      ICK = ICK_Vector_Conversion;
1580
867k
      return true;
1581
867k
    }
1582
103k
  }
1583
103k
1584
103k
  return false;
1585
103k
}
1586
1587
static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1588
                                bool InOverloadResolution,
1589
                                StandardConversionSequence &SCS,
1590
                                bool CStyle);
1591
1592
/// IsStandardConversion - Determines whether there is a standard
1593
/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1594
/// expression From to the type ToType. Standard conversion sequences
1595
/// only consider non-class types; for conversions that involve class
1596
/// types, use TryImplicitConversion. If a conversion exists, SCS will
1597
/// contain the standard conversion sequence required to perform this
1598
/// conversion and this routine will return true. Otherwise, this
1599
/// routine will return false and the value of SCS is unspecified.
1600
static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1601
                                 bool InOverloadResolution,
1602
                                 StandardConversionSequence &SCS,
1603
                                 bool CStyle,
1604
36.9M
                                 bool AllowObjCWritebackConversion) {
1605
36.9M
  QualType FromType = From->getType();
1606
36.9M
1607
36.9M
  // Standard conversions (C++ [conv])
1608
36.9M
  SCS.setAsIdentityConversion();
1609
36.9M
  SCS.IncompatibleObjC = false;
1610
36.9M
  SCS.setFromType(FromType);
1611
36.9M
  SCS.CopyConstructor = nullptr;
1612
36.9M
1613
36.9M
  // There are no standard conversions for class types in C++, so
1614
36.9M
  // abort early. When overloading in C, however, we do permit them.
1615
36.9M
  if (S.getLangOpts().CPlusPlus &&
1616
36.9M
      
(35.3M
FromType->isRecordType()35.3M
||
ToType->isRecordType()33.9M
))
1617
1.50M
    return false;
1618
35.4M
1619
35.4M
  // The first conversion can be an lvalue-to-rvalue conversion,
1620
35.4M
  // array-to-pointer conversion, or function-to-pointer conversion
1621
35.4M
  // (C++ 4p1).
1622
35.4M
1623
35.4M
  if (FromType == S.Context.OverloadTy) {
1624
40.5k
    DeclAccessPair AccessPair;
1625
40.5k
    if (FunctionDecl *Fn
1626
3.78k
          = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1627
3.78k
                                                 AccessPair)) {
1628
3.78k
      // We were able to resolve the address of the overloaded function,
1629
3.78k
      // so we can convert to the type of that function.
1630
3.78k
      FromType = Fn->getType();
1631
3.78k
      SCS.setFromType(FromType);
1632
3.78k
1633
3.78k
      // we can sometimes resolve &foo<int> regardless of ToType, so check
1634
3.78k
      // if the type matches (identity) or we are converting to bool
1635
3.78k
      if (!S.Context.hasSameUnqualifiedType(
1636
3.78k
                      S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1637
109
        QualType resultTy;
1638
109
        // if the function type matches except for [[noreturn]], it's ok
1639
109
        if (!S.IsFunctionConversion(FromType,
1640
109
              S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1641
38
          // otherwise, only a boolean conversion is standard
1642
38
          if (!ToType->isBooleanType())
1643
18
            return false;
1644
3.76k
      }
1645
3.76k
1646
3.76k
      // Check if the "from" expression is taking the address of an overloaded
1647
3.76k
      // function and recompute the FromType accordingly. Take advantage of the
1648
3.76k
      // fact that non-static member functions *must* have such an address-of
1649
3.76k
      // expression.
1650
3.76k
      CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1651
3.76k
      if (Method && 
!Method->isStatic()270
) {
1652
150
        assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1653
150
               "Non-unary operator on non-static member address");
1654
150
        assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1655
150
               == UO_AddrOf &&
1656
150
               "Non-address-of operator on non-static member address");
1657
150
        const Type *ClassType
1658
150
          = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1659
150
        FromType = S.Context.getMemberPointerType(FromType, ClassType);
1660
3.61k
      } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1661
359
        assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1662
359
               UO_AddrOf &&
1663
359
               "Non-address-of operator for overloaded function expression");
1664
359
        FromType = S.Context.getPointerType(FromType);
1665
359
      }
1666
3.76k
1667
3.76k
      // Check that we've computed the proper type after overload resolution.
1668
3.76k
      // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1669
3.76k
      // be calling it from within an NDEBUG block.
1670
3.76k
      assert(S.Context.hasSameType(
1671
3.76k
        FromType,
1672
3.76k
        S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1673
36.7k
    } else {
1674
36.7k
      return false;
1675
36.7k
    }
1676
35.4M
  }
1677
35.4M
  // Lvalue-to-rvalue conversion (C++11 4.1):
1678
35.4M
  //   A glvalue (3.10) of a non-function, non-array type T can
1679
35.4M
  //   be converted to a prvalue.
1680
35.4M
  bool argIsLValue = From->isGLValue();
1681
35.4M
  if (argIsLValue &&
1682
35.4M
      
!FromType->isFunctionType()13.0M
&&
!FromType->isArrayType()13.0M
&&
1683
35.4M
      
S.Context.getCanonicalType(FromType) != S.Context.OverloadTy12.5M
) {
1684
12.5M
    SCS.First = ICK_Lvalue_To_Rvalue;
1685
12.5M
1686
12.5M
    // C11 6.3.2.1p2:
1687
12.5M
    //   ... if the lvalue has atomic type, the value has the non-atomic version
1688
12.5M
    //   of the type of the lvalue ...
1689
12.5M
    if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1690
80
      FromType = Atomic->getValueType();
1691
12.5M
1692
12.5M
    // If T is a non-class type, the type of the rvalue is the
1693
12.5M
    // cv-unqualified version of T. Otherwise, the type of the rvalue
1694
12.5M
    // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1695
12.5M
    // just strip the qualifiers because they don't matter.
1696
12.5M
    FromType = FromType.getUnqualifiedType();
1697
22.8M
  } else if (FromType->isArrayType()) {
1698
544k
    // Array-to-pointer conversion (C++ 4.2)
1699
544k
    SCS.First = ICK_Array_To_Pointer;
1700
544k
1701
544k
    // An lvalue or rvalue of type "array of N T" or "array of unknown
1702
544k
    // bound of T" can be converted to an rvalue of type "pointer to
1703
544k
    // T" (C++ 4.2p1).
1704
544k
    FromType = S.Context.getArrayDecayedType(FromType);
1705
544k
1706
544k
    if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1707
1.13k
      // This conversion is deprecated in C++03 (D.4)
1708
1.13k
      SCS.DeprecatedStringLiteralToCharPtr = true;
1709
1.13k
1710
1.13k
      // For the purpose of ranking in overload resolution
1711
1.13k
      // (13.3.3.1.1), this conversion is considered an
1712
1.13k
      // array-to-pointer conversion followed by a qualification
1713
1.13k
      // conversion (4.4). (C++ 4.2p2)
1714
1.13k
      SCS.Second = ICK_Identity;
1715
1.13k
      SCS.Third = ICK_Qualification;
1716
1.13k
      SCS.QualificationIncludesObjCLifetime = false;
1717
1.13k
      SCS.setAllToTypes(FromType);
1718
1.13k
      return true;
1719
1.13k
    }
1720
22.3M
  } else if (FromType->isFunctionType() && 
argIsLValue16.4k
) {
1721
16.4k
    // Function-to-pointer conversion (C++ 4.3).
1722
16.4k
    SCS.First = ICK_Function_To_Pointer;
1723
16.4k
1724
16.4k
    if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1725
13.1k
      if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1726
13.1k
        if (!S.checkAddressOfFunctionIsAvailable(FD))
1727
8
          return false;
1728
16.4k
1729
16.4k
    // An lvalue of function type T can be converted to an rvalue of
1730
16.4k
    // type "pointer to T." The result is a pointer to the
1731
16.4k
    // function. (C++ 4.3p1).
1732
16.4k
    FromType = S.Context.getPointerType(FromType);
1733
22.3M
  } else {
1734
22.3M
    // We don't require any conversions for the first step.
1735
22.3M
    SCS.First = ICK_Identity;
1736
22.3M
  }
1737
35.4M
  SCS.setToType(0, FromType);
1738
35.4M
1739
35.4M
  // The second conversion can be an integral promotion, floating
1740
35.4M
  // point promotion, integral conversion, floating point conversion,
1741
35.4M
  // floating-integral conversion, pointer conversion,
1742
35.4M
  // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1743
35.4M
  // For overloading in C, this can also be a "compatible-type"
1744
35.4M
  // conversion.
1745
35.4M
  bool IncompatibleObjC = false;
1746
35.4M
  ImplicitConversionKind SecondICK = ICK_Identity;
1747
35.4M
  if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1748
12.6M
    // The unqualified versions of the types are the same: there's no
1749
12.6M
    // conversion to do.
1750
12.6M
    SCS.Second = ICK_Identity;
1751
22.7M
  } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1752
1.58M
    // Integral promotion (C++ 4.5).
1753
1.58M
    SCS.Second = ICK_Integral_Promotion;
1754
1.58M
    FromType = ToType.getUnqualifiedType();
1755
21.2M
  } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1756
9.27k
    // Floating point promotion (C++ 4.6).
1757
9.27k
    SCS.Second = ICK_Floating_Promotion;
1758
9.27k
    FromType = ToType.getUnqualifiedType();
1759
21.1M
  } else if (S.IsComplexPromotion(FromType, ToType)) {
1760
30
    // Complex promotion (Clang extension)
1761
30
    SCS.Second = ICK_Complex_Promotion;
1762
30
    FromType = ToType.getUnqualifiedType();
1763
21.1M
  } else if (ToType->isBooleanType() &&
1764
21.1M
             
(281k
FromType->isArithmeticType()281k
||
1765
281k
              
FromType->isAnyPointerType()34.8k
||
1766
281k
              
FromType->isBlockPointerType()830
||
1767
281k
              
FromType->isMemberPointerType()818
||
1768
281k
              
FromType->isNullPtrType()63
)) {
1769
281k
    // Boolean conversions (C++ 4.12).
1770
281k
    SCS.Second = ICK_Boolean_Conversion;
1771
281k
    FromType = S.Context.BoolTy;
1772
20.9M
  } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1773
20.9M
             
ToType->isIntegralType(S.Context)18.0M
) {
1774
13.2M
    // Integral conversions (C++ 4.7).
1775
13.2M
    SCS.Second = ICK_Integral_Conversion;
1776
13.2M
    FromType = ToType.getUnqualifiedType();
1777
13.2M
  } else 
if (7.62M
FromType->isAnyComplexType()7.62M
&&
ToType->isAnyComplexType()440
) {
1778
79
    // Complex conversions (C99 6.3.1.6)
1779
79
    SCS.Second = ICK_Complex_Conversion;
1780
79
    FromType = ToType.getUnqualifiedType();
1781
7.62M
  } else if ((FromType->isAnyComplexType() && 
ToType->isArithmeticType()361
) ||
1782
7.62M
             
(7.62M
ToType->isAnyComplexType()7.62M
&&
FromType->isArithmeticType()265
)) {
1783
610
    // Complex-real conversions (C99 6.3.1.7)
1784
610
    SCS.Second = ICK_Complex_Real;
1785
610
    FromType = ToType.getUnqualifiedType();
1786
7.62M
  } else if (FromType->isRealFloatingType() && 
ToType->isRealFloatingType()198k
) {
1787
110k
    // FIXME: disable conversions between long double and __float128 if
1788
110k
    // their representation is different until there is back end support
1789
110k
    // We of course allow this conversion if long double is really double.
1790
110k
    if (&S.Context.getFloatTypeSemantics(FromType) !=
1791
110k
        &S.Context.getFloatTypeSemantics(ToType)) {
1792
78.2k
      bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1793
78.2k
                                    
ToType == S.Context.LongDoubleTy4
) ||
1794
78.2k
                                   
(78.2k
FromType == S.Context.LongDoubleTy78.2k
&&
1795
78.2k
                                    
ToType == S.Context.Float128Ty222
));
1796
78.2k
      if (Float128AndLongDouble &&
1797
78.2k
          (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1798
8
           &llvm::APFloat::PPCDoubleDouble()))
1799
6
        return false;
1800
110k
    }
1801
110k
    // Floating point conversions (C++ 4.8).
1802
110k
    SCS.Second = ICK_Floating_Conversion;
1803
110k
    FromType = ToType.getUnqualifiedType();
1804
7.51M
  } else if ((FromType->isRealFloatingType() &&
1805
7.51M
              
ToType->isIntegralType(S.Context)87.7k
) ||
1806
7.51M
             
(7.42M
FromType->isIntegralOrUnscopedEnumerationType()7.42M
&&
1807
7.42M
              
ToType->isRealFloatingType()4.71M
)) {
1808
4.67M
    // Floating-integral conversions (C++ 4.9).
1809
4.67M
    SCS.Second = ICK_Floating_Integral;
1810
4.67M
    FromType = ToType.getUnqualifiedType();
1811
4.67M
  } else 
if (2.83M
S.IsBlockPointerConversion(FromType, ToType, FromType)2.83M
) {
1812
8
    SCS.Second = ICK_Block_Pointer_Conversion;
1813
2.83M
  } else if (AllowObjCWritebackConversion &&
1814
2.83M
             
S.isObjCWritebackConversion(FromType, ToType, FromType)392
) {
1815
19
    SCS.Second = ICK_Writeback_Conversion;
1816
2.83M
  } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1817
2.83M
                                   FromType, IncompatibleObjC)) {
1818
314k
    // Pointer conversions (C++ 4.10).
1819
314k
    SCS.Second = ICK_Pointer_Conversion;
1820
314k
    SCS.IncompatibleObjC = IncompatibleObjC;
1821
314k
    FromType = FromType.getUnqualifiedType();
1822
2.51M
  } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1823
2.51M
                                         InOverloadResolution, FromType)) {
1824
1.75k
    // Pointer to member conversions (4.11).
1825
1.75k
    SCS.Second = ICK_Pointer_Member;
1826
2.51M
  } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1827
867k
    SCS.Second = SecondICK;
1828
867k
    FromType = ToType.getUnqualifiedType();
1829
1.65M
  } else if (!S.getLangOpts().CPlusPlus &&
1830
1.65M
             
S.Context.typesAreCompatible(ToType, FromType)321k
) {
1831
6.41k
    // Compatible conversions (Clang extension for C function overloading)
1832
6.41k
    SCS.Second = ICK_Compatible_Conversion;
1833
6.41k
    FromType = ToType.getUnqualifiedType();
1834
1.64M
  } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1835
1.64M
                                             InOverloadResolution,
1836
1.64M
                                             SCS, CStyle)) {
1837
1
    SCS.Second = ICK_TransparentUnionConversion;
1838
1
    FromType = ToType;
1839
1.64M
  } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1840
1.64M
                                 CStyle)) {
1841
388
    // tryAtomicConversion has updated the standard conversion sequence
1842
388
    // appropriately.
1843
388
    return true;
1844
1.64M
  } else if (ToType->isEventT() &&
1845
1.64M
             
From->isIntegerConstantExpr(S.getASTContext())2
&&
1846
1.64M
             
From->EvaluateKnownConstInt(S.getASTContext()) == 02
) {
1847
2
    SCS.Second = ICK_Zero_Event_Conversion;
1848
2
    FromType = ToType;
1849
1.64M
  } else if (ToType->isQueueT() &&
1850
1.64M
             
From->isIntegerConstantExpr(S.getASTContext())4
&&
1851
1.64M
             
(From->EvaluateKnownConstInt(S.getASTContext()) == 0)4
) {
1852
2
    SCS.Second = ICK_Zero_Queue_Conversion;
1853
2
    FromType = ToType;
1854
1.64M
  } else if (ToType->isSamplerT() &&
1855
1.64M
             
From->isIntegerConstantExpr(S.getASTContext())1
) {
1856
1
    SCS.Second = ICK_Compatible_Conversion;
1857
1
    FromType = ToType;
1858
1.64M
  } else {
1859
1.64M
    // No second conversion required.
1860
1.64M
    SCS.Second = ICK_Identity;
1861
1.64M
  }
1862
35.4M
  SCS.setToType(1, FromType);
1863
35.4M
1864
35.4M
  // The third conversion can be a function pointer conversion or a
1865
35.4M
  // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1866
35.4M
  bool ObjCLifetimeConversion;
1867
35.4M
  if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1868
172
    // Function pointer conversions (removing 'noexcept') including removal of
1869
172
    // 'noreturn' (Clang extension).
1870
172
    SCS.Third = ICK_Function_Conversion;
1871
35.4M
  } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1872
35.4M
                                         ObjCLifetimeConversion)) {
1873
222k
    SCS.Third = ICK_Qualification;
1874
222k
    SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1875
222k
    FromType = ToType;
1876
35.1M
  } else {
1877
35.1M
    // No conversion required
1878
35.1M
    SCS.Third = ICK_Identity;
1879
35.1M
  }
1880
35.4M
1881
35.4M
  // C++ [over.best.ics]p6:
1882
35.4M
  //   [...] Any difference in top-level cv-qualification is
1883
35.4M
  //   subsumed by the initialization itself and does not constitute
1884
35.4M
  //   a conversion. [...]
1885
35.4M
  QualType CanonFrom = S.Context.getCanonicalType(FromType);
1886
35.4M
  QualType CanonTo = S.Context.getCanonicalType(ToType);
1887
35.4M
  if (CanonFrom.getLocalUnqualifiedType()
1888
35.4M
                                     == CanonTo.getLocalUnqualifiedType() &&
1889
35.4M
      
CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()33.9M
) {
1890
678k
    FromType = ToType;
1891
678k
    CanonFrom = CanonTo;
1892
678k
  }
1893
35.4M
1894
35.4M
  SCS.setToType(2, FromType);
1895
35.4M
1896
35.4M
  if (CanonFrom == CanonTo)
1897
33.9M
    return true;
1898
1.44M
1899
1.44M
  // If we have not converted the argument type to the parameter type,
1900
1.44M
  // this is a bad conversion sequence, unless we're resolving an overload in C.
1901
1.44M
  if (S.getLangOpts().CPlusPlus || 
!InOverloadResolution306k
)
1902
1.13M
    return false;
1903
306k
1904
306k
  ExprResult ER = ExprResult{From};
1905
306k
  Sema::AssignConvertType Conv =
1906
306k
      S.CheckSingleAssignmentConstraints(ToType, ER,
1907
306k
                                         /*Diagnose=*/false,
1908
306k
                                         /*DiagnoseCFAudited=*/false,
1909
306k
                                         /*ConvertRHS=*/false);
1910
306k
  ImplicitConversionKind SecondConv;
1911
306k
  switch (Conv) {
1912
306k
  case Sema::Compatible:
1913
1.97k
    SecondConv = ICK_C_Only_Conversion;
1914
1.97k
    break;
1915
306k
  // For our purposes, discarding qualifiers is just as bad as using an
1916
306k
  // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1917
306k
  // qualifiers, as well.
1918
306k
  case Sema::CompatiblePointerDiscardsQualifiers:
1919
229k
  case Sema::IncompatiblePointer:
1920
229k
  case Sema::IncompatiblePointerSign:
1921
229k
    SecondConv = ICK_Incompatible_Pointer_Conversion;
1922
229k
    break;
1923
229k
  default:
1924
75.5k
    return false;
1925
231k
  }
1926
231k
1927
231k
  // First can only be an lvalue conversion, so we pretend that this was the
1928
231k
  // second conversion. First should already be valid from earlier in the
1929
231k
  // function.
1930
231k
  SCS.Second = SecondConv;
1931
231k
  SCS.setToType(1, ToType);
1932
231k
1933
231k
  // Third is Identity, because Second should rank us worse than any other
1934
231k
  // conversion. This could also be ICK_Qualification, but it's simpler to just
1935
231k
  // lump everything in with the second conversion, and we don't gain anything
1936
231k
  // from making this ICK_Qualification.
1937
231k
  SCS.Third = ICK_Identity;
1938
231k
  SCS.setToType(2, ToType);
1939
231k
  return true;
1940
231k
}
1941
1942
static bool
1943
IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1944
                                     QualType &ToType,
1945
                                     bool InOverloadResolution,
1946
                                     StandardConversionSequence &SCS,
1947
1.64M
                                     bool CStyle) {
1948
1.64M
1949
1.64M
  const RecordType *UT = ToType->getAsUnionType();
1950
1.64M
  if (!UT || 
!UT->getDecl()->hasAttr<TransparentUnionAttr>()1
)
1951
1.64M
    return false;
1952
1
  // The field to initialize within the transparent union.
1953
1
  RecordDecl *UD = UT->getDecl();
1954
1
  // It's compatible if the expression matches any of the fields.
1955
1
  for (const auto *it : UD->fields()) {
1956
1
    if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1957
1
                             CStyle, /*AllowObjCWritebackConversion=*/false)) {
1958
1
      ToType = it->getType();
1959
1
      return true;
1960
1
    }
1961
1
  }
1962
1
  
return false0
;
1963
1
}
1964
1965
/// IsIntegralPromotion - Determines whether the conversion from the
1966
/// expression From (whose potentially-adjusted type is FromType) to
1967
/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1968
/// sets PromotedType to the promoted type.
1969
22.8M
bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1970
22.8M
  const BuiltinType *To = ToType->getAs<BuiltinType>();
1971
22.8M
  // All integers are built-in.
1972
22.8M
  if (!To) {
1973
1.89M
    return false;
1974
1.89M
  }
1975
21.0M
1976
21.0M
  // An rvalue of type char, signed char, unsigned char, short int, or
1977
21.0M
  // unsigned short int can be converted to an rvalue of type int if
1978
21.0M
  // int can represent all the values of the source type; otherwise,
1979
21.0M
  // the source rvalue can be converted to an rvalue of type unsigned
1980
21.0M
  // int (C++ 4.5p1).
1981
21.0M
  if (FromType->isPromotableIntegerType() && 
!FromType->isBooleanType()15.5M
&&
1982
21.0M
      
!FromType->isEnumeralType()15.3M
) {
1983
151k
    if (// We can promote any signed, promotable integer type to an int
1984
151k
        (FromType->isSignedIntegerType() ||
1985
151k
         // We can promote any unsigned integer type whose size is
1986
151k
         // less than int to an int.
1987
151k
         
Context.getTypeSize(FromType) < Context.getTypeSize(ToType)63.7k
)) {
1988
147k
      return To->getKind() == BuiltinType::Int;
1989
147k
    }
1990
3.25k
1991
3.25k
    return To->getKind() == BuiltinType::UInt;
1992
3.25k
  }
1993
20.8M
1994
20.8M
  // C++11 [conv.prom]p3:
1995
20.8M
  //   A prvalue of an unscoped enumeration type whose underlying type is not
1996
20.8M
  //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1997
20.8M
  //   following types that can represent all the values of the enumeration
1998
20.8M
  //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1999
20.8M
  //   unsigned int, long int, unsigned long int, long long int, or unsigned
2000
20.8M
  //   long long int. If none of the types in that list can represent all the
2001
20.8M
  //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2002
20.8M
  //   type can be converted to an rvalue a prvalue of the extended integer type
2003
20.8M
  //   with lowest integer conversion rank (4.13) greater than the rank of long
2004
20.8M
  //   long in which all the values of the enumeration can be represented. If
2005
20.8M
  //   there are two such extended types, the signed one is chosen.
2006
20.8M
  // C++11 [conv.prom]p4:
2007
20.8M
  //   A prvalue of an unscoped enumeration type whose underlying type is fixed
2008
20.8M
  //   can be converted to a prvalue of its underlying type. Moreover, if
2009
20.8M
  //   integral promotion can be applied to its underlying type, a prvalue of an
2010
20.8M
  //   unscoped enumeration type whose underlying type is fixed can also be
2011
20.8M
  //   converted to a prvalue of the promoted underlying type.
2012
20.8M
  if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2013
15.4M
    // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2014
15.4M
    // provided for a scoped enumeration.
2015
15.4M
    if (FromEnumType->getDecl()->isScoped())
2016
249k
      return false;
2017
15.1M
2018
15.1M
    // We can perform an integral promotion to the underlying type of the enum,
2019
15.1M
    // even if that's not the promoted type. Note that the check for promoting
2020
15.1M
    // the underlying type is based on the type alone, and does not consider
2021
15.1M
    // the bitfield-ness of the actual source expression.
2022
15.1M
    if (FromEnumType->getDecl()->isFixed()) {
2023
105k
      QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2024
105k
      return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2025
105k
             
IsIntegralPromotion(nullptr, Underlying, ToType)96.3k
;
2026
105k
    }
2027
15.0M
2028
15.0M
    // We have already pre-calculated the promotion type, so this is trivial.
2029
15.0M
    if (ToType->isIntegerType() &&
2030
15.0M
        
isCompleteType(From->getBeginLoc(), FromType)11.1M
)
2031
11.1M
      return Context.hasSameUnqualifiedType(
2032
11.1M
          ToType, FromEnumType->getDecl()->getPromotionType());
2033
3.92M
2034
3.92M
    // C++ [conv.prom]p5:
2035
3.92M
    //   If the bit-field has an enumerated type, it is treated as any other
2036
3.92M
    //   value of that type for promotion purposes.
2037
3.92M
    //
2038
3.92M
    // ... so do not fall through into the bit-field checks below in C++.
2039
3.92M
    if (getLangOpts().CPlusPlus)
2040
3.92M
      return false;
2041
5.45M
  }
2042
5.45M
2043
5.45M
  // C++0x [conv.prom]p2:
2044
5.45M
  //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2045
5.45M
  //   to an rvalue a prvalue of the first of the following types that can
2046
5.45M
  //   represent all the values of its underlying type: int, unsigned int,
2047
5.45M
  //   long int, unsigned long int, long long int, or unsigned long long int.
2048
5.45M
  //   If none of the types in that list can represent all the values of its
2049
5.45M
  //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2050
5.45M
  //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2051
5.45M
  //   type.
2052
5.45M
  if (FromType->isAnyCharacterType() && 
!FromType->isCharType()0
&&
2053
5.45M
      
ToType->isIntegerType()0
) {
2054
0
    // Determine whether the type we're converting from is signed or
2055
0
    // unsigned.
2056
0
    bool FromIsSigned = FromType->isSignedIntegerType();
2057
0
    uint64_t FromSize = Context.getTypeSize(FromType);
2058
0
2059
0
    // The types we'll try to promote to, in the appropriate
2060
0
    // order. Try each of these types.
2061
0
    QualType PromoteTypes[6] = {
2062
0
      Context.IntTy, Context.UnsignedIntTy,
2063
0
      Context.LongTy, Context.UnsignedLongTy ,
2064
0
      Context.LongLongTy, Context.UnsignedLongLongTy
2065
0
    };
2066
0
    for (int Idx = 0; Idx < 6; ++Idx) {
2067
0
      uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2068
0
      if (FromSize < ToSize ||
2069
0
          (FromSize == ToSize &&
2070
0
           FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2071
0
        // We found the type that we can promote to. If this is the
2072
0
        // type we wanted, we have a promotion. Otherwise, no
2073
0
        // promotion.
2074
0
        return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2075
0
      }
2076
0
    }
2077
0
  }
2078
5.45M
2079
5.45M
  // An rvalue for an integral bit-field (9.6) can be converted to an
2080
5.45M
  // rvalue of type int if int can represent all the values of the
2081
5.45M
  // bit-field; otherwise, it can be converted to unsigned int if
2082
5.45M
  // unsigned int can represent all the values of the bit-field. If
2083
5.45M
  // the bit-field is larger yet, no integral promotion applies to
2084
5.45M
  // it. If the bit-field has an enumerated type, it is treated as any
2085
5.45M
  // other value of that type for promotion purposes (C++ 4.5p3).
2086
5.45M
  // FIXME: We should delay checking of bit-fields until we actually perform the
2087
5.45M
  // conversion.
2088
5.45M
  //
2089
5.45M
  // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2090
5.45M
  // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2091
5.45M
  // bit-fields and those whose underlying type is larger than int) for GCC
2092
5.45M
  // compatibility.
2093
5.45M
  if (From) {
2094
5.37M
    if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2095
11.9k
      llvm::APSInt BitWidth;
2096
11.9k
      if (FromType->isIntegralType(Context) &&
2097
11.9k
          MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2098
11.9k
        llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2099
11.9k
        ToSize = Context.getTypeSize(ToType);
2100
11.9k
2101
11.9k
        // Are we promoting to an int from a bitfield that fits in an int?
2102
11.9k
        if (BitWidth < ToSize ||
2103
11.9k
            
(42
FromType->isSignedIntegerType()42
&&
BitWidth <= ToSize0
)) {
2104
11.8k
          return To->getKind() == BuiltinType::Int;
2105
11.8k
        }
2106
42
2107
42
        // Are we promoting to an unsigned int from an unsigned bitfield
2108
42
        // that fits into an unsigned int?
2109
42
        if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2110
10
          return To->getKind() == BuiltinType::UInt;
2111
10
        }
2112
32
2113
32
        return false;
2114
32
      }
2115
11.9k
    }
2116
5.37M
  }
2117
5.44M
2118
5.44M
  // An rvalue of type bool can be converted to an rvalue of type int,
2119
5.44M
  // with false becoming zero and true becoming one (C++ 4.5p4).
2120
5.44M
  if (FromType->isBooleanType() && 
To->getKind() == BuiltinType::Int214k
) {
2121
29.2k
    return true;
2122
29.2k
  }
2123
5.41M
2124
5.41M
  return false;
2125
5.41M
}
2126
2127
/// IsFloatingPointPromotion - Determines whether the conversion from
2128
/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2129
/// returns true and sets PromotedType to the promoted type.
2130
21.2M
bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2131
21.2M
  if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2132
4.93M
    if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2133
4.72M
      /// An rvalue of type float can be converted to an rvalue of type
2134
4.72M
      /// double. (C++ 4.6p1).
2135
4.72M
      if (FromBuiltin->getKind() == BuiltinType::Float &&
2136
4.72M
          
ToBuiltin->getKind() == BuiltinType::Double85.7k
)
2137
9.27k
        return true;
2138
4.71M
2139
4.71M
      // C99 6.3.1.5p1:
2140
4.71M
      //   When a float is promoted to double or long double, or a
2141
4.71M
      //   double is promoted to long double [...].
2142
4.71M
      if (!getLangOpts().CPlusPlus &&
2143
4.71M
          
(31.3k
FromBuiltin->getKind() == BuiltinType::Float31.3k
||
2144
31.3k
           
FromBuiltin->getKind() == BuiltinType::Double31.1k
) &&
2145
4.71M
          
(2.23k
ToBuiltin->getKind() == BuiltinType::LongDouble2.23k
||
2146
2.23k
           
ToBuiltin->getKind() == BuiltinType::Float1282.20k
))
2147
28
        return true;
2148
4.71M
2149
4.71M
      // Half can be promoted to float.
2150
4.71M
      if (!getLangOpts().NativeHalfType &&
2151
4.71M
           
FromBuiltin->getKind() == BuiltinType::Half4.71M
&&
2152
4.71M
          
ToBuiltin->getKind() == BuiltinType::Float4
)
2153
2
        return true;
2154
21.1M
    }
2155
21.1M
2156
21.1M
  return false;
2157
21.1M
}
2158
2159
/// Determine if a conversion is a complex promotion.
2160
///
2161
/// A complex promotion is defined as a complex -> complex conversion
2162
/// where the conversion between the underlying real types is a
2163
/// floating-point or integral promotion.
2164
21.1M
bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2165
21.1M
  const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2166
21.1M
  if (!FromComplex)
2167
21.1M
    return false;
2168
486
2169
486
  const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2170
486
  if (!ToComplex)
2171
377
    return false;
2172
109
2173
109
  return IsFloatingPointPromotion(FromComplex->getElementType(),
2174
109
                                  ToComplex->getElementType()) ||
2175
109
    IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2176
82
                        ToComplex->getElementType());
2177
109
}
2178
2179
/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2180
/// the pointer type FromPtr to a pointer to type ToPointee, with the
2181
/// same type qualifiers as FromPtr has on its pointee type. ToType,
2182
/// if non-empty, will be a pointer to ToType that may or may not have
2183
/// the right set of qualifiers on its pointee.
2184
///
2185
static QualType
2186
BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2187
                                   QualType ToPointee, QualType ToType,
2188
                                   ASTContext &Context,
2189
152k
                                   bool StripObjCLifetime = false) {
2190
152k
  assert((FromPtr->getTypeClass() == Type::Pointer ||
2191
152k
          FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2192
152k
         "Invalid similarly-qualified pointer type");
2193
152k
2194
152k
  /// Conversions to 'id' subsume cv-qualifier conversions.
2195
152k
  if (ToType->isObjCIdType() || 
ToType->isObjCQualifiedIdType()152k
)
2196
818
    return ToType.getUnqualifiedType();
2197
151k
2198
151k
  QualType CanonFromPointee
2199
151k
    = Context.getCanonicalType(FromPtr->getPointeeType());
2200
151k
  QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2201
151k
  Qualifiers Quals = CanonFromPointee.getQualifiers();
2202
151k
2203
151k
  if (StripObjCLifetime)
2204
117k
    Quals.removeObjCLifetime();
2205
151k
2206
151k
  // Exact qualifier match -> return the pointer type we're converting to.
2207
151k
  if (CanonToPointee.getLocalQualifiers() == Quals) {
2208
129k
    // ToType is exactly what we need. Return it.
2209
129k
    if (!ToType.isNull())
2210
129k
      return ToType.getUnqualifiedType();
2211
0
2212
0
    // Build a pointer to ToPointee. It has the right qualifiers
2213
0
    // already.
2214
0
    if (isa<ObjCObjectPointerType>(ToType))
2215
0
      return Context.getObjCObjectPointerType(ToPointee);
2216
0
    return Context.getPointerType(ToPointee);
2217
0
  }
2218
22.2k
2219
22.2k
  // Just build a canonical type that has the right qualifiers.
2220
22.2k
  QualType QualifiedCanonToPointee
2221
22.2k
    = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2222
22.2k
2223
22.2k
  if (isa<ObjCObjectPointerType>(ToType))
2224
35
    return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2225
22.1k
  return Context.getPointerType(QualifiedCanonToPointee);
2226
22.1k
}
2227
2228
static bool isNullPointerConstantForConversion(Expr *Expr,
2229
                                               bool InOverloadResolution,
2230
914k
                                               ASTContext &Context) {
2231
914k
  // Handle value-dependent integral null pointer constants correctly.
2232
914k
  // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2233
914k
  if (Expr->isValueDependent() && 
!Expr->isTypeDependent()48
&&
2234
914k
      
Expr->getType()->isIntegerType()48
&&
!Expr->getType()->isEnumeralType()23
)
2235
23
    return !InOverloadResolution;
2236
914k
2237
914k
  return Expr->isNullPointerConstant(Context,
2238
914k
                    InOverloadResolution? 
Expr::NPC_ValueDependentIsNotNull449k
2239
914k
                                        : 
Expr::NPC_ValueDependentIsNull464k
);
2240
914k
}
2241
2242
/// IsPointerConversion - Determines whether the conversion of the
2243
/// expression From, which has the (possibly adjusted) type FromType,
2244
/// can be converted to the type ToType via a pointer conversion (C++
2245
/// 4.10). If so, returns true and places the converted type (that
2246
/// might differ from ToType in its cv-qualifiers at some level) into
2247
/// ConvertedType.
2248
///
2249
/// This routine also supports conversions to and from block pointers
2250
/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2251
/// pointers to interfaces. FIXME: Once we've determined the
2252
/// appropriate overloading rules for Objective-C, we may want to
2253
/// split the Objective-C checks into a different routine; however,
2254
/// GCC seems to consider all of these conversions to be pointer
2255
/// conversions, so for now they live here. IncompatibleObjC will be
2256
/// set if the conversion is an allowed Objective-C conversion that
2257
/// should result in a warning.
2258
bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2259
                               bool InOverloadResolution,
2260
                               QualType& ConvertedType,
2261
2.83M
                               bool &IncompatibleObjC) {
2262
2.83M
  IncompatibleObjC = false;
2263
2.83M
  if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2264
2.83M
                              IncompatibleObjC))
2265
1.21k
    return true;
2266
2.83M
2267
2.83M
  // Conversion from a null pointer constant to any Objective-C pointer type.
2268
2.83M
  if (ToType->isObjCObjectPointerType() &&
2269
2.83M
      
isNullPointerConstantForConversion(From, InOverloadResolution, Context)627
) {
2270
315
    ConvertedType = ToType;
2271
315
    return true;
2272
315
  }
2273
2.83M
2274
2.83M
  // Blocks: Block pointers can be converted to void*.
2275
2.83M
  if (FromType->isBlockPointerType() && 
ToType->isPointerType()632
&&
2276
2.83M
      
ToType->getAs<PointerType>()->getPointeeType()->isVoidType()619
) {
2277
610
    ConvertedType = ToType;
2278
610
    return true;
2279
610
  }
2280
2.83M
  // Blocks: A null pointer constant can be converted to a block
2281
2.83M
  // pointer type.
2282
2.83M
  if (ToType->isBlockPointerType() &&
2283
2.83M
      
isNullPointerConstantForConversion(From, InOverloadResolution, Context)558
) {
2284
347
    ConvertedType = ToType;
2285
347
    return true;
2286
347
  }
2287
2.83M
2288
2.83M
  // If the left-hand-side is nullptr_t, the right side can be a null
2289
2.83M
  // pointer constant.
2290
2.83M
  if (ToType->isNullPtrType() &&
2291
2.83M
      
isNullPointerConstantForConversion(From, InOverloadResolution, Context)3.79k
) {
2292
23
    ConvertedType = ToType;
2293
23
    return true;
2294
23
  }
2295
2.83M
2296
2.83M
  const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2297
2.83M
  if (!ToTypePtr)
2298
1.92M
    return false;
2299
909k
2300
909k
  // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2301
909k
  if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2302
160k
    ConvertedType = ToType;
2303
160k
    return true;
2304
160k
  }
2305
749k
2306
749k
  // Beyond this point, both types need to be pointers
2307
749k
  // , including objective-c pointers.
2308
749k
  QualType ToPointeeType = ToTypePtr->getPointeeType();
2309
749k
  if (FromType->isObjCObjectPointerType() && 
ToPointeeType->isVoidType()248
&&
2310
749k
      
!getLangOpts().ObjCAutoRefCount99
) {
2311
94
    ConvertedType = BuildSimilarlyQualifiedPointerType(
2312
94
                                      FromType->getAs<ObjCObjectPointerType>(),
2313
94
                                                       ToPointeeType,
2314
94
                                                       ToType, Context);
2315
94
    return true;
2316
94
  }
2317
749k
  const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2318
749k
  if (!FromTypePtr)
2319
29.2k
    return false;
2320
719k
2321
719k
  QualType FromPointeeType = FromTypePtr->getPointeeType();
2322
719k
2323
719k
  // If the unqualified pointee types are the same, this can't be a
2324
719k
  // pointer conversion, so don't do all of the work below.
2325
719k
  if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2326
252k
    return false;
2327
467k
2328
467k
  // An rvalue of type "pointer to cv T," where T is an object type,
2329
467k
  // can be converted to an rvalue of type "pointer to cv void" (C++
2330
467k
  // 4.10p2).
2331
467k
  if (FromPointeeType->isIncompleteOrObjectType() &&
2332
467k
      
ToPointeeType->isVoidType()464k
) {
2333
117k
    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2334
117k
                                                       ToPointeeType,
2335
117k
                                                       ToType, Context,
2336
117k
                                                   /*StripObjCLifetime=*/true);
2337
117k
    return true;
2338
117k
  }
2339
350k
2340
350k
  // MSVC allows implicit function to void* type conversion.
2341
350k
  if (getLangOpts().MSVCCompat && 
FromPointeeType->isFunctionType()165
&&
2342
350k
      
ToPointeeType->isVoidType()7
) {
2343
6
    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2344
6
                                                       ToPointeeType,
2345
6
                                                       ToType, Context);
2346
6
    return true;
2347
6
  }
2348
350k
2349
350k
  // When we're overloading in C, we allow a special kind of pointer
2350
350k
  // conversion for compatible-but-not-identical pointee types.
2351
350k
  if (!getLangOpts().CPlusPlus &&
2352
350k
      
Context.typesAreCompatible(FromPointeeType, ToPointeeType)235k
) {
2353
3.71k
    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2354
3.71k
                                                       ToPointeeType,
2355
3.71k
                                                       ToType, Context);
2356
3.71k
    return true;
2357
3.71k
  }
2358
346k
2359
346k
  // C++ [conv.ptr]p3:
2360
346k
  //
2361
346k
  //   An rvalue of type "pointer to cv D," where D is a class type,
2362
346k
  //   can be converted to an rvalue of type "pointer to cv B," where
2363
346k
  //   B is a base class (clause 10) of D. If B is an inaccessible
2364
346k
  //   (clause 11) or ambiguous (10.2) base class of D, a program that
2365
346k
  //   necessitates this conversion is ill-formed. The result of the
2366
346k
  //   conversion is a pointer to the base class sub-object of the
2367
346k
  //   derived class object. The null pointer value is converted to
2368
346k
  //   the null pointer value of the destination type.
2369
346k
  //
2370
346k
  // Note that we do not check for ambiguity or inaccessibility
2371
346k
  // here. That is handled by CheckPointerConversion.
2372
346k
  if (getLangOpts().CPlusPlus && 
FromPointeeType->isRecordType()114k
&&
2373
346k
      
ToPointeeType->isRecordType()42.2k
&&
2374
346k
      
!Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)35.5k
&&
2375
346k
      
IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)35.5k
) {
2376
30.0k
    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2377
30.0k
                                                       ToPointeeType,
2378
30.0k
                                                       ToType, Context);
2379
30.0k
    return true;
2380
30.0k
  }
2381
316k
2382
316k
  if (FromPointeeType->isVectorType() && 
ToPointeeType->isVectorType()130k
&&
2383
316k
      
Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)64.3k
) {
2384
22
    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2385
22
                                                       ToPointeeType,
2386
22
                                                       ToType, Context);
2387
22
    return true;
2388
22
  }
2389
316k
2390
316k
  return false;
2391
316k
}
2392
2393
/// Adopt the given qualifiers for the given type.
2394
1.27k
static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2395
1.27k
  Qualifiers TQs = T.getQualifiers();
2396
1.27k
2397
1.27k
  // Check whether qualifiers already match.
2398
1.27k
  if (TQs == Qs)
2399
1.24k
    return T;
2400
21
2401
21
  if (Qs.compatiblyIncludes(TQs))
2402
4
    return Context.getQualifiedType(T, Qs);
2403
17
2404
17
  return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2405
17
}
2406
2407
/// isObjCPointerConversion - Determines whether this is an
2408
/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2409
/// with the same arguments and return values.
2410
bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2411
                                   QualType& ConvertedType,
2412
2.83M
                                   bool &IncompatibleObjC) {
2413
2.83M
  if (!getLangOpts().ObjC)
2414
2.82M
    return false;
2415
4.41k
2416
4.41k
  // The set of qualifiers on the type we're converting from.
2417
4.41k
  Qualifiers FromQualifiers = FromType.getQualifiers();
2418
4.41k
2419
4.41k
  // First, we handle all conversions on ObjC object pointer types.
2420
4.41k
  const ObjCObjectPointerType* ToObjCPtr =
2421
4.41k
    ToType->getAs<ObjCObjectPointerType>();
2422
4.41k
  const ObjCObjectPointerType *FromObjCPtr =
2423
4.41k
    FromType->getAs<ObjCObjectPointerType>();
2424
4.41k
2425
4.41k
  if (ToObjCPtr && 
FromObjCPtr1.94k
) {
2426
1.38k
    // If the pointee types are the same (ignoring qualifications),
2427
1.38k
    // then this is not a pointer conversion.
2428
1.38k
    if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2429
1.38k
                                       FromObjCPtr->getPointeeType()))
2430
108
      return false;
2431
1.27k
2432
1.27k
    // Conversion between Objective-C pointers.
2433
1.27k
    if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2434
1.17k
      const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2435
1.17k
      const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2436
1.17k
      if (getLangOpts().CPlusPlus && 
LHS1.15k
&&
RHS346
&&
2437
1.17k
          !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2438
93
                                                FromObjCPtr->getPointeeType()))
2439
1
        return false;
2440
1.17k
      ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2441
1.17k
                                                   ToObjCPtr->getPointeeType(),
2442
1.17k
                                                         ToType, Context);
2443
1.17k
      ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2444
1.17k
      return true;
2445
1.17k
    }
2446
98
2447
98
    if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2448
36
      // Okay: this is some kind of implicit downcast of Objective-C
2449
36
      // interfaces, which is permitted. However, we're going to
2450
36
      // complain about it.
2451
36
      IncompatibleObjC = true;
2452
36
      ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2453
36
                                                   ToObjCPtr->getPointeeType(),
2454
36
                                                         ToType, Context);
2455
36
      ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2456
36
      return true;
2457
36
    }
2458
3.09k
  }
2459
3.09k
  // Beyond this point, both types need to be C pointers or block pointers.
2460
3.09k
  QualType ToPointeeType;
2461
3.09k
  if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2462
2.33k
    ToPointeeType = ToCPtr->getPointeeType();
2463
764
  else if (const BlockPointerType *ToBlockPtr =
2464
59
            ToType->getAs<BlockPointerType>()) {
2465
59
    // Objective C++: We're able to convert from a pointer to any object
2466
59
    // to a block pointer type.
2467
59
    if (FromObjCPtr && 
FromObjCPtr->isObjCBuiltinType()21
) {
2468
14
      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2469
14
      return true;
2470
14
    }
2471
45
    ToPointeeType = ToBlockPtr->getPointeeType();
2472
45
  }
2473
705
  else if (FromType->getAs<BlockPointerType>() &&
2474
705
           
ToObjCPtr28
&&
ToObjCPtr->isObjCBuiltinType()28
) {
2475
27
    // Objective C++: We're able to convert from a block pointer type to a
2476
27
    // pointer to any object.
2477
27
    ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2478
27
    return true;
2479
27
  }
2480
678
  else
2481
678
    return false;
2482
2.37k
2483
2.37k
  QualType FromPointeeType;
2484
2.37k
  if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2485
1.35k
    FromPointeeType = FromCPtr->getPointeeType();
2486
1.02k
  else if (const BlockPointerType *FromBlockPtr =
2487
26
           FromType->getAs<BlockPointerType>())
2488
26
    FromPointeeType = FromBlockPtr->getPointeeType();
2489
998
  else
2490
998
    return false;
2491
1.37k
2492
1.37k
  // If we have pointers to pointers, recursively check whether this
2493
1.37k
  // is an Objective-C conversion.
2494
1.37k
  if (FromPointeeType->isPointerType() && 
ToPointeeType->isPointerType()58
&&
2495
1.37k
      isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2496
9
                              IncompatibleObjC)) {
2497
0
    // We always complain about this conversion.
2498
0
    IncompatibleObjC = true;
2499
0
    ConvertedType = Context.getPointerType(ConvertedType);
2500
0
    ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2501
0
    return true;
2502
0
  }
2503
1.37k
  // Allow conversion of pointee being objective-c pointer to another one;
2504
1.37k
  // as in I* to id.
2505
1.37k
  if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2506
1.37k
      
ToPointeeType->getAs<ObjCObjectPointerType>()158
&&
2507
1.37k
      isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2508
92
                              IncompatibleObjC)) {
2509
16
2510
16
    ConvertedType = Context.getPointerType(ConvertedType);
2511
16
    ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2512
16
    return true;
2513
16
  }
2514
1.36k
2515
1.36k
  // If we have pointers to functions or blocks, check whether the only
2516
1.36k
  // differences in the argument and result types are in Objective-C
2517
1.36k
  // pointer conversions. If so, we permit the conversion (but
2518
1.36k
  // complain about it).
2519
1.36k
  const FunctionProtoType *FromFunctionType
2520
1.36k
    = FromPointeeType->getAs<FunctionProtoType>();
2521
1.36k
  const FunctionProtoType *ToFunctionType
2522
1.36k
    = ToPointeeType->getAs<FunctionProtoType>();
2523
1.36k
  if (FromFunctionType && 
ToFunctionType55
) {
2524
46
    // If the function types are exactly the same, this isn't an
2525
46
    // Objective-C pointer conversion.
2526
46
    if (Context.getCanonicalType(FromPointeeType)
2527
46
          == Context.getCanonicalType(ToPointeeType))
2528
24
      return false;
2529
22
2530
22
    // Perform the quick checks that will tell us whether these
2531
22
    // function types are obviously different.
2532
22
    if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2533
22
        
FromFunctionType->isVariadic() != ToFunctionType->isVariadic()17
||
2534
22
        
FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals()17
)
2535
5
      return false;
2536
17
2537
17
    bool HasObjCConversion = false;
2538
17
    if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2539
17
        Context.getCanonicalType(ToFunctionType->getReturnType())) {
2540
15
      // Okay, the types match exactly. Nothing to do.
2541
15
    } else 
if (2
isObjCPointerConversion(FromFunctionType->getReturnType(),
2542
2
                                       ToFunctionType->getReturnType(),
2543
2
                                       ConvertedType, IncompatibleObjC)) {
2544
2
      // Okay, we have an Objective-C pointer conversion.
2545
2
      HasObjCConversion = true;
2546
2
    } else {
2547
0
      // Function types are too different. Abort.
2548
0
      return false;
2549
0
    }
2550
17
2551
17
    // Check argument types.
2552
17
    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2553
37
         ArgIdx != NumArgs; 
++ArgIdx20
) {
2554
20
      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2555
20
      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2556
20
      if (Context.getCanonicalType(FromArgType)
2557
20
            == Context.getCanonicalType(ToArgType)) {
2558
19
        // Okay, the types match exactly. Nothing to do.
2559
19
      } else 
if (1
isObjCPointerConversion(FromArgType, ToArgType,
2560
1
                                         ConvertedType, IncompatibleObjC)) {
2561
1
        // Okay, we have an Objective-C pointer conversion.
2562
1
        HasObjCConversion = true;
2563
1
      } else {
2564
0
        // Argument types are too different. Abort.
2565
0
        return false;
2566
0
      }
2567
20
    }
2568
17
2569
17
    if (HasObjCConversion) {
2570
3
      // We had an Objective-C conversion. Allow this pointer
2571
3
      // conversion, but complain about it.
2572
3
      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2573
3
      IncompatibleObjC = true;
2574
3
      return true;
2575
3
    }
2576
1.33k
  }
2577
1.33k
2578
1.33k
  return false;
2579
1.33k
}
2580
2581
/// Determine whether this is an Objective-C writeback conversion,
2582
/// used for parameter passing when performing automatic reference counting.
2583
///
2584
/// \param FromType The type we're converting form.
2585
///
2586
/// \param ToType The type we're converting to.
2587
///
2588
/// \param ConvertedType The type that will be produced after applying
2589
/// this conversion.
2590
bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2591
2.04k
                                     QualType &ConvertedType) {
2592
2.04k
  if (!getLangOpts().ObjCAutoRefCount ||
2593
2.04k
      Context.hasSameUnqualifiedType(FromType, ToType))
2594
1.07k
    return false;
2595
966
2596
966
  // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2597
966
  QualType ToPointee;
2598
966
  if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2599
476
    ToPointee = ToPointer->getPointeeType();
2600
490
  else
2601
490
    return false;
2602
476
2603
476
  Qualifiers ToQuals = ToPointee.getQualifiers();
2604
476
  if (!ToPointee->isObjCLifetimeType() ||
2605
476
      
ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing133
||
2606
476
      
!ToQuals.withoutObjCLifetime().empty()95
)
2607
392
    return false;
2608
84
2609
84
  // Argument must be a pointer to __strong to __weak.
2610
84
  QualType FromPointee;
2611
84
  if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2612
83
    FromPointee = FromPointer->getPointeeType();
2613
1
  else
2614
1
    return false;
2615
83
2616
83
  Qualifiers FromQuals = FromPointee.getQualifiers();
2617
83
  if (!FromPointee->isObjCLifetimeType() ||
2618
83
      (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2619
83
       
FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak20
))
2620
5
    return false;
2621
78
2622
78
  // Make sure that we have compatible qualifiers.
2623
78
  FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2624
78
  if (!ToQuals.compatiblyIncludes(FromQuals))
2625
0
    return false;
2626
78
2627
78
  // Remove qualifiers from the pointee type we're converting from; they
2628
78
  // aren't used in the compatibility check belong, and we'll be adding back
2629
78
  // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2630
78
  FromPointee = FromPointee.getUnqualifiedType();
2631
78
2632
78
  // The unqualified form of the pointee types must be compatible.
2633
78
  ToPointee = ToPointee.getUnqualifiedType();
2634
78
  bool IncompatibleObjC;
2635
78
  if (Context.typesAreCompatible(FromPointee, ToPointee))
2636
75
    FromPointee = ToPointee;
2637
3
  else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2638
3
                                    IncompatibleObjC))
2639
0
    return false;
2640
78
2641
78
  /// Construct the type we're converting to, which is a pointer to
2642
78
  /// __autoreleasing pointee.
2643
78
  FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2644
78
  ConvertedType = Context.getPointerType(FromPointee);
2645
78
  return true;
2646
78
}
2647
2648
bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2649
2.83M
                                    QualType& ConvertedType) {
2650
2.83M
  QualType ToPointeeType;
2651
2.83M
  if (const BlockPointerType *ToBlockPtr =
2652
580
        ToType->getAs<BlockPointerType>())
2653
580
    ToPointeeType = ToBlockPtr->getPointeeType();
2654
2.83M
  else
2655
2.83M
    return false;
2656
580
2657
580
  QualType FromPointeeType;
2658
580
  if (const BlockPointerType *FromBlockPtr =
2659
21
      FromType->getAs<BlockPointerType>())
2660
21
    FromPointeeType = FromBlockPtr->getPointeeType();
2661
559
  else
2662
559
    return false;
2663
21
  // We have pointer to blocks, check whether the only
2664
21
  // differences in the argument and result types are in Objective-C
2665
21
  // pointer conversions. If so, we permit the conversion.
2666
21
2667
21
  const FunctionProtoType *FromFunctionType
2668
21
    = FromPointeeType->getAs<FunctionProtoType>();
2669
21
  const FunctionProtoType *ToFunctionType
2670
21
    = ToPointeeType->getAs<FunctionProtoType>();
2671
21
2672
21
  if (!FromFunctionType || !ToFunctionType)
2673
0
    return false;
2674
21
2675
21
  if (Context.hasSameType(FromPointeeType, ToPointeeType))
2676
0
    return true;
2677
21
2678
21
  // Perform the quick checks that will tell us whether these
2679
21
  // function types are obviously different.
2680
21
  if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2681
21
      
FromFunctionType->isVariadic() != ToFunctionType->isVariadic()17
)
2682
4
    return false;
2683
17
2684
17
  FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2685
17
  FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2686
17
  if (FromEInfo != ToEInfo)
2687
0
    return false;
2688
17
2689
17
  bool IncompatibleObjC = false;
2690
17
  if (Context.hasSameType(FromFunctionType->getReturnType(),
2691
17
                          ToFunctionType->getReturnType())) {
2692
11
    // Okay, the types match exactly. Nothing to do.
2693
11
  } else {
2694
6
    QualType RHS = FromFunctionType->getReturnType();
2695
6
    QualType LHS = ToFunctionType->getReturnType();
2696
6
    if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2697
6
        !RHS.hasQualifiers() && 
LHS.hasQualifiers()5
)
2698
1
       LHS = LHS.getUnqualifiedType();
2699
6
2700
6
     if (Context.hasSameType(RHS,LHS)) {
2701
1
       // OK exact match.
2702
5
     } else if (isObjCPointerConversion(RHS, LHS,
2703
5
                                        ConvertedType, IncompatibleObjC)) {
2704
4
     if (IncompatibleObjC)
2705
0
       return false;
2706
1
     // Okay, we have an Objective-C pointer conversion.
2707
1
     }
2708
1
     else
2709
1
       return false;
2710
16
   }
2711
16
2712
16
   // Check argument types.
2713
16
   for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2714
32
        ArgIdx != NumArgs; 
++ArgIdx16
) {
2715
18
     IncompatibleObjC = false;
2716
18
     QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2717
18
     QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2718
18
     if (Context.hasSameType(FromArgType, ToArgType)) {
2719
13
       // Okay, the types match exactly. Nothing to do.
2720
13
     } else 
if (5
isObjCPointerConversion(ToArgType, FromArgType,
2721
5
                                        ConvertedType, IncompatibleObjC)) {
2722
4
       if (IncompatibleObjC)
2723
1
         return false;
2724
1
       // Okay, we have an Objective-C pointer conversion.
2725
1
     } else
2726
1
       // Argument types are too different. Abort.
2727
1
       return false;
2728
18
   }
2729
16
2730
16
   SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2731
14
   bool CanUseToFPT, CanUseFromFPT;
2732
14
   if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2733
14
                                      CanUseToFPT, CanUseFromFPT,
2734
14
                                      NewParamInfos))
2735
6
     return false;
2736
8
2737
8
   ConvertedType = ToType;
2738
8
   return true;
2739
8
}
2740
2741
enum {
2742
  ft_default,
2743
  ft_different_class,
2744
  ft_parameter_arity,
2745
  ft_parameter_mismatch,
2746
  ft_return_type,
2747
  ft_qualifer_mismatch,
2748
  ft_noexcept
2749
};
2750
2751
/// Attempts to get the FunctionProtoType from a Type. Handles
2752
/// MemberFunctionPointers properly.
2753
4.01k
static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2754
4.01k
  if (auto *FPT = FromType->getAs<FunctionProtoType>())
2755
403
    return FPT;
2756
3.61k
2757
3.61k
  if (auto *MPT = FromType->getAs<MemberPointerType>())
2758
3
    return MPT->getPointeeType()->getAs<FunctionProtoType>();
2759
3.61k
2760
3.61k
  return nullptr;
2761
3.61k
}
2762
2763
/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2764
/// function types.  Catches different number of parameter, mismatch in
2765
/// parameter types, and different return types.
2766
void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2767
5.92k
                                      QualType FromType, QualType ToType) {
2768
5.92k
  // If either type is not valid, include no extra info.
2769
5.92k
  if (FromType.isNull() || ToType.isNull()) {
2770
3.78k
    PDiag << ft_default;
2771
3.78k
    return;
2772
3.78k
  }
2773
2.13k
2774
2.13k
  // Get the function type from the pointers.
2775
2.13k
  if (FromType->isMemberPointerType() && 
ToType->isMemberPointerType()43
) {
2776
43
    const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2777
43
                            *ToMember = ToType->getAs<MemberPointerType>();
2778
43
    if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2779
6
      PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2780
6
            << QualType(FromMember->getClass(), 0);
2781
6
      return;
2782
6
    }
2783
37
    FromType = FromMember->getPointeeType();
2784
37
    ToType = ToMember->getPointeeType();
2785
37
  }
2786
2.13k
2787
2.13k
  
if (2.13k
FromType->isPointerType()2.13k
)
2788
616
    FromType = FromType->getPointeeType();
2789
2.13k
  if (ToType->isPointerType())
2790
823
    ToType = ToType->getPointeeType();
2791
2.13k
2792
2.13k
  // Remove references.
2793
2.13k
  FromType = FromType.getNonReferenceType();
2794
2.13k
  ToType = ToType.getNonReferenceType();
2795
2.13k
2796
2.13k
  // Don't print extra info for non-specialized template functions.
2797
2.13k
  if (FromType->isInstantiationDependentType() &&
2798
2.13k
      
!FromType->getAs<TemplateSpecializationType>()6
) {
2799
6
    PDiag << ft_default;
2800
6
    return;
2801
6
  }
2802
2.12k
2803
2.12k
  // No extra info for same types.
2804
2.12k
  if (Context.hasSameType(FromType, ToType)) {
2805
117
    PDiag << ft_default;
2806
117
    return;
2807
117
  }
2808
2.00k
2809
2.00k
  const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2810
2.00k
                          *ToFunction = tryGetFunctionProtoType(ToType);
2811
2.00k
2812
2.00k
  // Both types need to be function types.
2813
2.00k
  if (!FromFunction || 
!ToFunction204
) {
2814
1.82k
    PDiag << ft_default;
2815
1.82k
    return;
2816
1.82k
  }
2817
183
2818
183
  if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2819
51
    PDiag << ft_parameter_arity << ToFunction->getNumParams()
2820
51
          << FromFunction->getNumParams();
2821
51
    return;
2822
51
  }
2823
132
2824
132
  // Handle different parameter types.
2825
132
  unsigned ArgPos;
2826
132
  if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2827
51
    PDiag << ft_parameter_mismatch << ArgPos + 1
2828
51
          << ToFunction->getParamType(ArgPos)
2829
51
          << FromFunction->getParamType(ArgPos);
2830
51
    return;
2831
51
  }
2832
81
2833
81
  // Handle different return type.
2834
81
  if (!Context.hasSameType(FromFunction->getReturnType(),
2835
81
                           ToFunction->getReturnType())) {
2836
15
    PDiag << ft_return_type << ToFunction->getReturnType()
2837
15
          << FromFunction->getReturnType();
2838
15
    return;
2839
15
  }
2840
66
2841
66
  if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2842
30
    PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2843
30
          << FromFunction->getMethodQuals();
2844
30
    return;
2845
30
  }
2846
36
2847
36
  // Handle exception specification differences on canonical type (in C++17
2848
36
  // onwards).
2849
36
  if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2850
36
          ->isNothrow() !=
2851
36
      cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2852
36
          ->isNothrow()) {
2853
19
    PDiag << ft_noexcept;
2854
19
    return;
2855
19
  }
2856
17
2857
17
  // Unable to find a difference, so add no extra info.
2858
17
  PDiag << ft_default;
2859
17
}
2860
2861
/// FunctionParamTypesAreEqual - This routine checks two function proto types
2862
/// for equality of their argument types. Caller has already checked that
2863
/// they have same number of arguments.  If the parameters are different,
2864
/// ArgPos will have the parameter index of the first different parameter.
2865
bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2866
                                      const FunctionProtoType *NewType,
2867
9.08M
                                      unsigned *ArgPos) {
2868
9.08M
  for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2869
9.08M
                                              N = NewType->param_type_begin(),
2870
9.08M
                                              E = OldType->param_type_end();
2871
10.1M
       O && (O != E); 
++O, ++N1.03M
) {
2872
9.93M
    if (!Context.hasSameType(O->getUnqualifiedType(),
2873
9.93M
                             N->getUnqualifiedType())) {
2874
8.89M
      if (ArgPos)
2875
51
        *ArgPos = O - OldType->param_type_begin();
2876
8.89M
      return false;
2877
8.89M
    }
2878
9.93M
  }
2879
9.08M
  
return true194k
;
2880
9.08M
}
2881
2882
/// CheckPointerConversion - Check the pointer conversion from the
2883
/// expression From to the type ToType. This routine checks for
2884
/// ambiguous or inaccessible derived-to-base pointer
2885
/// conversions for which IsPointerConversion has already returned
2886
/// true. It returns true and produces a diagnostic if there was an
2887
/// error, or returns false otherwise.
2888
bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2889
                                  CastKind &Kind,
2890
                                  CXXCastPath& BasePath,
2891
                                  bool IgnoreBaseAccess,
2892
238k
                                  bool Diagnose) {
2893
238k
  QualType FromType = From->getType();
2894
238k
  bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2895
238k
2896
238k
  Kind = CK_BitCast;
2897
238k
2898
238k
  if (Diagnose && !IsCStyleOrFunctionalCast && 
!FromType->isAnyPointerType()222k
&&
2899
238k
      From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2900
131k
          Expr::NPCK_ZeroExpression) {
2901
22
    if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2902
9
      DiagRuntimeBehavior(From->getExprLoc(), From,
2903
9
                          PDiag(diag::warn_impcast_bool_to_null_pointer)
2904
9
                            << ToType << From->getSourceRange());
2905
13
    else if (!isUnevaluatedContext())
2906
13
      Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2907
13
        << ToType << From->getSourceRange();
2908
22
  }
2909
238k
  if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2910
235k
    if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2911
99.3k
      QualType FromPointeeType = FromPtrType->getPointeeType(),
2912
99.3k
               ToPointeeType   = ToPtrType->getPointeeType();
2913
99.3k
2914
99.3k
      if (FromPointeeType->isRecordType() && 
ToPointeeType->isRecordType()45.3k
&&
2915
99.3k
          
!Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)20.5k
) {
2916
20.5k
        // We must have a derived-to-base conversion. Check an
2917
20.5k
        // ambiguous or inaccessible conversion.
2918
20.5k
        unsigned InaccessibleID = 0;
2919
20.5k
        unsigned AmbigiousID = 0;
2920
20.5k
        if (Diagnose) {
2921
20.5k
          InaccessibleID = diag::err_upcast_to_inaccessible_base;
2922
20.5k
          AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2923
20.5k
        }
2924
20.5k
        if (CheckDerivedToBaseConversion(
2925
20.5k
                FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2926
20.5k
                From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2927
20.5k
                &BasePath, IgnoreBaseAccess))
2928
13
          return true;
2929
20.4k
2930
20.4k
        // The conversion was successful.
2931
20.4k
        Kind = CK_DerivedToBase;
2932
20.4k
      }
2933
99.3k
2934
99.3k
      
if (99.3k
Diagnose99.3k
&&
!IsCStyleOrFunctionalCast99.3k
&&
2935
99.3k
          
FromPointeeType->isFunctionType()89.1k
&&
ToPointeeType->isVoidType()8
) {
2936
6
        assert(getLangOpts().MSVCCompat &&
2937
6
               "this should only be possible with MSVCCompat!");
2938
6
        Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2939
6
            << From->getSourceRange();
2940
6
      }
2941
99.3k
    }
2942
235k
  } else 
if (const ObjCObjectPointerType *2.90k
ToPtrType2.90k
=
2943
2.60k
               ToType->getAs<ObjCObjectPointerType>()) {
2944
2.60k
    if (const ObjCObjectPointerType *FromPtrType =
2945
1.06k
          FromType->getAs<ObjCObjectPointerType>()) {
2946
1.06k
      // Objective-C++ conversions are always okay.
2947
1.06k
      // FIXME: We should have a different class of conversions for the
2948
1.06k
      // Objective-C++ implicit conversions.
2949
1.06k
      if (FromPtrType->isObjCBuiltinType() || 
ToPtrType->isObjCBuiltinType()807
)
2950
900
        return false;
2951
1.53k
    } else if (FromType->isBlockPointerType()) {
2952
24
      Kind = CK_BlockPointerToObjCPointerCast;
2953
1.51k
    } else {
2954
1.51k
      Kind = CK_CPointerToObjCPointerCast;
2955
1.51k
    }
2956
2.60k
  } else 
if (305
ToType->isBlockPointerType()305
) {
2957
289
    if (!FromType->isBlockPointerType())
2958
289
      Kind = CK_AnyPointerToBlockPointerCast;
2959
289
  }
2960
238k
2961
238k
  // We shouldn't fall into this case unless it's valid for other
2962
238k
  // reasons.
2963
238k
  
if (237k
From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)237k
)
2964
146k
    Kind = CK_NullToPointer;
2965
237k
2966
237k
  return false;
2967
238k
}
2968
2969
/// IsMemberPointerConversion - Determines whether the conversion of the
2970
/// expression From, which has the (possibly adjusted) type FromType, can be
2971
/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2972
/// If so, returns true and places the converted type (that might differ from
2973
/// ToType in its cv-qualifiers at some level) into ConvertedType.
2974
bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2975
                                     QualType ToType,
2976
                                     bool InOverloadResolution,
2977
2.51M
                                     QualType &ConvertedType) {
2978
2.51M
  const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2979
2.51M
  if (!ToTypePtr)
2980
2.51M
    return false;
2981
3.20k
2982
3.20k
  // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2983
3.20k
  if (From->isNullPointerConstant(Context,
2984
3.20k
                    InOverloadResolution? 
Expr::NPC_ValueDependentIsNotNull751
2985
3.20k
                                        : 
Expr::NPC_ValueDependentIsNull2.45k
)) {
2986
1.30k
    ConvertedType = ToType;
2987
1.30k
    return true;
2988
1.30k
  }
2989
1.89k
2990
1.89k
  // Otherwise, both types have to be member pointers.
2991
1.89k
  const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2992
1.89k
  if (!FromTypePtr)
2993
723
    return false;
2994
1.17k
2995
1.17k
  // A pointer to member of B can be converted to a pointer to member of D,
2996
1.17k
  // where D is derived from B (C++ 4.11p2).
2997
1.17k
  QualType FromClass(FromTypePtr->getClass(), 0);
2998
1.17k
  QualType ToClass(ToTypePtr->getClass(), 0);
2999
1.17k
3000
1.17k
  if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3001
1.17k
      
IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)664
) {
3002
445
    ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3003
445
                                                 ToClass.getTypePtr());
3004
445
    return true;
3005
445
  }
3006
730
3007
730
  return false;
3008
730
}
3009
3010
/// CheckMemberPointerConversion - Check the member pointer conversion from the
3011
/// expression From to the type ToType. This routine checks for ambiguous or
3012
/// virtual or inaccessible base-to-derived member pointer conversions
3013
/// for which IsMemberPointerConversion has already returned true. It returns
3014
/// true and produces a diagnostic if there was an error, or returns false
3015
/// otherwise.
3016
bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3017
                                        CastKind &Kind,
3018
                                        CXXCastPath &BasePath,
3019
1.04k
                                        bool IgnoreBaseAccess) {
3020
1.04k
  QualType FromType = From->getType();
3021
1.04k
  const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3022
1.04k
  if (!FromPtrType) {
3023
659
    // This must be a null pointer to member pointer conversion
3024
659
    assert(From->isNullPointerConstant(Context,
3025
659
                                       Expr::NPC_ValueDependentIsNull) &&
3026
659
           "Expr must be null pointer constant!");
3027
659
    Kind = CK_NullToMemberPointer;
3028
659
    return false;
3029
659
  }
3030
387
3031
387
  const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3032
387
  assert(ToPtrType && "No member pointer cast has a target type "
3033
387
                      "that is not a member pointer.");
3034
387
3035
387
  QualType FromClass = QualType(FromPtrType->getClass(), 0);
3036
387
  QualType ToClass   = QualType(ToPtrType->getClass(), 0);
3037
387
3038
387
  // FIXME: What about dependent types?
3039
387
  assert(FromClass->isRecordType() && "Pointer into non-class.");
3040
387
  assert(ToClass->isRecordType() && "Pointer into non-class.");
3041
387
3042
387
  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3043
387
                     /*DetectVirtual=*/true);
3044
387
  bool DerivationOkay =
3045
387
      IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3046
387
  assert(DerivationOkay &&
3047
387
         "Should not have been called if derivation isn't OK.");
3048
387
  (void)DerivationOkay;
3049
387
3050
387
  if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3051
387
                                  getUnqualifiedType())) {
3052
7
    std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3053
7
    Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3054
7
      << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3055
7
    return true;
3056
7
  }
3057
380
3058
380
  if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3059
17
    Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3060
17
      << FromClass << ToClass << QualType(VBase, 0)
3061
17
      << From->getSourceRange();
3062
17
    return true;
3063
17
  }
3064
363
3065
363
  if (!IgnoreBaseAccess)
3066
317
    CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3067
317
                         Paths.front(),
3068
317
                         diag::err_downcast_from_inaccessible_base);
3069
363
3070
363
  // Must be a base to derived member conversion.
3071
363
  BuildBasePathArray(Paths, BasePath);
3072
363
  Kind = CK_BaseToDerivedMemberPointer;
3073
363
  return false;
3074
363
}
3075
3076
/// Determine whether the lifetime conversion between the two given
3077
/// qualifiers sets is nontrivial.
3078
static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3079
61
                                               Qualifiers ToQuals) {
3080
61
  // Converting anything to const __unsafe_unretained is trivial.
3081
61
  if (ToQuals.hasConst() &&
3082
61
      
ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone45
)
3083
13
    return false;
3084
48
3085
48
  return true;
3086
48
}
3087
3088
/// IsQualificationConversion - Determines whether the conversion from
3089
/// an rvalue of type FromType to ToType is a qualification conversion
3090
/// (C++ 4.4).
3091
///
3092
/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3093
/// when the qualification conversion involves a change in the Objective-C
3094
/// object lifetime.
3095
bool
3096
Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3097
35.4M
                                bool CStyle, bool &ObjCLifetimeConversion) {
3098
35.4M
  FromType = Context.getCanonicalType(FromType);
3099
35.4M
  ToType = Context.getCanonicalType(ToType);
3100
35.4M
  ObjCLifetimeConversion = false;
3101
35.4M
3102
35.4M
  // If FromType and ToType are the same type, this is not a
3103
35.4M
  // qualification conversion.
3104
35.4M
  if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3105
33.7M
    return false;
3106
1.70M
3107
1.70M
  // (C++ 4.4p4):
3108
1.70M
  //   A conversion can add cv-qualifiers at levels other than the first
3109
1.70M
  //   in multi-level pointers, subject to the following rules: [...]
3110
1.70M
  bool PreviousToQualsIncludeConst = true;
3111
1.70M
  bool UnwrappedAnyPointer = false;
3112
2.27M
  while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3113
631k
    // Within each iteration of the loop, we check the qualifiers to
3114
631k
    // determine if this still looks like a qualification
3115
631k
    // conversion. Then, if all is well, we unwrap one more level of
3116
631k
    // pointers or pointers-to-members and do it all again
3117
631k
    // until there are no more pointers or pointers-to-members left to
3118
631k
    // unwrap.
3119
631k
    UnwrappedAnyPointer = true;
3120
631k
3121
631k
    Qualifiers FromQuals = FromType.getQualifiers();
3122
631k
    Qualifiers ToQuals = ToType.getQualifiers();
3123
631k
3124
631k
    // Ignore __unaligned qualifier if this type is void.
3125
631k
    if (ToType.getUnqualifiedType()->isVoidType())
3126
22.1k
      FromQuals.removeUnaligned();
3127
631k
3128
631k
    // Objective-C ARC:
3129
631k
    //   Check Objective-C lifetime conversions.
3130
631k
    if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3131
631k
        
UnwrappedAnyPointer100
) {
3132
100
      if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3133
41
        if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3134
33
          ObjCLifetimeConversion = true;
3135
41
        FromQuals.removeObjCLifetime();
3136
41
        ToQuals.removeObjCLifetime();
3137
59
      } else {
3138
59
        // Qualification conversions cannot cast between different
3139
59
        // Objective-C lifetime qualifiers.
3140
59
        return false;
3141
59
      }
3142
631k
    }
3143
631k
3144
631k
    // Allow addition/removal of GC attributes but not changing GC attributes.
3145
631k
    if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3146
631k
        
(8
!FromQuals.hasObjCGCAttr()8
||
!ToQuals.hasObjCGCAttr()2
)) {
3147
6
      FromQuals.removeObjCGCAttr();
3148
6
      ToQuals.removeObjCGCAttr();
3149
6
    }
3150
631k
3151
631k
    //   -- for every j > 0, if const is in cv 1,j then const is in cv
3152
631k
    //      2,j, and similarly for volatile.
3153
631k
    if (!CStyle && 
!ToQuals.compatiblyIncludes(FromQuals)600k
)
3154
63.3k
      return false;
3155
568k
3156
568k
    //   -- if the cv 1,j and cv 2,j are different, then const is in
3157
568k
    //      every cv for 0 < k < j.
3158
568k
    if (!CStyle && 
FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()536k
3159
568k
        && 
!PreviousToQualsIncludeConst360k
)
3160
28
      return false;
3161
568k
3162
568k
    // Keep track of whether all prior cv-qualifiers in the "to" type
3163
568k
    // include const.
3164
568k
    PreviousToQualsIncludeConst
3165
568k
      = PreviousToQualsIncludeConst && 
ToQuals.hasConst()567k
;
3166
568k
  }
3167
1.70M
3168
1.70M
  // Allows address space promotion by language rules implemented in
3169
1.70M
  // Type::Qualifiers::isAddressSpaceSupersetOf.
3170
1.70M
  Qualifiers FromQuals = FromType.getQualifiers();
3171
1.64M
  Qualifiers ToQuals = ToType.getQualifiers();
3172
1.64M
  if (!ToQuals.isAddressSpaceSupersetOf(FromQuals) &&
3173
1.64M
      
!FromQuals.isAddressSpaceSupersetOf(ToQuals)176
) {
3174
175
    return false;
3175
175
  }
3176
1.64M
3177
1.64M
  // We are left with FromType and ToType being the pointee types
3178
1.64M
  // after unwrapping the original FromType and ToType the same number
3179
1.64M
  // of types. If we unwrapped any pointers, and if FromType and
3180
1.64M
  // ToType have the same unqualified type (since we checked
3181
1.64M
  // qualifiers above), then this is a qualification conversion.
3182
1.64M
  return UnwrappedAnyPointer && 
Context.hasSameUnqualifiedType(FromType,ToType)566k
;
3183
1.64M
}
3184
3185
/// - Determine whether this is a conversion from a scalar type to an
3186
/// atomic type.
3187
///
3188
/// If successful, updates \c SCS's second and third steps in the conversion
3189
/// sequence to finish the conversion.
3190
static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3191
                                bool InOverloadResolution,
3192
                                StandardConversionSequence &SCS,
3193
1.64M
                                bool CStyle) {
3194
1.64M
  const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3195
1.64M
  if (!ToAtomic)
3196
1.64M
    return false;
3197
442
3198
442
  StandardConversionSequence InnerSCS;
3199
442
  if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3200
442
                            InOverloadResolution, InnerSCS,
3201
442
                            CStyle, /*AllowObjCWritebackConversion=*/false))
3202
54
    return false;
3203
388
3204
388
  SCS.Second = InnerSCS.Second;
3205
388
  SCS.setToType(1, InnerSCS.getToType(1));
3206
388
  SCS.Third = InnerSCS.Third;
3207
388
  SCS.QualificationIncludesObjCLifetime
3208
388
    = InnerSCS.QualificationIncludesObjCLifetime;
3209
388
  SCS.setToType(2, InnerSCS.getToType(2));
3210
388
  return true;
3211
388
}
3212
3213
static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3214
                                              CXXConstructorDecl *Constructor,
3215
630
                                              QualType Type) {
3216
630
  const FunctionProtoType *CtorType =
3217
630
      Constructor->getType()->getAs<FunctionProtoType>();
3218
630
  if (CtorType->getNumParams() > 0) {
3219
618
    QualType FirstArg = CtorType->getParamType(0);
3220
618
    if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3221
292
      return true;
3222
338
  }
3223
338
  return false;
3224
338
}
3225
3226
static OverloadingResult
3227
IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3228
                                       CXXRecordDecl *To,
3229
                                       UserDefinedConversionSequence &User,
3230
                                       OverloadCandidateSet &CandidateSet,
3231
667
                                       bool AllowExplicit) {
3232
667
  CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3233
4.34k
  for (auto *D : S.LookupConstructors(To)) {
3234
4.34k
    auto Info = getConstructorInfo(D);
3235
4.34k
    if (!Info)
3236
6
      continue;
3237
4.33k
3238
4.33k
    bool Usable = !Info.Constructor->isInvalidDecl() &&
3239
4.33k
                  S.isInitListConstructor(Info.Constructor) &&
3240
4.33k
                  
(173
AllowExplicit173
||
!Info.Constructor->isExplicit()173
);
3241
4.33k
    if (Usable) {
3242
173
      // If the first argument is (a reference to) the target type,
3243
173
      // suppress conversions.
3244
173
      bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3245
173
          S.Context, Info.Constructor, ToType);
3246
173
      if (Info.ConstructorTmpl)
3247
0
        S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3248
0
                                       /*ExplicitArgs*/ nullptr, From,
3249
0
                                       CandidateSet, SuppressUserConversions,
3250
0
                                       /*PartialOverloading*/ false,
3251
0
                                       AllowExplicit);
3252
173
      else
3253
173
        S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3254
173
                               CandidateSet, SuppressUserConversions,
3255
173
                               /*PartialOverloading*/ false, AllowExplicit);
3256
173
    }
3257
4.33k
  }
3258
667
3259
667
  bool HadMultipleCandidates = (CandidateSet.size() > 1);
3260
667
3261
667
  OverloadCandidateSet::iterator Best;
3262
667
  switch (auto Result =
3263
667
              CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3264
667
  case OR_Deleted:
3265
170
  case OR_Success: {
3266
170
    // Record the standard conversion we used and the conversion function.
3267
170
    CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3268
170
    QualType ThisType = Constructor->getThisType();
3269
170
    // Initializer lists don't have conversions as such.
3270
170
    User.Before.setAsIdentityConversion();
3271
170
    User.HadMultipleCandidates = HadMultipleCandidates;
3272
170
    User.ConversionFunction = Constructor;
3273
170
    User.FoundConversionFunction = Best->FoundDecl;
3274
170
    User.After.setAsIdentityConversion();
3275
170
    User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3276
170
    User.After.setAllToTypes(ToType);
3277
170
    return Result;
3278
170
  }
3279
170
3280
497
  case OR_No_Viable_Function:
3281
497
    return OR_No_Viable_Function;
3282
170
  case OR_Ambiguous:
3283
0
    return OR_Ambiguous;
3284
0
  }
3285
0
3286
0
  llvm_unreachable("Invalid OverloadResult!");
3287
0
}
3288
3289
/// Determines whether there is a user-defined conversion sequence
3290
/// (C++ [over.ics.user]) that converts expression From to the type
3291
/// ToType. If such a conversion exists, User will contain the
3292
/// user-defined conversion sequence that performs such a conversion
3293
/// and this routine will return true. Otherwise, this routine returns
3294
/// false and User is unspecified.
3295
///
3296
/// \param AllowExplicit  true if the conversion should consider C++0x
3297
/// "explicit" conversion functions as well as non-explicit conversion
3298
/// functions (C++0x [class.conv.fct]p2).
3299
///
3300
/// \param AllowObjCConversionOnExplicit true if the conversion should
3301
/// allow an extra Objective-C pointer conversion on uses of explicit
3302
/// constructors. Requires \c AllowExplicit to also be set.
3303
static OverloadingResult
3304
IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3305
                        UserDefinedConversionSequence &User,
3306
                        OverloadCandidateSet &CandidateSet,
3307
                        bool AllowExplicit,
3308
1.69M
                        bool AllowObjCConversionOnExplicit) {
3309
1.69M
  assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3310
1.69M
  CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3311
1.69M
3312
1.69M
  // Whether we will only visit constructors.
3313
1.69M
  bool ConstructorsOnly = false;
3314
1.69M
3315
1.69M
  // If the type we are conversion to is a class type, enumerate its
3316
1.69M
  // constructors.
3317
1.69M
  if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3318
252k
    // C++ [over.match.ctor]p1:
3319
252k
    //   When objects of class type are direct-initialized (8.5), or
3320
252k
    //   copy-initialized from an expression of the same or a
3321
252k
    //   derived class type (8.5), overload resolution selects the
3322
252k
    //   constructor. [...] For copy-initialization, the candidate
3323
252k
    //   functions are all the converting constructors (12.3.1) of
3324
252k
    //   that class. The argument list is the expression-list within
3325
252k
    //   the parentheses of the initializer.
3326
252k
    if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3327
252k
        (From->getType()->getAs<RecordType>() &&
3328
252k
         
S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)127k
))
3329
0
      ConstructorsOnly = true;
3330
252k
3331
252k
    if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3332
5.16k
      // We're not going to find any constructors.
3333
247k
    } else if (CXXRecordDecl *ToRecordDecl
3334
247k
                 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3335
247k
3336
247k
      Expr **Args = &From;
3337
247k
      unsigned NumArgs = 1;
3338
247k
      bool ListInitializing = false;
3339
247k
      if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3340
667
        // But first, see if there is an init-list-constructor that will work.
3341
667
        OverloadingResult Result = IsInitializerListConstructorConversion(
3342
667
            S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3343
667
        if (Result != OR_No_Viable_Function)
3344
170
          return Result;
3345
497
        // Never mind.
3346
497
        CandidateSet.clear(
3347
497
            OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3348
497
3349
497
        // If we're list-initializing, we pass the individual elements as
3350
497
        // arguments, not the entire list.
3351
497
        Args = InitList->getInits();
3352
497
        NumArgs = InitList->getNumInits();
3353
497
        ListInitializing = true;
3354
497
      }
3355
247k
3356
1.24M
      
for (auto *D : S.LookupConstructors(ToRecordDecl))246k
{
3357
1.24M
        auto Info = getConstructorInfo(D);
3358
1.24M
        if (!Info)
3359
416
          continue;
3360
1.24M
3361
1.24M
        bool Usable = !Info.Constructor->isInvalidDecl();
3362
1.24M
        if (ListInitializing)
3363
2.42k
          Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3364
1.24M
        else
3365
1.24M
          Usable = Usable &&
3366
1.24M
                   
Info.Constructor->isConvertingConstructor(AllowExplicit)1.24M
;
3367
1.24M
        if (Usable) {
3368
547k
          bool SuppressUserConversions = !ConstructorsOnly;
3369
547k
          if (SuppressUserConversions && ListInitializing) {
3370
2.02k
            SuppressUserConversions = false;
3371
2.02k
            if (NumArgs == 1) {
3372
457
              // If the first argument is (a reference to) the target type,
3373
457
              // suppress conversions.
3374
457
              SuppressUserConversions = isFirstArgumentCompatibleWithType(
3375
457
                  S.Context, Info.Constructor, ToType);
3376
457
            }
3377
2.02k
          }
3378
547k
          if (Info.ConstructorTmpl)
3379
70.9k
            S.AddTemplateOverloadCandidate(
3380
70.9k
                Info.ConstructorTmpl, Info.FoundDecl,
3381
70.9k
                /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3382
70.9k
                CandidateSet, SuppressUserConversions,
3383
70.9k
                /*PartialOverloading*/ false, AllowExplicit);
3384
476k
          else
3385
476k
            // Allow one user-defined conversion when user specifies a
3386
476k
            // From->ToType conversion via an static cast (c-style, etc).
3387
476k
            S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3388
476k
                                   llvm::makeArrayRef(Args, NumArgs),
3389
476k
                                   CandidateSet, SuppressUserConversions,
3390
476k
                                   /*PartialOverloading*/ false, AllowExplicit);
3391
547k
        }
3392
1.24M
      }
3393
246k
    }
3394
252k
  }
3395
1.69M
3396
1.69M
  // Enumerate conversion functions, if we're allowed to.
3397
1.69M
  
if (1.69M
ConstructorsOnly1.69M
||
isa<InitListExpr>(From)1.69M
) {
3398
1.69M
  } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3399
4.45k
    // No conversion functions from incomplete types.
3400
1.68M
  } else if (const RecordType *FromRecordType =
3401
1.15M
                 From->getType()->getAs<RecordType>()) {
3402
1.15M
    if (CXXRecordDecl *FromRecordDecl
3403
1.15M
         = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3404
1.15M
      // Add all of the conversion functions as candidates.
3405
1.15M
      const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3406
2.48M
      for (auto I = Conversions.begin(), E = Conversions.end(); I != E; 
++I1.33M
) {
3407
1.33M
        DeclAccessPair FoundDecl = I.getPair();
3408
1.33M
        NamedDecl *D = FoundDecl.getDecl();
3409
1.33M
        CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3410
1.33M
        if (isa<UsingShadowDecl>(D))
3411
11
          D = cast<UsingShadowDecl>(D)->getTargetDecl();
3412
1.33M
3413
1.33M
        CXXConversionDecl *Conv;
3414
1.33M
        FunctionTemplateDecl *ConvTemplate;
3415
1.33M
        if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3416
3.07k
          Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3417
1.32M
        else
3418
1.32M
          Conv = cast<CXXConversionDecl>(D);
3419
1.33M
3420
1.33M
        if (AllowExplicit || 
!Conv->isExplicit()1.32M
) {
3421
1.27M
          if (ConvTemplate)
3422
3.07k
            S.AddTemplateConversionCandidate(
3423
3.07k
                ConvTemplate, FoundDecl, ActingContext, From, ToType,
3424
3.07k
                CandidateSet, AllowObjCConversionOnExplicit, AllowExplicit);
3425
1.26M
          else
3426
1.26M
            S.AddConversionCandidate(
3427
1.26M
                Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
3428
1.26M
                AllowObjCConversionOnExplicit, AllowExplicit);
3429
1.27M
        }
3430
1.33M
      }
3431
1.15M
    }
3432
1.15M
  }
3433
1.69M
3434
1.69M
  bool HadMultipleCandidates = (CandidateSet.size() > 1);
3435
1.69M
3436
1.69M
  OverloadCandidateSet::iterator Best;
3437
1.69M
  switch (auto Result =
3438
1.69M
              CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3439
1.69M
  case OR_Success:
3440
325k
  case OR_Deleted:
3441
325k
    // Record the standard conversion we used and the conversion function.
3442
325k
    if (CXXConstructorDecl *Constructor
3443
36.3k
          = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3444
36.3k
      // C++ [over.ics.user]p1:
3445
36.3k
      //   If the user-defined conversion is specified by a
3446
36.3k
      //   constructor (12.3.1), the initial standard conversion
3447
36.3k
      //   sequence converts the source type to the type required by
3448
36.3k
      //   the argument of the constructor.
3449
36.3k
      //
3450
36.3k
      QualType ThisType = Constructor->getThisType();
3451
36.3k
      if (isa<InitListExpr>(From)) {
3452
412
        // Initializer lists don't have conversions as such.
3453
412
        User.Before.setAsIdentityConversion();
3454
35.9k
      } else {
3455
35.9k
        if (Best->Conversions[0].isEllipsis())
3456
245
          User.EllipsisConversion = true;
3457
35.7k
        else {
3458
35.7k
          User.Before = Best->Conversions[0].Standard;
3459
35.7k
          User.EllipsisConversion = false;
3460
35.7k
        }
3461
35.9k
      }
3462
36.3k
      User.HadMultipleCandidates = HadMultipleCandidates;
3463
36.3k
      User.ConversionFunction = Constructor;
3464
36.3k
      User.FoundConversionFunction = Best->FoundDecl;
3465
36.3k
      User.After.setAsIdentityConversion();
3466
36.3k
      User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3467
36.3k
      User.After.setAllToTypes(ToType);
3468
36.3k
      return Result;
3469
36.3k
    }
3470
288k
    if (CXXConversionDecl *Conversion
3471
288k
                 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3472
288k
      // C++ [over.ics.user]p1:
3473
288k
      //
3474
288k
      //   [...] If the user-defined conversion is specified by a
3475
288k
      //   conversion function (12.3.2), the initial standard
3476
288k
      //   conversion sequence converts the source type to the
3477
288k
      //   implicit object parameter of the conversion function.
3478
288k
      User.Before = Best->Conversions[0].Standard;
3479
288k
      User.HadMultipleCandidates = HadMultipleCandidates;
3480
288k
      User.ConversionFunction = Conversion;
3481
288k
      User.FoundConversionFunction = Best->FoundDecl;
3482
288k
      User.EllipsisConversion = false;
3483
288k
3484
288k
      // C++ [over.ics.user]p2:
3485
288k
      //   The second standard conversion sequence converts the
3486
288k
      //   result of the user-defined conversion to the target type
3487
288k
      //   for the sequence. Since an implicit conversion sequence
3488
288k
      //   is an initialization, the special rules for
3489
288k
      //   initialization by user-defined conversion apply when
3490
288k
      //   selecting the best user-defined conversion for a
3491
288k
      //   user-defined conversion sequence (see 13.3.3 and
3492
288k
      //   13.3.3.1).
3493
288k
      User.After = Best->FinalConversion;
3494
288k
      return Result;
3495
288k
    }
3496
0
    llvm_unreachable("Not a constructor or conversion function?");
3497
0
3498
1.36M
  case OR_No_Viable_Function:
3499
1.36M
    return OR_No_Viable_Function;
3500
0
3501
251
  case OR_Ambiguous:
3502
251
    return OR_Ambiguous;
3503
0
  }
3504
0
3505
0
  llvm_unreachable("Invalid OverloadResult!");
3506
0
}
3507
3508
bool
3509
80
Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3510
80
  ImplicitConversionSequence ICS;
3511
80
  OverloadCandidateSet CandidateSet(From->getExprLoc(),
3512
80
                                    OverloadCandidateSet::CSK_Normal);
3513
80
  OverloadingResult OvResult =
3514
80
    IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3515
80
                            CandidateSet, false, false);
3516
80
3517
80
  if (!(OvResult == OR_Ambiguous ||
3518
80
        (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3519
78
    return false;
3520
2
3521
2
  auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, From);
3522
2
  if (OvResult == OR_Ambiguous)
3523
0
    Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3524
0
        << From->getType() << ToType << From->getSourceRange();
3525
2
  else { // OR_No_Viable_Function && !CandidateSet.empty()
3526
2
    if (!RequireCompleteType(From->getBeginLoc(), ToType,
3527
2
                             diag::err_typecheck_nonviable_condition_incomplete,
3528
2
                             From->getType(), From->getSourceRange()))
3529
2
      Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3530
2
          << false << From->getType() << From->getSourceRange() << ToType;
3531
2
  }
3532
2
3533
2
  CandidateSet.NoteCandidates(
3534
2
                              *this, From, Cands);
3535
2
  return true;
3536
2
}
3537
3538
/// Compare the user-defined conversion functions or constructors
3539
/// of two user-defined conversion sequences to determine whether any ordering
3540
/// is possible.
3541
static ImplicitConversionSequence::CompareKind
3542
compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3543
5.89k
                           FunctionDecl *Function2) {
3544
5.89k
  if (!S.getLangOpts().ObjC || 
!S.getLangOpts().CPlusPlus11160
)
3545
5.73k
    return ImplicitConversionSequence::Indistinguishable;
3546
160
3547
160
  // Objective-C++:
3548
160
  //   If both conversion functions are implicitly-declared conversions from
3549
160
  //   a lambda closure type to a function pointer and a block pointer,
3550
160
  //   respectively, always prefer the conversion to a function pointer,
3551
160
  //   because the function pointer is more lightweight and is more likely
3552
160
  //   to keep code working.
3553
160
  CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3554
160
  if (!Conv1)
3555
0
    return ImplicitConversionSequence::Indistinguishable;
3556
160
3557
160
  CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3558
160
  if (!Conv2)
3559
0
    return ImplicitConversionSequence::Indistinguishable;
3560
160
3561
160
  if (Conv1->getParent()->isLambda() && 
Conv2->getParent()->isLambda()12
) {
3562
12
    bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3563
12
    bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3564
12
    if (Block1 != Block2)
3565
12
      return Block1 ? 
ImplicitConversionSequence::Worse4
3566
12
                    : 
ImplicitConversionSequence::Better8
;
3567
148
  }
3568
148
3569
148
  return ImplicitConversionSequence::Indistinguishable;
3570
148
}
3571
3572
static bool hasDeprecatedStringLiteralToCharPtrConversion(
3573
127M
    const ImplicitConversionSequence &ICS) {
3574
127M
  return (ICS.isStandard() && 
ICS.Standard.DeprecatedStringLiteralToCharPtr126M
) ||
3575
127M
         
(127M
ICS.isUserDefined()127M
&&
3576
127M
          
ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr1.10M
);
3577
127M
}
3578
3579
/// CompareImplicitConversionSequences - Compare two implicit
3580
/// conversion sequences to determine whether one is better than the
3581
/// other or if they are indistinguishable (C++ 13.3.3.2).
3582
static ImplicitConversionSequence::CompareKind
3583
CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3584
                                   const ImplicitConversionSequence& ICS1,
3585
                                   const ImplicitConversionSequence& ICS2)
3586
30.8M
{
3587
30.8M
  // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3588
30.8M
  // conversion sequences (as defined in 13.3.3.1)
3589
30.8M
  //   -- a standard conversion sequence (13.3.3.1.1) is a better
3590
30.8M
  //      conversion sequence than a user-defined conversion sequence or
3591
30.8M
  //      an ellipsis conversion sequence, and
3592
30.8M
  //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3593
30.8M
  //      conversion sequence than an ellipsis conversion sequence
3594
30.8M
  //      (13.3.3.1.3).
3595
30.8M
  //
3596
30.8M
  // C++0x [over.best.ics]p10:
3597
30.8M
  //   For the purpose of ranking implicit conversion sequences as
3598
30.8M
  //   described in 13.3.3.2, the ambiguous conversion sequence is
3599
30.8M
  //   treated as a user-defined sequence that is indistinguishable
3600
30.8M
  //   from any other user-defined conversion sequence.
3601
30.8M
3602
30.8M
  // String literal to 'char *' conversion has been deprecated in C++03. It has
3603
30.8M
  // been removed from C++11. We still accept this conversion, if it happens at
3604
30.8M
  // the best viable function. Otherwise, this conversion is considered worse
3605
30.8M
  // than ellipsis conversion. Consider this as an extension; this is not in the
3606
30.8M
  // standard. For example:
3607
30.8M
  //
3608
30.8M
  // int &f(...);    // #1
3609
30.8M
  // void f(char*);  // #2
3610
30.8M
  // void g() { int &r = f("foo"); }
3611
30.8M
  //
3612
30.8M
  // In C++03, we pick #2 as the best viable function.
3613
30.8M
  // In C++11, we pick #1 as the best viable function, because ellipsis
3614
30.8M
  // conversion is better than string-literal to char* conversion (since there
3615
30.8M
  // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3616
30.8M
  // convert arguments, #2 would be the best viable function in C++11.
3617
30.8M
  // If the best viable function has this conversion, a warning will be issued
3618
30.8M
  // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3619
30.8M
3620
30.8M
  if (S.getLangOpts().CPlusPlus11 && 
!S.getLangOpts().WritableStrings28.1M
&&
3621
30.8M
      hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3622
28.1M
      hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3623
0
    return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3624
0
               ? ImplicitConversionSequence::Worse
3625
0
               : ImplicitConversionSequence::Better;
3626
30.8M
3627
30.8M
  if (ICS1.getKindRank() < ICS2.getKindRank())
3628
143k
    return ImplicitConversionSequence::Better;
3629
30.6M
  if (ICS2.getKindRank() < ICS1.getKindRank())
3630
95.2k
    return ImplicitConversionSequence::Worse;
3631
30.5M
3632
30.5M
  // The following checks require both conversion sequences to be of
3633
30.5M
  // the same kind.
3634
30.5M
  if (ICS1.getKind() != ICS2.getKind())
3635
6
    return ImplicitConversionSequence::Indistinguishable;
3636
30.5M
3637
30.5M
  ImplicitConversionSequence::CompareKind Result =
3638
30.5M
      ImplicitConversionSequence::Indistinguishable;
3639
30.5M
3640
30.5M
  // Two implicit conversion sequences of the same form are
3641
30.5M
  // indistinguishable conversion sequences unless one of the
3642
30.5M
  // following rules apply: (C++ 13.3.3.2p3):
3643
30.5M
3644
30.5M
  // List-initialization sequence L1 is a better conversion sequence than
3645
30.5M
  // list-initialization sequence L2 if:
3646
30.5M
  // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3647
30.5M
  //   if not that,
3648
30.5M
  // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3649
30.5M
  //   and N1 is smaller than N2.,
3650
30.5M
  // even if one of the other rules in this paragraph would otherwise apply.
3651
30.5M
  if (!ICS1.isBad()) {
3652
30.5M
    if (ICS1.isStdInitializerListElement() &&
3653
30.5M
        
!ICS2.isStdInitializerListElement()146
)
3654
60
      return ImplicitConversionSequence::Better;
3655
30.5M
    if (!ICS1.isStdInitializerListElement() &&
3656
30.5M
        
ICS2.isStdInitializerListElement()30.5M
)
3657
32
      return ImplicitConversionSequence::Worse;
3658
30.5M
  }
3659
30.5M
3660
30.5M
  if (ICS1.isStandard())
3661
30.2M
    // Standard conversion sequence S1 is a better conversion sequence than
3662
30.2M
    // standard conversion sequence S2 if [...]
3663
30.2M
    Result = CompareStandardConversionSequences(S, Loc,
3664
30.2M
                                                ICS1.Standard, ICS2.Standard);
3665
374k
  else if (ICS1.isUserDefined()) {
3666
361k
    // User-defined conversion sequence U1 is a better conversion
3667
361k
    // sequence than another user-defined conversion sequence U2 if
3668
361k
    // they contain the same user-defined conversion function or
3669
361k
    // constructor and if the second standard conversion sequence of
3670
361k
    // U1 is better than the second standard conversion sequence of
3671
361k
    // U2 (C++ 13.3.3.2p3).
3672
361k
    if (ICS1.UserDefined.ConversionFunction ==
3673
361k
          ICS2.UserDefined.ConversionFunction)
3674
356k
      Result = CompareStandardConversionSequences(S, Loc,
3675
356k
                                                  ICS1.UserDefined.After,
3676
356k
                                                  ICS2.UserDefined.After);
3677
4.34k
    else
3678
4.34k
      Result = compareConversionFunctions(S,
3679
4.34k
                                          ICS1.UserDefined.ConversionFunction,
3680
4.34k
                                          ICS2.UserDefined.ConversionFunction);
3681
361k
  }
3682
30.5M
3683
30.5M
  return Result;
3684
30.5M
}
3685
3686
// Per 13.3.3.2p3, compare the given standard conversion sequences to
3687
// determine if one is a proper subset of the other.
3688
static ImplicitConversionSequence::CompareKind
3689
compareStandardConversionSubsets(ASTContext &Context,
3690
                                 const StandardConversionSequence& SCS1,
3691
30.5M
                                 const StandardConversionSequence& SCS2) {
3692
30.5M
  ImplicitConversionSequence::CompareKind Result
3693
30.5M
    = ImplicitConversionSequence::Indistinguishable;
3694
30.5M
3695
30.5M
  // the identity conversion sequence is considered to be a subsequence of
3696
30.5M
  // any non-identity conversion sequence
3697
30.5M
  if (SCS1.isIdentityConversion() && 
!SCS2.isIdentityConversion()17.0M
)
3698
15.3M
    return ImplicitConversionSequence::Better;
3699
15.1M
  else if (!SCS1.isIdentityConversion() && 
SCS2.isIdentityConversion()13.4M
)
3700
7.39M
    return ImplicitConversionSequence::Worse;
3701
7.79M
3702
7.79M
  if (SCS1.Second != SCS2.Second) {
3703
4.32M
    if (SCS1.Second == ICK_Identity)
3704
2.95k
      Result = ImplicitConversionSequence::Better;
3705
4.32M
    else if (SCS2.Second == ICK_Identity)
3706
1.03k
      Result = ImplicitConversionSequence::Worse;
3707
4.32M
    else
3708
4.32M
      return ImplicitConversionSequence::Indistinguishable;
3709
3.46M
  } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3710
1.04M
    return ImplicitConversionSequence::Indistinguishable;
3711
2.41M
3712
2.41M
  if (SCS1.Third == SCS2.Third) {
3713
2.41M
    return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? 
Result1.78M
3714
2.41M
                             : 
ImplicitConversionSequence::Indistinguishable628k
;
3715
2.41M
  }
3716
5.10k
3717
5.10k
  if (SCS1.Third == ICK_Identity)
3718
1.65k
    return Result == ImplicitConversionSequence::Worse
3719
1.65k
             ? 
ImplicitConversionSequence::Indistinguishable1.00k
3720
1.65k
             : 
ImplicitConversionSequence::Better649
;
3721
3.44k
3722
3.44k
  if (SCS2.Third == ICK_Identity)
3723
3.44k
    return Result == ImplicitConversionSequence::Better
3724
3.44k
             ? 
ImplicitConversionSequence::Indistinguishable2.83k
3725
3.44k
             : 
ImplicitConversionSequence::Worse613
;
3726
0
3727
0
  return ImplicitConversionSequence::Indistinguishable;
3728
0
}
3729
3730
/// Determine whether one of the given reference bindings is better
3731
/// than the other based on what kind of bindings they are.
3732
static bool
3733
isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3734
1.33M
                             const StandardConversionSequence &SCS2) {
3735
1.33M
  // C++0x [over.ics.rank]p3b4:
3736
1.33M
  //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3737
1.33M
  //      implicit object parameter of a non-static member function declared
3738
1.33M
  //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3739
1.33M
  //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3740
1.33M
  //      lvalue reference to a function lvalue and S2 binds an rvalue
3741
1.33M
  //      reference*.
3742
1.33M
  //
3743
1.33M
  // FIXME: Rvalue references. We're going rogue with the above edits,
3744
1.33M
  // because the semantics in the current C++0x working paper (N3225 at the
3745
1.33M
  // time of this writing) break the standard definition of std::forward
3746
1.33M
  // and std::reference_wrapper when dealing with references to functions.
3747
1.33M
  // Proposed wording changes submitted to CWG for consideration.
3748
1.33M
  if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3749
1.33M
      
SCS2.BindsImplicitObjectArgumentWithoutRefQualifier679k
)
3750
672k
    return false;
3751
662k
3752
662k
  return (!SCS1.IsLvalueReference && 
SCS1.BindsToRvalue419k
&&
3753
662k
          
SCS2.IsLvalueReference419k
) ||
3754
662k
         
(267k
SCS1.IsLvalueReference267k
&&
SCS1.BindsToFunctionLvalue243k
&&
3755
267k
          
!SCS2.IsLvalueReference98
&&
SCS2.BindsToFunctionLvalue78
);
3756
662k
}
3757
3758
/// CompareStandardConversionSequences - Compare two standard
3759
/// conversion sequences to determine whether one is better than the
3760
/// other or if they are indistinguishable (C++ 13.3.3.2p3).
3761
static ImplicitConversionSequence::CompareKind
3762
CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3763
                                   const StandardConversionSequence& SCS1,
3764
                                   const StandardConversionSequence& SCS2)
3765
30.5M
{
3766
30.5M
  // Standard conversion sequence S1 is a better conversion sequence
3767
30.5M
  // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3768
30.5M
3769
30.5M
  //  -- S1 is a proper subsequence of S2 (comparing the conversion
3770
30.5M
  //     sequences in the canonical form defined by 13.3.3.1.1,
3771
30.5M
  //     excluding any Lvalue Transformation; the identity conversion
3772
30.5M
  //     sequence is considered to be a subsequence of any
3773
30.5M
  //     non-identity conversion sequence) or, if not that,
3774
30.5M
  if (ImplicitConversionSequence::CompareKind CK
3775
22.7M
        = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3776
22.7M
    return CK;
3777
7.78M
3778
7.78M
  //  -- the rank of S1 is better than the rank of S2 (by the rules
3779
7.78M
  //     defined below), or, if not that,
3780
7.78M
  ImplicitConversionRank Rank1 = SCS1.getRank();
3781
7.78M
  ImplicitConversionRank Rank2 = SCS2.getRank();
3782
7.78M
  if (Rank1 < Rank2)
3783
2.48M
    return ImplicitConversionSequence::Better;
3784
5.30M
  else if (Rank2 < Rank1)
3785
1.47M
    return ImplicitConversionSequence::Worse;
3786
3.82M
3787
3.82M
  // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3788
3.82M
  // are indistinguishable unless one of the following rules
3789
3.82M
  // applies:
3790
3.82M
3791
3.82M
  //   A conversion that is not a conversion of a pointer, or
3792
3.82M
  //   pointer to member, to bool is better than another conversion
3793
3.82M
  //   that is such a conversion.
3794
3.82M
  if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3795
1.54k
    return SCS2.isPointerConversionToBool()
3796
1.54k
             ? 
ImplicitConversionSequence::Better1.53k
3797
1.54k
             : 
ImplicitConversionSequence::Worse7
;
3798
3.81M
3799
3.81M
  // C++ [over.ics.rank]p4b2:
3800
3.81M
  //
3801
3.81M
  //   If class B is derived directly or indirectly from class A,
3802
3.81M
  //   conversion of B* to A* is better than conversion of B* to
3803
3.81M
  //   void*, and conversion of A* to void* is better than conversion
3804
3.81M
  //   of B* to void*.
3805
3.81M
  bool SCS1ConvertsToVoid
3806
3.81M
    = SCS1.isPointerConversionToVoidPointer(S.Context);
3807
3.81M
  bool SCS2ConvertsToVoid
3808
3.81M
    = SCS2.isPointerConversionToVoidPointer(S.Context);
3809
3.81M
  if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3810
3.32k
    // Exactly one of the conversion sequences is a conversion to
3811
3.32k
    // a void pointer; it's the worse conversion.
3812
3.32k
    return SCS2ConvertsToVoid ? 
ImplicitConversionSequence::Better1.67k
3813
3.32k
                              : 
ImplicitConversionSequence::Worse1.65k
;
3814
3.81M
  } else if (!SCS1ConvertsToVoid && 
!SCS2ConvertsToVoid3.81M
) {
3815
3.81M
    // Neither conversion sequence converts to a void pointer; compare
3816
3.81M
    // their derived-to-base conversions.
3817
3.81M
    if (ImplicitConversionSequence::CompareKind DerivedCK
3818
134
          = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3819
134
      return DerivedCK;
3820
94
  } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3821
94
             !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3822
0
    // Both conversion sequences are conversions to void
3823
0
    // pointers. Compare the source types to determine if there's an
3824
0
    // inheritance relationship in their sources.
3825
0
    QualType FromType1 = SCS1.getFromType();
3826
0
    QualType FromType2 = SCS2.getFromType();
3827
0
3828
0
    // Adjust the types we're converting from via the array-to-pointer
3829
0
    // conversion, if we need to.
3830
0
    if (SCS1.First == ICK_Array_To_Pointer)
3831
0
      FromType1 = S.Context.getArrayDecayedType(FromType1);
3832
0
    if (SCS2.First == ICK_Array_To_Pointer)
3833
0
      FromType2 = S.Context.getArrayDecayedType(FromType2);
3834
0
3835
0
    QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3836
0
    QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3837
0
3838
0
    if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3839
0
      return ImplicitConversionSequence::Better;
3840
0
    else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3841
0
      return ImplicitConversionSequence::Worse;
3842
0
3843
0
    // Objective-C++: If one interface is more specific than the
3844
0
    // other, it is the better one.
3845
0
    const ObjCObjectPointerType* FromObjCPtr1
3846
0
      = FromType1->getAs<ObjCObjectPointerType>();
3847
0
    const ObjCObjectPointerType* FromObjCPtr2
3848
0
      = FromType2->getAs<ObjCObjectPointerType>();
3849
0
    if (FromObjCPtr1 && FromObjCPtr2) {
3850
0
      bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3851
0
                                                          FromObjCPtr2);
3852
0
      bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3853
0
                                                           FromObjCPtr1);
3854
0
      if (AssignLeft != AssignRight) {
3855
0
        return AssignLeft? ImplicitConversionSequence::Better
3856
0
                         : ImplicitConversionSequence::Worse;
3857
0
      }
3858
3.81M
    }
3859
0
  }
3860
3.81M
3861
3.81M
  // Compare based on qualification conversions (C++ 13.3.3.2p3,
3862
3.81M
  // bullet 3).
3863
3.81M
  if (ImplicitConversionSequence::CompareKind QualCK
3864
47
        = CompareQualificationConversions(S, SCS1, SCS2))
3865
47
    return QualCK;
3866
3.81M
3867
3.81M
  if (SCS1.ReferenceBinding && 
SCS2.ReferenceBinding861k
) {
3868
860k
    // Check for a better reference binding based on the kind of bindings.
3869
860k
    if (isBetterReferenceBindingKind(SCS1, SCS2))
3870
385k
      return ImplicitConversionSequence::Better;
3871
474k
    else if (isBetterReferenceBindingKind(SCS2, SCS1))
3872
9.78k
      return ImplicitConversionSequence::Worse;
3873
464k
3874
464k
    // C++ [over.ics.rank]p3b4:
3875
464k
    //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3876
464k
    //      which the references refer are the same type except for
3877
464k
    //      top-level cv-qualifiers, and the type to which the reference
3878
464k
    //      initialized by S2 refers is more cv-qualified than the type
3879
464k
    //      to which the reference initialized by S1 refers.
3880
464k
    QualType T1 = SCS1.getToType(2);
3881
464k
    QualType T2 = SCS2.getToType(2);
3882
464k
    T1 = S.Context.getCanonicalType(T1);
3883
464k
    T2 = S.Context.getCanonicalType(T2);
3884
464k
    Qualifiers T1Quals, T2Quals;
3885
464k
    QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3886
464k
    QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3887
464k
    if (UnqualT1 == UnqualT2) {
3888
464k
      // Objective-C++ ARC: If the references refer to objects with different
3889
464k
      // lifetimes, prefer bindings that don't change lifetime.
3890
464k
      if (SCS1.ObjCLifetimeConversionBinding !=
3891
464k
                                          SCS2.ObjCLifetimeConversionBinding) {
3892
2
        return SCS1.ObjCLifetimeConversionBinding
3893
2
                                           ? 
ImplicitConversionSequence::Worse0
3894
2
                                           : ImplicitConversionSequence::Better;
3895
2
      }
3896
464k
3897
464k
      // If the type is an array type, promote the element qualifiers to the
3898
464k
      // type for comparison.
3899
464k
      if (isa<ArrayType>(T1) && 
T1Quals43
)
3900
37
        T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3901
464k
      if (isa<ArrayType>(T2) && 
T2Quals43
)
3902
37
        T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3903
464k
      if (T2.isMoreQualifiedThan(T1))
3904
136k
        return ImplicitConversionSequence::Better;
3905
327k
      else if (T1.isMoreQualifiedThan(T2))
3906
95.3k
        return ImplicitConversionSequence::Worse;
3907
3.18M
    }
3908
464k
  }
3909
3.18M
3910
3.18M
  // In Microsoft mode, prefer an integral conversion to a
3911
3.18M
  // floating-to-integral conversion if the integral conversion
3912
3.18M
  // is between types of the same size.
3913
3.18M
  // For example:
3914
3.18M
  // void f(float);
3915
3.18M
  // void f(int);
3916
3.18M
  // int main {
3917
3.18M
  //    long a;
3918
3.18M
  //    f(a);
3919
3.18M
  // }
3920
3.18M
  // Here, MSVC will call f(int) instead of generating a compile error
3921
3.18M
  // as clang will do in standard mode.
3922
3.18M
  if (S.getLangOpts().MSVCCompat && 
SCS1.Second == ICK_Integral_Conversion16.1k
&&
3923
3.18M
      
SCS2.Second == ICK_Floating_Integral7.09k
&&
3924
3.18M
      S.Context.getTypeSize(SCS1.getFromType()) ==
3925
2.49k
          S.Context.getTypeSize(SCS1.getToType(2)))
3926
540
    return ImplicitConversionSequence::Better;
3927
3.18M
3928
3.18M
  // Prefer a compatible vector conversion over a lax vector conversion
3929
3.18M
  // For example:
3930
3.18M
  //
3931
3.18M
  // typedef float __v4sf __attribute__((__vector_size__(16)));
3932
3.18M
  // void f(vector float);
3933
3.18M
  // void f(vector signed int);
3934
3.18M
  // int main() {
3935
3.18M
  //   __v4sf a;
3936
3.18M
  //   f(a);
3937
3.18M
  // }
3938
3.18M
  // Here, we'd like to choose f(vector float) and not
3939
3.18M
  // report an ambiguous call error
3940
3.18M
  if (SCS1.Second == ICK_Vector_Conversion &&
3941
3.18M
      
SCS2.Second == ICK_Vector_Conversion460k
) {
3942
460k
    bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
3943
460k
        SCS1.getFromType(), SCS1.getToType(2));
3944
460k
    bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
3945
460k
        SCS2.getFromType(), SCS2.getToType(2));
3946
460k
3947
460k
    if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
3948
39.8k
      return SCS1IsCompatibleVectorConversion
3949
39.8k
                 ? 
ImplicitConversionSequence::Better27.3k
3950
39.8k
                 : 
ImplicitConversionSequence::Worse12.5k
;
3951
3.14M
  }
3952
3.14M
3953
3.14M
  return ImplicitConversionSequence::Indistinguishable;
3954
3.14M
}
3955
3956
/// CompareQualificationConversions - Compares two standard conversion
3957
/// sequences to determine whether they can be ranked based on their
3958
/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3959
static ImplicitConversionSequence::CompareKind
3960
CompareQualificationConversions(Sema &S,
3961
                                const StandardConversionSequence& SCS1,
3962
3.81M
                                const StandardConversionSequence& SCS2) {
3963
3.81M
  // C++ 13.3.3.2p3:
3964
3.81M
  //  -- S1 and S2 differ only in their qualification conversion and
3965
3.81M
  //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3966
3.81M
  //     cv-qualification signature of type T1 is a proper subset of
3967
3.81M
  //     the cv-qualification signature of type T2, and S1 is not the
3968
3.81M
  //     deprecated string literal array-to-pointer conversion (4.2).
3969
3.81M
  if (SCS1.First != SCS2.First || 
SCS1.Second != SCS2.Second3.81M
||
3970
3.81M
      
SCS1.Third != SCS2.Third3.45M
||
SCS1.Third != ICK_Qualification3.45M
)
3971
3.81M
    return ImplicitConversionSequence::Indistinguishable;
3972
396
3973
396
  // FIXME: the example in the standard doesn't use a qualification
3974
396
  // conversion (!)
3975
396
  QualType T1 = SCS1.getToType(2);
3976
396
  QualType T2 = SCS2.getToType(2);
3977
396
  T1 = S.Context.getCanonicalType(T1);
3978
396
  T2 = S.Context.getCanonicalType(T2);
3979
396
  Qualifiers T1Quals, T2Quals;
3980
396
  QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3981
396
  QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3982
396
3983
396
  // If the types are the same, we won't learn anything by unwrapped
3984
396
  // them.
3985
396
  if (UnqualT1 == UnqualT2)
3986
313
    return ImplicitConversionSequence::Indistinguishable;
3987
83
3988
83
  // If the type is an array type, promote the element qualifiers to the type
3989
83
  // for comparison.
3990
83
  if (isa<ArrayType>(T1) && 
T1Quals0
)
3991
0
    T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3992
83
  if (isa<ArrayType>(T2) && 
T2Quals0
)
3993
0
    T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3994
83
3995
83
  ImplicitConversionSequence::CompareKind Result
3996
83
    = ImplicitConversionSequence::Indistinguishable;
3997
83
3998
83
  // Objective-C++ ARC:
3999
83
  //   Prefer qualification conversions not involving a change in lifetime
4000
83
  //   to qualification conversions that do not change lifetime.
4001
83
  if (SCS1.QualificationIncludesObjCLifetime !=
4002
83
                                      SCS2.QualificationIncludesObjCLifetime) {
4003
4
    Result = SCS1.QualificationIncludesObjCLifetime
4004
4
               ? 
ImplicitConversionSequence::Worse1
4005
4
               : 
ImplicitConversionSequence::Better3
;
4006
4
  }
4007
83
4008
101
  while (S.Context.UnwrapSimilarTypes(T1, T2)) {
4009
101
    // Within each iteration of the loop, we check the qualifiers to
4010
101
    // determine if this still looks like a qualification
4011
101
    // conversion. Then, if all is well, we unwrap one more level of
4012
101
    // pointers or pointers-to-members and do it all again
4013
101
    // until there are no more pointers or pointers-to-members left
4014
101
    // to unwrap. This essentially mimics what
4015
101
    // IsQualificationConversion does, but here we're checking for a
4016
101
    // strict subset of qualifiers.
4017
101
    if (T1.getQualifiers().withoutObjCLifetime() ==
4018
101
        T2.getQualifiers().withoutObjCLifetime())
4019
14
      // The qualifiers are the same, so this doesn't tell us anything
4020
14
      // about how the sequences rank.
4021
14
      // ObjC ownership quals are omitted above as they interfere with
4022
14
      // the ARC overload rule.
4023
14
      ;
4024
87
    else if (T2.isMoreQualifiedThan(T1)) {
4025
36
      // T1 has fewer qualifiers, so it could be the better sequence.
4026
36
      if (Result == ImplicitConversionSequence::Worse)
4027
6
        // Neither has qualifiers that are a subset of the other's
4028
6
        // qualifiers.
4029
6
        return ImplicitConversionSequence::Indistinguishable;
4030
30
4031
30
      Result = ImplicitConversionSequence::Better;
4032
51
    } else if (T1.isMoreQualifiedThan(T2)) {
4033
31
      // T2 has fewer qualifiers, so it could be the better sequence.
4034
31
      if (Result == ImplicitConversionSequence::Better)
4035
6
        // Neither has qualifiers that are a subset of the other's
4036
6
        // qualifiers.
4037
6
        return ImplicitConversionSequence::Indistinguishable;
4038
25
4039
25
      Result = ImplicitConversionSequence::Worse;
4040
25
    } else {
4041
20
      // Qualifiers are disjoint.
4042
20
      return ImplicitConversionSequence::Indistinguishable;
4043
20
    }
4044
69
4045
69
    // If the types after this point are equivalent, we're done.
4046
69
    if (S.Context.hasSameUnqualifiedType(T1, T2))
4047
51
      break;
4048
69
  }
4049
83
4050
83
  // Check that the winning standard conversion sequence isn't using
4051
83
  // the deprecated string literal array to pointer conversion.
4052
83
  switch (Result) {
4053
51
  case ImplicitConversionSequence::Better:
4054
27
    if (SCS1.DeprecatedStringLiteralToCharPtr)
4055
0
      Result = ImplicitConversionSequence::Indistinguishable;
4056
27
    break;
4057
51
4058
51
  case ImplicitConversionSequence::Indistinguishable:
4059
4
    break;
4060
51
4061
51
  case ImplicitConversionSequence::Worse:
4062
20
    if (SCS2.DeprecatedStringLiteralToCharPtr)
4063
0
      Result = ImplicitConversionSequence::Indistinguishable;
4064
20
    break;
4065
51
  }
4066
51
4067
51
  return Result;
4068
51
}
4069
4070
/// CompareDerivedToBaseConversions - Compares two standard conversion
4071
/// sequences to determine whether they can be ranked based on their
4072
/// various kinds of derived-to-base conversions (C++
4073
/// [over.ics.rank]p4b3).  As part of these checks, we also look at
4074
/// conversions between Objective-C interface types.
4075
static ImplicitConversionSequence::CompareKind
4076
CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4077
                                const StandardConversionSequence& SCS1,
4078
3.81M
                                const StandardConversionSequence& SCS2) {
4079
3.81M
  QualType FromType1 = SCS1.getFromType();
4080
3.81M
  QualType ToType1 = SCS1.getToType(1);
4081
3.81M
  QualType FromType2 = SCS2.getFromType();
4082
3.81M
  QualType ToType2 = SCS2.getToType(1);
4083
3.81M
4084
3.81M
  // Adjust the types we're converting from via the array-to-pointer
4085
3.81M
  // conversion, if we need to.
4086
3.81M
  if (SCS1.First == ICK_Array_To_Pointer)
4087
10.7k
    FromType1 = S.Context.getArrayDecayedType(FromType1);
4088
3.81M
  if (SCS2.First == ICK_Array_To_Pointer)
4089
10.7k
    FromType2 = S.Context.getArrayDecayedType(FromType2);
4090
3.81M
4091
3.81M
  // Canonicalize all of the types.
4092
3.81M
  FromType1 = S.Context.getCanonicalType(FromType1);
4093
3.81M
  ToType1 = S.Context.getCanonicalType(ToType1);
4094
3.81M
  FromType2 = S.Context.getCanonicalType(FromType2);
4095
3.81M
  ToType2 = S.Context.getCanonicalType(ToType2);
4096
3.81M
4097
3.81M
  // C++ [over.ics.rank]p4b3:
4098
3.81M
  //
4099
3.81M
  //   If class B is derived directly or indirectly from class A and
4100
3.81M
  //   class C is derived directly or indirectly from B,
4101
3.81M
  //
4102
3.81M
  // Compare based on pointer conversions.
4103
3.81M
  if (SCS1.Second == ICK_Pointer_Conversion &&
4104
3.81M
      
SCS2.Second == ICK_Pointer_Conversion2.88k
&&
4105
3.81M
      /*FIXME: Remove if Objective-C id conversions get their own rank*/
4106
3.81M
      
FromType1->isPointerType()2.87k
&&
FromType2->isPointerType()448
&&
4107
3.81M
      
ToType1->isPointerType()448
&&
ToType2->isPointerType()448
) {
4108
448
    QualType FromPointee1
4109
448
      = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4110
448
    QualType ToPointee1
4111
448
      = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4112
448
    QualType FromPointee2
4113
448
      = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4114
448
    QualType ToPointee2
4115
448
      = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4116
448
4117
448
    //   -- conversion of C* to B* is better than conversion of C* to A*,
4118
448
    if (FromPointee1 == FromPointee2 && 
ToPointee1 != ToPointee2444
) {
4119
388
      if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4120
10
        return ImplicitConversionSequence::Better;
4121
378
      else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4122
10
        return ImplicitConversionSequence::Worse;
4123
428
    }
4124
428
4125
428
    //   -- conversion of B* to A* is better than conversion of C* to A*,
4126
428
    if (FromPointee1 != FromPointee2 && 
ToPointee1 == ToPointee24
) {
4127
4
      if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4128
0
        return ImplicitConversionSequence::Better;
4129
4
      else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4130
0
        return ImplicitConversionSequence::Worse;
4131
3.81M
    }
4132
3.81M
  } else if (SCS1.Second == ICK_Pointer_Conversion &&
4133
3.81M
             
SCS2.Second == ICK_Pointer_Conversion2.43k
) {
4134
2.42k
    const ObjCObjectPointerType *FromPtr1
4135
2.42k
      = FromType1->getAs<ObjCObjectPointerType>();
4136
2.42k
    const ObjCObjectPointerType *FromPtr2
4137
2.42k
      = FromType2->getAs<ObjCObjectPointerType>();
4138
2.42k
    const ObjCObjectPointerType *ToPtr1
4139
2.42k
      = ToType1->getAs<ObjCObjectPointerType>();
4140
2.42k
    const ObjCObjectPointerType *ToPtr2
4141
2.42k
      = ToType2->getAs<ObjCObjectPointerType>();
4142
2.42k
4143
2.42k
    if (FromPtr1 && 
FromPtr255
&&
ToPtr155
&&
ToPtr255
) {
4144
55
      // Apply the same conversion ranking rules for Objective-C pointer types
4145
55
      // that we do for C++ pointers to class types. However, we employ the
4146
55
      // Objective-C pseudo-subtyping relationship used for assignment of
4147
55
      // Objective-C pointer types.
4148
55
      bool FromAssignLeft
4149
55
        = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4150
55
      bool FromAssignRight
4151
55
        = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4152
55
      bool ToAssignLeft
4153
55
        = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4154
55
      bool ToAssignRight
4155
55
        = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4156
55
4157
55
      // A conversion to an a non-id object pointer type or qualified 'id'
4158
55
      // type is better than a conversion to 'id'.
4159
55
      if (ToPtr1->isObjCIdType() &&
4160
55
          
(5
ToPtr2->isObjCQualifiedIdType()5
||
ToPtr2->getInterfaceDecl()5
))
4161
1
        return ImplicitConversionSequence::Worse;
4162
54
      if (ToPtr2->isObjCIdType() &&
4163
54
          
(10
ToPtr1->isObjCQualifiedIdType()10
||
ToPtr1->getInterfaceDecl()10
))
4164
5
        return ImplicitConversionSequence::Better;
4165
49
4166
49
      // A conversion to a non-id object pointer type is better than a
4167
49
      // conversion to a qualified 'id' type
4168
49
      if (ToPtr1->isObjCQualifiedIdType() && 
ToPtr2->getInterfaceDecl()4
)
4169
0
        return ImplicitConversionSequence::Worse;
4170
49
      if (ToPtr2->isObjCQualifiedIdType() && 
ToPtr1->getInterfaceDecl()6
)
4171
2
        return ImplicitConversionSequence::Better;
4172
47
4173
47
      // A conversion to an a non-Class object pointer type or qualified 'Class'
4174
47
      // type is better than a conversion to 'Class'.
4175
47
      if (ToPtr1->isObjCClassType() &&
4176
47
          
(1
ToPtr2->isObjCQualifiedClassType()1
||
ToPtr2->getInterfaceDecl()1
))
4177
0
        return ImplicitConversionSequence::Worse;
4178
47
      if (ToPtr2->isObjCClassType() &&
4179
47
          
(2
ToPtr1->isObjCQualifiedClassType()2
||
ToPtr1->getInterfaceDecl()2
))
4180
2
        return ImplicitConversionSequence::Better;
4181
45
4182
45
      // A conversion to a non-Class object pointer type is better than a
4183
45
      // conversion to a qualified 'Class' type.
4184
45
      if (ToPtr1->isObjCQualifiedClassType() && 
ToPtr2->getInterfaceDecl()0
)
4185
0
        return ImplicitConversionSequence::Worse;
4186
45
      if (ToPtr2->isObjCQualifiedClassType() && 
ToPtr1->getInterfaceDecl()0
)
4187
0
        return ImplicitConversionSequence::Better;
4188
45
4189
45
      //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4190
45
      if (S.Context.hasSameType(FromType1, FromType2) &&
4191
45
          
!FromPtr1->isObjCIdType()15
&&
!FromPtr1->isObjCClassType()11
&&
4192
45
          
(ToAssignLeft != ToAssignRight)11
) {
4193
6
        if (FromPtr1->isSpecialized()) {
4194
4
          // "conversion of B<A> * to B * is better than conversion of B * to
4195
4
          // C *.
4196
4
          bool IsFirstSame =
4197
4
              FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4198
4
          bool IsSecondSame =
4199
4
              FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4200
4
          if (IsFirstSame) {
4201
3
            if (!IsSecondSame)
4202
3
              return ImplicitConversionSequence::Better;
4203
1
          } else if (IsSecondSame)
4204
1
            return ImplicitConversionSequence::Worse;
4205
2
        }
4206
2
        return ToAssignLeft? 
ImplicitConversionSequence::Worse1
4207
2
                           : 
ImplicitConversionSequence::Better1
;
4208
2
      }
4209
39
4210
39
      //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4211
39
      if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4212
39
          
(FromAssignLeft != FromAssignRight)30
)
4213
12
        return FromAssignLeft? ImplicitConversionSequence::Better
4214
12
        : 
ImplicitConversionSequence::Worse0
;
4215
3.81M
    }
4216
2.42k
  }
4217
3.81M
4218
3.81M
  // Ranking of member-pointer types.
4219
3.81M
  if (SCS1.Second == ICK_Pointer_Member && 
SCS2.Second == ICK_Pointer_Member235
&&
4220
3.81M
      
FromType1->isMemberPointerType()233
&&
FromType2->isMemberPointerType()24
&&
4221
3.81M
      
ToType1->isMemberPointerType()24
&&
ToType2->isMemberPointerType()24
) {
4222
24
    const MemberPointerType * FromMemPointer1 =
4223
24
                                        FromType1->getAs<MemberPointerType>();
4224
24
    const MemberPointerType * ToMemPointer1 =
4225
24
                                          ToType1->getAs<MemberPointerType>();
4226
24
    const MemberPointerType * FromMemPointer2 =
4227
24
                                          FromType2->getAs<MemberPointerType>();
4228
24
    const MemberPointerType * ToMemPointer2 =
4229
24
                                          ToType2->getAs<MemberPointerType>();
4230
24
    const Type *FromPointeeType1 = FromMemPointer1->getClass();
4231
24
    const Type *ToPointeeType1 = ToMemPointer1->getClass();
4232
24
    const Type *FromPointeeType2 = FromMemPointer2->getClass();
4233
24
    const Type *ToPointeeType2 = ToMemPointer2->getClass();
4234
24
    QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4235
24
    QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4236
24
    QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4237
24
    QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4238
24
    // conversion of A::* to B::* is better than conversion of A::* to C::*,
4239
24
    if (FromPointee1 == FromPointee2 && 
ToPointee1 != ToPointee28
) {
4240
8
      if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4241
2
        return ImplicitConversionSequence::Worse;
4242
6
      else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4243
6
        return ImplicitConversionSequence::Better;
4244
16
    }
4245
16
    // conversion of B::* to C::* is better than conversion of A::* to C::*
4246
16
    if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4247
16
      if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4248
16
        return ImplicitConversionSequence::Better;
4249
0
      else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4250
0
        return ImplicitConversionSequence::Worse;
4251
3.81M
    }
4252
16
  }
4253
3.81M
4254
3.81M
  if (SCS1.Second == ICK_Derived_To_Base) {
4255
41.0k
    //   -- conversion of C to B is better than conversion of C to A,
4256
41.0k
    //   -- binding of an expression of type C to a reference of type
4257
41.0k
    //      B& is better than binding an expression of type C to a
4258
41.0k
    //      reference of type A&,
4259
41.0k
    if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4260
41.0k
        
!S.Context.hasSameUnqualifiedType(ToType1, ToType2)41.0k
) {
4261
95
      if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4262
33
        return ImplicitConversionSequence::Better;
4263
62
      else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4264
25
        return ImplicitConversionSequence::Worse;
4265
41.0k
    }
4266
41.0k
4267
41.0k
    //   -- conversion of B to A is better than conversion of C to A.
4268
41.0k
    //   -- binding of an expression of type B to a reference of type
4269
41.0k
    //      A& is better than binding an expression of type C to a
4270
41.0k
    //      reference of type A&,
4271
41.0k
    if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4272
41.0k
        
S.Context.hasSameUnqualifiedType(ToType1, ToType2)28
) {
4273
28
      if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4274
2
        return ImplicitConversionSequence::Better;
4275
26
      else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4276
2
        return ImplicitConversionSequence::Worse;
4277
3.81M
    }
4278
41.0k
  }
4279
3.81M
4280
3.81M
  return ImplicitConversionSequence::Indistinguishable;
4281
3.81M
}
4282
4283
/// Determine whether the given type is valid, e.g., it is not an invalid
4284
/// C++ class.
4285
12.4M
static bool isTypeValid(QualType T) {
4286
12.4M
  if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4287
3.62M
    return !Record->isInvalidDecl();
4288
8.81M
4289
8.81M
  return true;
4290
8.81M
}
4291
4292
/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4293
/// determine whether they are reference-related,
4294
/// reference-compatible, reference-compatible with added
4295
/// qualification, or incompatible, for use in C++ initialization by
4296
/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4297
/// type, and the first type (T1) is the pointee type of the reference
4298
/// type being initialized.
4299
Sema::ReferenceCompareResult
4300
Sema::CompareReferenceRelationship(SourceLocation Loc,
4301
                                   QualType OrigT1, QualType OrigT2,
4302
                                   bool &DerivedToBase,
4303
                                   bool &ObjCConversion,
4304
8.09M
                                   bool &ObjCLifetimeConversion) {
4305
8.09M
  assert(!OrigT1->isReferenceType() &&
4306
8.09M
    "T1 must be the pointee type of the reference type");
4307
8.09M
  assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4308
8.09M
4309
8.09M
  QualType T1 = Context.getCanonicalType(OrigT1);
4310
8.09M
  QualType T2 = Context.getCanonicalType(OrigT2);
4311
8.09M
  Qualifiers T1Quals, T2Quals;
4312
8.09M
  QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4313
8.09M
  QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4314
8.09M
4315
8.09M
  // C++ [dcl.init.ref]p4:
4316
8.09M
  //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4317
8.09M
  //   reference-related to "cv2 T2" if T1 is the same type as T2, or
4318
8.09M
  //   T1 is a base class of T2.
4319
8.09M
  DerivedToBase = false;
4320
8.09M
  ObjCConversion = false;
4321
8.09M
  ObjCLifetimeConversion = false;
4322
8.09M
  QualType ConvertedT2;
4323
8.09M
  if (UnqualT1 == UnqualT2) {
4324
1.87M
    // Nothing to do.
4325
6.22M
  } else if (isCompleteType(Loc, OrigT2) &&
4326
6.22M
             
isTypeValid(UnqualT1)6.21M
&&
isTypeValid(UnqualT2)6.21M
&&
4327
6.22M
             
IsDerivedFrom(Loc, UnqualT2, UnqualT1)6.21M
)
4328
50.5k
    DerivedToBase = true;
4329
6.17M
  else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4330
6.17M
           
UnqualT2->isObjCObjectOrInterfaceType()42
&&
4331
6.17M
           
Context.canBindObjCObjectType(UnqualT1, UnqualT2)32
)
4332
32
    ObjCConversion = true;
4333
6.17M
  else if (UnqualT2->isFunctionType() &&
4334
6.17M
           
IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)4.67k
)
4335
33
    // C++1z [dcl.init.ref]p4:
4336
33
    //   cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4337
33
    //   function" and T1 is "function"
4338
33
    //
4339
33
    // We extend this to also apply to 'noreturn', so allow any function
4340
33
    // conversion between function types.
4341
33
    return Ref_Compatible;
4342
6.17M
  else
4343
6.17M
    return Ref_Incompatible;
4344
1.92M
4345
1.92M
  // At this point, we know that T1 and T2 are reference-related (at
4346
1.92M
  // least).
4347
1.92M
4348
1.92M
  // If the type is an array type, promote the element qualifiers to the type
4349
1.92M
  // for comparison.
4350
1.92M
  if (isa<ArrayType>(T1) && 
T1Quals5.70k
)
4351
3.29k
    T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4352
1.92M
  if (isa<ArrayType>(T2) && 
T2Quals5.70k
)
4353
3.20k
    T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4354
1.92M
4355
1.92M
  // C++ [dcl.init.ref]p4:
4356
1.92M
  //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4357
1.92M
  //   reference-related to T2 and cv1 is the same cv-qualification
4358
1.92M
  //   as, or greater cv-qualification than, cv2. For purposes of
4359
1.92M
  //   overload resolution, cases for which cv1 is greater
4360
1.92M
  //   cv-qualification than cv2 are identified as
4361
1.92M
  //   reference-compatible with added qualification (see 13.3.3.2).
4362
1.92M
  //
4363
1.92M
  // Note that we also require equivalence of Objective-C GC and address-space
4364
1.92M
  // qualifiers when performing these computations, so that e.g., an int in
4365
1.92M
  // address space 1 is not reference-compatible with an int in address
4366
1.92M
  // space 2.
4367
1.92M
  if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4368
1.92M
      
T1Quals.compatiblyIncludesObjCLifetime(T2Quals)32
) {
4369
20
    if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4370
15
      ObjCLifetimeConversion = true;
4371
20
4372
20
    T1Quals.removeObjCLifetime();
4373
20
    T2Quals.removeObjCLifetime();
4374
20
  }
4375
1.92M
4376
1.92M
  // MS compiler ignores __unaligned qualifier for references; do the same.
4377
1.92M
  T1Quals.removeUnaligned();
4378
1.92M
  T2Quals.removeUnaligned();
4379
1.92M
4380
1.92M
  if (T1Quals.compatiblyIncludes(T2Quals))
4381
1.81M
    return Ref_Compatible;
4382
105k
  else
4383
105k
    return Ref_Related;
4384
1.92M
}
4385
4386
/// Look for a user-defined conversion to a value reference-compatible
4387
///        with DeclType. Return true if something definite is found.
4388
static bool
4389
FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4390
                         QualType DeclType, SourceLocation DeclLoc,
4391
                         Expr *Init, QualType T2, bool AllowRvalues,
4392
1.53M
                         bool AllowExplicit) {
4393
1.53M
  assert(T2->isRecordType() && "Can only find conversions of record types.");
4394
1.53M
  CXXRecordDecl *T2RecordDecl
4395
1.53M
    = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4396
1.53M
4397
1.53M
  OverloadCandidateSet CandidateSet(
4398
1.53M
      DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4399
1.53M
  const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4400
2.45M
  for (auto I = Conversions.begin(), E = Conversions.end(); I != E; 
++I923k
) {
4401
923k
    NamedDecl *D = *I;
4402
923k
    CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4403
923k
    if (isa<UsingShadowDecl>(D))
4404
0
      D = cast<UsingShadowDecl>(D)->getTargetDecl();
4405
923k
4406
923k
    FunctionTemplateDecl *ConvTemplate
4407
923k
      = dyn_cast<FunctionTemplateDecl>(D);
4408
923k
    CXXConversionDecl *Conv;
4409
923k
    if (ConvTemplate)
4410
71
      Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4411
923k
    else
4412
923k
      Conv = cast<CXXConversionDecl>(D);
4413
923k
4414
923k
    // If this is an explicit conversion, and we're not allowed to consider
4415
923k
    // explicit conversions, skip it.
4416
923k
    if (!AllowExplicit && 
Conv->isExplicit()918k
)
4417
8.35k
      continue;
4418
915k
4419
915k
    if (AllowRvalues) {
4420
51.5k
      bool DerivedToBase = false;
4421
51.5k
      bool ObjCConversion = false;
4422
51.5k
      bool ObjCLifetimeConversion = false;
4423
51.5k
4424
51.5k
      // If we are initializing an rvalue reference, don't permit conversion
4425
51.5k
      // functions that return lvalues.
4426
51.5k
      if (!ConvTemplate && 
DeclType->isRValueReferenceType()51.5k
) {
4427
4.05k
        const ReferenceType *RefType
4428
4.05k
          = Conv->getConversionType()->getAs<LValueReferenceType>();
4429
4.05k
        if (RefType && 
!RefType->getPointeeType()->isFunctionType()186
)
4430
179
          continue;
4431
51.3k
      }
4432
51.3k
4433
51.3k
      if (!ConvTemplate &&
4434
51.3k
          S.CompareReferenceRelationship(
4435
51.3k
            DeclLoc,
4436
51.3k
            Conv->getConversionType().getNonReferenceType()
4437
51.3k
              .getUnqualifiedType(),
4438
51.3k
            DeclType.getNonReferenceType().getUnqualifiedType(),
4439
51.3k
            DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4440
51.3k
          Sema::Ref_Incompatible)
4441
47.8k
        continue;
4442
863k
    } else {
4443
863k
      // If the conversion function doesn't return a reference type,
4444
863k
      // it can't be considered for this conversion. An rvalue reference
4445
863k
      // is only acceptable if its referencee is a function type.
4446
863k
4447
863k
      const ReferenceType *RefType =
4448
863k
        Conv->getConversionType()->getAs<ReferenceType>();
4449
863k
      if (!RefType ||
4450
863k
          
(30.8k
!RefType->isLValueReferenceType()30.8k
&&
4451
30.8k
           
!RefType->getPointeeType()->isFunctionType()2
))
4452
832k
        continue;
4453
34.3k
    }
4454
34.3k
4455
34.3k
    if (ConvTemplate)
4456
51
      S.AddTemplateConversionCandidate(
4457
51
          ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4458
51
          /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4459
34.3k
    else
4460
34.3k
      S.AddConversionCandidate(
4461
34.3k
          Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4462
34.3k
          /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4463
34.3k
  }
4464
1.53M
4465
1.53M
  bool HadMultipleCandidates = (CandidateSet.size() > 1);
4466
1.53M
4467
1.53M
  OverloadCandidateSet::iterator Best;
4468
1.53M
  switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4469
1.53M
  case OR_Success:
4470
4.23k
    // C++ [over.ics.ref]p1:
4471
4.23k
    //
4472
4.23k
    //   [...] If the parameter binds directly to the result of
4473
4.23k
    //   applying a conversion function to the argument
4474
4.23k
    //   expression, the implicit conversion sequence is a
4475
4.23k
    //   user-defined conversion sequence (13.3.3.1.2), with the
4476
4.23k
    //   second standard conversion sequence either an identity
4477
4.23k
    //   conversion or, if the conversion function returns an
4478
4.23k
    //   entity of a type that is a derived class of the parameter
4479
4.23k
    //   type, a derived-to-base Conversion.
4480
4.23k
    if (!Best->FinalConversion.DirectBinding)
4481
76
      return false;
4482
4.15k
4483
4.15k
    ICS.setUserDefined();
4484
4.15k
    ICS.UserDefined.Before = Best->Conversions[0].Standard;
4485
4.15k
    ICS.UserDefined.After = Best->FinalConversion;
4486
4.15k
    ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4487
4.15k
    ICS.UserDefined.ConversionFunction = Best->Function;
4488
4.15k
    ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4489
4.15k
    ICS.UserDefined.EllipsisConversion = false;
4490
4.15k
    assert(ICS.UserDefined.After.ReferenceBinding &&
4491
4.15k
           ICS.UserDefined.After.DirectBinding &&
4492
4.15k
           "Expected a direct reference binding!");
4493
4.15k
    return true;
4494
4.15k
4495
4.15k
  case OR_Ambiguous:
4496
22
    ICS.setAmbiguous();
4497
22
    for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4498
66
         Cand != CandidateSet.end(); 
++Cand44
)
4499
44
      if (Cand->Viable)
4500
44
        ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4501
22
    return true;
4502
4.15k
4503
1.52M
  case OR_No_Viable_Function:
4504
1.52M
  case OR_Deleted:
4505
1.52M
    // There was no suitable conversion, or we found a deleted
4506
1.52M
    // conversion; continue with other checks.
4507
1.52M
    return false;
4508
0
  }
4509
0
4510
0
  llvm_unreachable("Invalid OverloadResult!");
4511
0
}
4512
4513
/// Compute an implicit conversion sequence for reference
4514
/// initialization.
4515
static ImplicitConversionSequence
4516
TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4517
                 SourceLocation DeclLoc,
4518
                 bool SuppressUserConversions,
4519
7.26M
                 bool AllowExplicit) {
4520
7.26M
  assert(DeclType->isReferenceType() && "Reference init needs a reference");
4521
7.26M
4522
7.26M
  // Most paths end in a failed conversion.
4523
7.26M
  ImplicitConversionSequence ICS;
4524
7.26M
  ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4525
7.26M
4526
7.26M
  QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4527
7.26M
  QualType T2 = Init->getType();
4528
7.26M
4529
7.26M
  // If the initializer is the address of an overloaded function, try
4530
7.26M
  // to resolve the overloaded function. If all goes well, T2 is the
4531
7.26M
  // type of the resulting function.
4532
7.26M
  if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4533
8.92k
    DeclAccessPair Found;
4534
8.92k
    if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4535
86
                                                                false, Found))
4536
86
      T2 = Fn->getType();
4537
8.92k
  }
4538
7.26M
4539
7.26M
  // Compute some basic properties of the types and the initializer.
4540
7.26M
  bool isRValRef = DeclType->isRValueReferenceType();
4541
7.26M
  bool DerivedToBase = false;
4542
7.26M
  bool ObjCConversion = false;
4543
7.26M
  bool ObjCLifetimeConversion = false;
4544
7.26M
  Expr::Classification InitCategory = Init->Classify(S.Context);
4545
7.26M
  Sema::ReferenceCompareResult RefRelationship
4546
7.26M
    = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4547
7.26M
                                     ObjCConversion, ObjCLifetimeConversion);
4548
7.26M
4549
7.26M
4550
7.26M
  // C++0x [dcl.init.ref]p5:
4551
7.26M
  //   A reference to type "cv1 T1" is initialized by an expression
4552
7.26M
  //   of type "cv2 T2" as follows:
4553
7.26M
4554
7.26M
  //     -- If reference is an lvalue reference and the initializer expression
4555
7.26M
  if (!isRValRef) {
4556
6.68M
    //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4557
6.68M
    //        reference-compatible with "cv2 T2," or
4558
6.68M
    //
4559
6.68M
    // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4560
6.68M
    if (InitCategory.isLValue() && 
RefRelationship == Sema::Ref_Compatible6.12M
) {
4561
486k
      // C++ [over.ics.ref]p1:
4562
486k
      //   When a parameter of reference type binds directly (8.5.3)
4563
486k
      //   to an argument expression, the implicit conversion sequence
4564
486k
      //   is the identity conversion, unless the argument expression
4565
486k
      //   has a type that is a derived class of the parameter type,
4566
486k
      //   in which case the implicit conversion sequence is a
4567
486k
      //   derived-to-base Conversion (13.3.3.1).
4568
486k
      ICS.setStandard();
4569
486k
      ICS.Standard.First = ICK_Identity;
4570
486k
      ICS.Standard.Second = DerivedToBase? 
ICK_Derived_To_Base11.3k
4571
486k
                         : 
ObjCConversion475k
?
ICK_Compatible_Conversion17
4572
475k
                         : 
ICK_Identity475k
;
4573
486k
      ICS.Standard.Third = ICK_Identity;
4574
486k
      ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4575
486k
      ICS.Standard.setToType(0, T2);
4576
486k
      ICS.Standard.setToType(1, T1);
4577
486k
      ICS.Standard.setToType(2, T1);
4578
486k
      ICS.Standard.ReferenceBinding = true;
4579
486k
      ICS.Standard.DirectBinding = true;
4580
486k
      ICS.Standard.IsLvalueReference = !isRValRef;
4581
486k
      ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4582
486k
      ICS.Standard.BindsToRvalue = false;
4583
486k
      ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4584
486k
      ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4585
486k
      ICS.Standard.CopyConstructor = nullptr;
4586
486k
      ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4587
486k
4588
486k
      // Nothing more to do: the inaccessibility/ambiguity check for
4589
486k
      // derived-to-base conversions is suppressed when we're
4590
486k
      // computing the implicit conversion sequence (C++
4591
486k
      // [over.best.ics]p2).
4592
486k
      return ICS;
4593
486k
    }
4594
6.20M
4595
6.20M
    //       -- has a class type (i.e., T2 is a class type), where T1 is
4596
6.20M
    //          not reference-related to T2, and can be implicitly
4597
6.20M
    //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4598
6.20M
    //          is reference-compatible with "cv3 T3" 92) (this
4599
6.20M
    //          conversion is selected by enumerating the applicable
4600
6.20M
    //          conversion functions (13.3.1.6) and choosing the best
4601
6.20M
    //          one through overload resolution (13.3)),
4602
6.20M
    if (!SuppressUserConversions && 
T2->isRecordType()1.74M
&&
4603
6.20M
        
S.isCompleteType(DeclLoc, T2)1.59M
&&
4604
6.20M
        
RefRelationship == Sema::Ref_Incompatible1.59M
) {
4605
1.42M
      if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4606
1.42M
                                   Init, T2, /*AllowRvalues=*/false,
4607
1.42M
                                   AllowExplicit))
4608
724
        return ICS;
4609
6.77M
    }
4610
6.20M
  }
4611
6.77M
4612
6.77M
  //     -- Otherwise, the reference shall be an lvalue reference to a
4613
6.77M
  //        non-volatile const type (i.e., cv1 shall be const), or the reference
4614
6.77M
  //        shall be an rvalue reference.
4615
6.77M
  if (!isRValRef && 
(6.20M
!T1.isConstQualified()6.20M
||
T1.isVolatileQualified()805k
))
4616
5.39M
    return ICS;
4617
1.38M
4618
1.38M
  //       -- If the initializer expression
4619
1.38M
  //
4620
1.38M
  //            -- is an xvalue, class prvalue, array prvalue or function
4621
1.38M
  //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4622
1.38M
  if (RefRelationship == Sema::Ref_Compatible &&
4623
1.38M
      
(596k
InitCategory.isXValue()596k
||
4624
596k
       
(502k
InitCategory.isPRValue()502k
&&
(454k
T2->isRecordType()454k
||
T2->isArrayType()40.1k
)) ||
4625
596k
       
(87.7k
InitCategory.isLValue()87.7k
&&
T2->isFunctionType()47.6k
))) {
4626
508k
    ICS.setStandard();
4627
508k
    ICS.Standard.First = ICK_Identity;
4628
508k
    ICS.Standard.Second = DerivedToBase? 
ICK_Derived_To_Base10.0k
4629
508k
                      : 
ObjCConversion498k
?
ICK_Compatible_Conversion0
4630
498k
                      : ICK_Identity;
4631
508k
    ICS.Standard.Third = ICK_Identity;
4632
508k
    ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4633
508k
    ICS.Standard.setToType(0, T2);
4634
508k
    ICS.Standard.setToType(1, T1);
4635
508k
    ICS.Standard.setToType(2, T1);
4636
508k
    ICS.Standard.ReferenceBinding = true;
4637
508k
    // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4638
508k
    // binding unless we're binding to a class prvalue.
4639
508k
    // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4640
508k
    // allow the use of rvalue references in C++98/03 for the benefit of
4641
508k
    // standard library implementors; therefore, we need the xvalue check here.
4642
508k
    ICS.Standard.DirectBinding =
4643
508k
      S.getLangOpts().CPlusPlus11 ||
4644
508k
      
!(50.6k
InitCategory.isPRValue()50.6k
||
T2->isRecordType()772
);
4645
508k
    ICS.Standard.IsLvalueReference = !isRValRef;
4646
508k
    ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4647
508k
    ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4648
508k
    ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4649
508k
    ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4650
508k
    ICS.Standard.CopyConstructor = nullptr;
4651
508k
    ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4652
508k
    return ICS;
4653
508k
  }
4654
873k
4655
873k
  //            -- has a class type (i.e., T2 is a class type), where T1 is not
4656
873k
  //               reference-related to T2, and can be implicitly converted to
4657
873k
  //               an xvalue, class prvalue, or function lvalue of type
4658
873k
  //               "cv3 T3", where "cv1 T1" is reference-compatible with
4659
873k
  //               "cv3 T3",
4660
873k
  //
4661
873k
  //          then the reference is bound to the value of the initializer
4662
873k
  //          expression in the first case and to the result of the conversion
4663
873k
  //          in the second case (or, in either case, to an appropriate base
4664
873k
  //          class subobject).
4665
873k
  if (!SuppressUserConversions && 
RefRelationship == Sema::Ref_Incompatible324k
&&
4666
873k
      
T2->isRecordType()222k
&&
S.isCompleteType(DeclLoc, T2)109k
&&
4667
873k
      FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4668
107k
                               Init, T2, /*AllowRvalues=*/true,
4669
107k
                               AllowExplicit)) {
4670
3.45k
    // In the second case, if the reference is an rvalue reference
4671
3.45k
    // and the second standard conversion sequence of the
4672
3.45k
    // user-defined conversion sequence includes an lvalue-to-rvalue
4673
3.45k
    // conversion, the program is ill-formed.
4674
3.45k
    if (ICS.isUserDefined() && isRValRef &&
4675
3.45k
        
ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue2.90k
)
4676
0
      ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4677
3.45k
4678
3.45k
    return ICS;
4679
3.45k
  }
4680
870k
4681
870k
  // A temporary of function type cannot be created; don't even try.
4682
870k
  if (T1->isFunctionType())
4683
0
    return ICS;
4684
870k
4685
870k
  //       -- Otherwise, a temporary of type "cv1 T1" is created and
4686
870k
  //          initialized from the initializer expression using the
4687
870k
  //          rules for a non-reference copy initialization (8.5). The
4688
870k
  //          reference is then bound to the temporary. If T1 is
4689
870k
  //          reference-related to T2, cv1 must be the same
4690
870k
  //          cv-qualification as, or greater cv-qualification than,
4691
870k
  //          cv2; otherwise, the program is ill-formed.
4692
870k
  if (RefRelationship == Sema::Ref_Related) {
4693
104k
    // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4694
104k
    // we would be reference-compatible or reference-compatible with
4695
104k
    // added qualification. But that wasn't the case, so the reference
4696
104k
    // initialization fails.
4697
104k
    //
4698
104k
    // Note that we only want to check address spaces and cvr-qualifiers here.
4699
104k
    // ObjC GC, lifetime and unaligned qualifiers aren't important.
4700
104k
    Qualifiers T1Quals = T1.getQualifiers();
4701
104k
    Qualifiers T2Quals = T2.getQualifiers();
4702
104k
    T1Quals.removeObjCGCAttr();
4703
104k
    T1Quals.removeObjCLifetime();
4704
104k
    T2Quals.removeObjCGCAttr();
4705
104k
    T2Quals.removeObjCLifetime();
4706
104k
    // MS compiler ignores __unaligned qualifier for references; do the same.
4707
104k
    T1Quals.removeUnaligned();
4708
104k
    T2Quals.removeUnaligned();
4709
104k
    if (!T1Quals.compatiblyIncludes(T2Quals))
4710
104k
      return ICS;
4711
765k
  }
4712
765k
4713
765k
  // If at least one of the types is a class type, the types are not
4714
765k
  // related, and we aren't allowed any user conversions, the
4715
765k
  // reference binding fails. This case is important for breaking
4716
765k
  // recursion, since TryImplicitConversion below will attempt to
4717
765k
  // create a temporary through the use of a copy constructor.
4718
765k
  if (SuppressUserConversions && 
RefRelationship == Sema::Ref_Incompatible461k
&&
4719
765k
      
(458k
T1->isRecordType()458k
||
T2->isRecordType()185
))
4720
458k
    return ICS;
4721
306k
4722
306k
  // If T1 is reference-related to T2 and the reference is an rvalue
4723
306k
  // reference, the initializer expression shall not be an lvalue.
4724
306k
  if (RefRelationship >= Sema::Ref_Related &&
4725
306k
      
isRValRef87.7k
&&
Init->Classify(S.Context).isLValue()51.5k
)
4726
47.5k
    return ICS;
4727
259k
4728
259k
  // C++ [over.ics.ref]p2:
4729
259k
  //   When a parameter of reference type is not bound directly to
4730
259k
  //   an argument expression, the conversion sequence is the one
4731
259k
  //   required to convert the argument expression to the
4732
259k
  //   underlying type of the reference according to
4733
259k
  //   13.3.3.1. Conceptually, this conversion sequence corresponds
4734
259k
  //   to copy-initializing a temporary of the underlying type with
4735
259k
  //   the argument expression. Any difference in top-level
4736
259k
  //   cv-qualification is subsumed by the initialization itself
4737
259k
  //   and does not constitute a conversion.
4738
259k
  ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4739
259k
                              /*AllowExplicit=*/false,
4740
259k
                              /*InOverloadResolution=*/false,
4741
259k
                              /*CStyle=*/false,
4742
259k
                              /*AllowObjCWritebackConversion=*/false,
4743
259k
                              /*AllowObjCConversionOnExplicit=*/false);
4744
259k
4745
259k
  // Of course, that's still a reference binding.
4746
259k
  if (ICS.isStandard()) {
4747
47.5k
    ICS.Standard.ReferenceBinding = true;
4748
47.5k
    ICS.Standard.IsLvalueReference = !isRValRef;
4749
47.5k
    ICS.Standard.BindsToFunctionLvalue = false;
4750
47.5k
    ICS.Standard.BindsToRvalue = true;
4751
47.5k
    ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4752
47.5k
    ICS.Standard.ObjCLifetimeConversionBinding = false;
4753
211k
  } else if (ICS.isUserDefined()) {
4754
31.2k
    const ReferenceType *LValRefType =
4755
31.2k
        ICS.UserDefined.ConversionFunction->getReturnType()
4756
31.2k
            ->getAs<LValueReferenceType>();
4757
31.2k
4758
31.2k
    // C++ [over.ics.ref]p3:
4759
31.2k
    //   Except for an implicit object parameter, for which see 13.3.1, a
4760
31.2k
    //   standard conversion sequence cannot be formed if it requires [...]
4761
31.2k
    //   binding an rvalue reference to an lvalue other than a function
4762
31.2k
    //   lvalue.
4763
31.2k
    // Note that the function case is not possible here.
4764
31.2k
    if (DeclType->isRValueReferenceType() && 
LValRefType9.43k
) {
4765
37
      // FIXME: This is the wrong BadConversionSequence. The problem is binding
4766
37
      // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4767
37
      // reference to an rvalue!
4768
37
      ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4769
37
      return ICS;
4770
37
    }
4771
31.2k
4772
31.2k
    ICS.UserDefined.After.ReferenceBinding = true;
4773
31.2k
    ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4774
31.2k
    ICS.UserDefined.After.BindsToFunctionLvalue = false;
4775
31.2k
    ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4776
31.2k
    ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4777
31.2k
    ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4778
31.2k
  }
4779
259k
4780
259k
  
return ICS259k
;
4781
259k
}
4782
4783
static ImplicitConversionSequence
4784
TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4785
                      bool SuppressUserConversions,
4786
                      bool InOverloadResolution,
4787
                      bool AllowObjCWritebackConversion,
4788
                      bool AllowExplicit = false);
4789
4790
/// TryListConversion - Try to copy-initialize a value of type ToType from the
4791
/// initializer list From.
4792
static ImplicitConversionSequence
4793
TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4794
                  bool SuppressUserConversions,
4795
                  bool InOverloadResolution,
4796
2.81k
                  bool AllowObjCWritebackConversion) {
4797
2.81k
  // C++11 [over.ics.list]p1:
4798
2.81k
  //   When an argument is an initializer list, it is not an expression and
4799
2.81k
  //   special rules apply for converting it to a parameter type.
4800
2.81k
4801
2.81k
  ImplicitConversionSequence Result;
4802
2.81k
  Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4803
2.81k
4804
2.81k
  // We need a complete type for what follows. Incomplete types can never be
4805
2.81k
  // initialized from init lists.
4806
2.81k
  if (!S.isCompleteType(From->getBeginLoc(), ToType))
4807
0
    return Result;
4808
2.81k
4809
2.81k
  // Per DR1467:
4810
2.81k
  //   If the parameter type is a class X and the initializer list has a single
4811
2.81k
  //   element of type cv U, where U is X or a class derived from X, the
4812
2.81k
  //   implicit conversion sequence is the one required to convert the element
4813
2.81k
  //   to the parameter type.
4814
2.81k
  //
4815
2.81k
  //   Otherwise, if the parameter type is a character array [... ]
4816
2.81k
  //   and the initializer list has a single element that is an
4817
2.81k
  //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4818
2.81k
  //   implicit conversion sequence is the identity conversion.
4819
2.81k
  if (From->getNumInits() == 1) {
4820
666
    if (ToType->isRecordType()) {
4821
412
      QualType InitType = From->getInit(0)->getType();
4822
412
      if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4823
412
          
S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)405
)
4824
7
        return TryCopyInitialization(S, From->getInit(0), ToType,
4825
7
                                     SuppressUserConversions,
4826
7
                                     InOverloadResolution,
4827
7
                                     AllowObjCWritebackConversion);
4828
659
    }
4829
659
    // FIXME: Check the other conditions here: array of character type,
4830
659
    // initializer is a string literal.
4831
659
    if (ToType->isArrayType()) {
4832
11
      InitializedEntity Entity =
4833
11
        InitializedEntity::InitializeParameter(S.Context, ToType,
4834
11
                                               /*Consumed=*/false);
4835
11
      if (S.CanPerformCopyInitialization(Entity, From)) {
4836
11
        Result.setStandard();
4837
11
        Result.Standard.setAsIdentityConversion();
4838
11
        Result.Standard.setFromType(ToType);
4839
11
        Result.Standard.setAllToTypes(ToType);
4840
11
        return Result;
4841
11
      }
4842
2.79k
    }
4843
659
  }
4844
2.79k
4845
2.79k
  // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4846
2.79k
  // C++11 [over.ics.list]p2:
4847
2.79k
  //   If the parameter type is std::initializer_list<X> or "array of X" and
4848
2.79k
  //   all the elements can be implicitly converted to X, the implicit
4849
2.79k
  //   conversion sequence is the worst conversion necessary to convert an
4850
2.79k
  //   element of the list to X.
4851
2.79k
  //
4852
2.79k
  // C++14 [over.ics.list]p3:
4853
2.79k
  //   Otherwise, if the parameter type is "array of N X", if the initializer
4854
2.79k
  //   list has exactly N elements or if it has fewer than N elements and X is
4855
2.79k
  //   default-constructible, and if all the elements of the initializer list
4856
2.79k
  //   can be implicitly converted to X, the implicit conversion sequence is
4857
2.79k
  //   the worst conversion necessary to convert an element of the list to X.
4858
2.79k
  //
4859
2.79k
  // FIXME: We're missing a lot of these checks.
4860
2.79k
  bool toStdInitializerList = false;
4861
2.79k
  QualType X;
4862
2.79k
  if (ToType->isArrayType())
4863
187
    X = S.Context.getAsArrayType(ToType)->getElementType();
4864
2.61k
  else
4865
2.61k
    toStdInitializerList = S.isStdInitializerList(ToType, &X);
4866
2.79k
  if (!X.isNull()) {
4867
2.82k
    for (unsigned i = 0, e = From->getNumInits(); i < e; 
++i1.94k
) {
4868
1.99k
      Expr *Init = From->getInit(i);
4869
1.99k
      ImplicitConversionSequence ICS =
4870
1.99k
          TryCopyInitialization(S, Init, X, SuppressUserConversions,
4871
1.99k
                                InOverloadResolution,
4872
1.99k
                                AllowObjCWritebackConversion);
4873
1.99k
      // If a single element isn't convertible, fail.
4874
1.99k
      if (ICS.isBad()) {
4875
45
        Result = ICS;
4876
45
        break;
4877
45
      }
4878
1.94k
      // Otherwise, look for the worst conversion.
4879
1.94k
      if (Result.isBad() || CompareImplicitConversionSequences(
4880
1.20k
                                S, From->getBeginLoc(), ICS, Result) ==
4881
1.20k
                                ImplicitConversionSequence::Worse)
4882
752
        Result = ICS;
4883
1.94k
    }
4884
875
4885
875
    // For an empty list, we won't have computed any conversion sequence.
4886
875
    // Introduce the identity conversion sequence.
4887
875
    if (From->getNumInits() == 0) {
4888
85
      Result.setStandard();
4889
85
      Result.Standard.setAsIdentityConversion();
4890
85
      Result.Standard.setFromType(ToType);
4891
85
      Result.Standard.setAllToTypes(ToType);
4892
85
    }
4893
875
4894
875
    Result.setStdInitializerListElement(toStdInitializerList);
4895
875
    return Result;
4896
875
  }
4897
1.92k
4898
1.92k
  // C++14 [over.ics.list]p4:
4899
1.92k
  // C++11 [over.ics.list]p3:
4900
1.92k
  //   Otherwise, if the parameter is a non-aggregate class X and overload
4901
1.92k
  //   resolution chooses a single best constructor [...] the implicit
4902
1.92k
  //   conversion sequence is a user-defined conversion sequence. If multiple
4903
1.92k
  //   constructors are viable but none is better than the others, the
4904
1.92k
  //   implicit conversion sequence is a user-defined conversion sequence.
4905
1.92k
  if (ToType->isRecordType() && 
!ToType->isAggregateType()1.09k
) {
4906
733
    // This function can deal with initializer lists.
4907
733
    return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4908
733
                                    /*AllowExplicit=*/false,
4909
733
                                    InOverloadResolution, /*CStyle=*/false,
4910
733
                                    AllowObjCWritebackConversion,
4911
733
                                    /*AllowObjCConversionOnExplicit=*/false);
4912
733
  }
4913
1.18k
4914
1.18k
  // C++14 [over.ics.list]p5:
4915
1.18k
  // C++11 [over.ics.list]p4:
4916
1.18k
  //   Otherwise, if the parameter has an aggregate type which can be
4917
1.18k
  //   initialized from the initializer list [...] the implicit conversion
4918
1.18k
  //   sequence is a user-defined conversion sequence.
4919
1.18k
  if (ToType->isAggregateType()) {
4920
358
    // Type is an aggregate, argument is an init list. At this point it comes
4921
358
    // down to checking whether the initialization works.
4922
358
    // FIXME: Find out whether this parameter is consumed or not.
4923
358
    // FIXME: Exp