Coverage Report

Created: 2021-08-24 07:12

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